C# Extension Methods


In this article, let’s know about CSharp Extension methods. Basically this feature was introduced in C# 3.0

Introduction

Extension methods enable you to “add” methods to existing types. They are special kind of static method. They make it possible to extend existing types with additional methods.

Extension methods are declared by specifying this keyword on the first parameter of the methods. Extension methods can only be declared in non-generic, non-nested static classes.

Examples

1. Extend “int” datatype.


public static class MyExtensions
{

  public static bool IsEvenNumber(this int number)

  {
    if (number % 2 == 0)
    {
     return true;
    }
     return false;
  }
 }

To call “IsEvenNumber” extension method from main, consider following code snippet.


class Program
 {
 static void Main(string[] args)
 {
 int i = 45;

 Console.WriteLine(i.IsEvenNumber());
 Console.ReadLine();
 }
 }

 

int-Extension

So in the example above, “IsEvenNumber” has became part of  int datatype and is accessible via intellisense.

2. Extend “string” datatype.


public static class MyExtensions
 {
public static bool IsNullOrEmpty(this string input)
{
if (input == null || input == string.Empty)
{
return true;
}
return false;
}

}

To call “IsNullOrEmpty” extension method from main, consider following code snippet.


class Program
 {
static void Main(string[] args)
{
string str = "";

Console.WriteLine(str.IsNullOrEmpty());
Console.ReadLine();
}
 }

 

string-Extension

So in the example above, “IsNullOrEmpty” has became part of string datatype and is accessible via intellisense.

You can even include the namespance of the Extension methods and reuse them anywhere in your project.

Source Code Download:

Github [Repository Link]

Box.com [Direct Download Link]

Related articles

Step By Step Installing Kali Linux 1.0.6 in Virtualbox


Virtualization is great way to deal with multiple operating systems on a machine.

In this article, let’s see how to install Kali Linux 1.0.6 in Virtual Box. VirtualBox is an open source general-purpose full virtualizer for x86 hardware, targeted at server, desktop and embedded use.

Kali Linux can be downloaded from here and VirtualBox can be downloaded from here. In this article, I am using latest version 4.3.6 of virtualbox.

Steps:

1. After installing virtualbox, open it. Click on New to create a new virtual machine.

2. Enter the name “Kali Linux”, type and version was auto populated. Change version to Linux 2.6/3.x (64 bit) If you are installing 64 bit version of Kali linux. Click Next.

3. Select the memory size from the screen and click Next. Default is 256 MB.

4. From the next screen, you can either create a new virtual hard drive or use existing virtual drive. Default size is 8 GB, but I recommend to keep it to more than 10 GB. Click create button.

5. Now you need to select a hard drive file type. I recommend to keep it default to VDI. Click next.

6. From the “Storage on physical drive”, keep the default option which is “dynamic allocated” and click next.

7. From the “File location and size” window, set the virtual machine drive size to 12 GB and click create. It will create virtual machine.

Now it’s time to install Kali Linux.

8. From the main screen, right click on the newly created virtual machine “kali linux” and select “Settings..”. Click on System >> Processor and check the Enable PAE/NX setting and click OK as shown in the following screenshot. To know more about PAE and NX click here.

9. Then Select Storage >> Controller : IDE from the settings windows and browse for the ISO file for the Kali linux as shown below. Click OK.

10. From main screen, start your newly created virtual machine “Kali Linux”. Select “Graphical Install” from the following screen to start the installation.

11. Select the appropriate language.

12. Select your location.

13. Select your keyboard layout and click continue.

14. Installation will start loading the additional component.

15. Now enter the hostname for your system. Leave it default to “Kali” and click continue.

16. Enter the domain name, leave it blank if not using any specific domain.

17. By default Kali user is Root, so enter password for it and click continue.

18. Use the entire disk for installation, if you are advance user, you can try other options as well.

19. Select and continue the default virtual hard disk which we have created earlier.

20. If you are new user to Kali linux, select “All files in one partition” option, else you can try other options for advance users.

21. Confirm the virtual hard disk changes and click continue.

22. Confirm the changes, select “Yes” and click continue.

23. Installation will start now, it will take sometime around 5-10 minutes.

24. If you want to check newer versions of the software available then select Yes from “Network mirror” screen, else select No and click continue.

25. System will configure packages.

26. If we want to install grub loader then select Yes else select No option.

27. Once you get the “Installation Complete” screen, click continue.

28. Once it finishes, system will restart. Since the default is the right selection, enter to boot into Kali linux.

29. From the following screen, enter username and password.

30. Since you are into Virtualbox, from the device menu, click on “Install Virtualbox guest additions”, a drive is mounted automatically.

31. Copy the “VBoxLinuxAdditions.run” to the root directory using following command


cp VBoxLinuxAdditions.run /root/

32. Change the permissions of the file using command


chmod 755 /root/VBoxLinuxAdditions.run

33. Now, Navigate to the /root directory and execute the file using following command


./VBoxLinuxAdditions.run

34. After successfully installation reboot the system.

Hope this helps. For any queries / doubts, please comment below.

Book Review: “Nuget 2 Essentials” from Packt Publisher


In this post, I am going to review a book Nuget 2 Essentials from Packt Publisher.

Review

Recently I have gone through a book “Nuget to Essentials” and as a developer, I have found it to be a concise, interesting and very useful introduction to Nuget. Authors Damir Arh and Dejan Dakic have covered Nuget Package Manager and related topics very brilliantly.

It is so easy to read and the information is very interesting that each time you turn a page,
you want to learn and know more about Nuget! Every topic in this book is covered with examples. You can download the example code files for all Packt books you have purchased from your account. Since All the examples are written in C# language, only basic knowledge of the language is required to start reading this book.

Here is a list of the positive things, I found about the book:

  • Doesn’t require any prior knowledge about NuGet
  • Example source codes are written in C#
  • All the concepts on real-world examples step by step with a section that explain you the whole process each time in every topic
  • Very comprehensive writing. Authors explained almost everything which makes things clear!
  • Very informative, even if you are a beginner, an intermediate or an advanced user
  • Covers all aspects of using NuGet, from the basics to the advanced scenarios of creating packages and hosting an internal server

After you’ve read the book, you know how to easily find and refer third-party libraries from your projects, create packages from your class libraries for others to use and publish them to the official NuGet gallery and host your own internal NuGet server and publish packages to it.

One thing I have noticed about Packt Publisher is that they offer eBook versions of every book published with PDF and ePub files available, which is very great and added advantage.

Since everything is covered related to Nuget Package Manager along with simple and easily understandable examples, I strongly recommended this book to every .NET developer who wants to learn more about NuGet. A must have ‘Essential‘ book.

Book Details

Language : English
Paperback : 116 pages
Release Date : November 2013
ISBN / ISBN 13 : 178216586X / 9781782165866
Author(s) : Damir Arh, Dejan Dakic
Topics and Technologies : All Books, Open Source

Win Free Copies of the new book NuGet 2 Essentials from Packt Publishing


I recently came across a new book NuGet 2 Essentials from Packt Publishing. You would be pleased to know that I have teamed up with Packt Publishing to organize a Giveaway of the book.

And three lucky winners stand a chance to win 3 digital copies of this book. Keep reading to find out how you can be one of the Lucky Winners.

Overview:

  • Install NuGet in all supported versions of Visual Studio
  • Use NuGet with source control and build servers
  • Create a NuGet package for your own class library
  • Publish your package to the official NuGet gallery
  • Create packages with multi-platform and multi-language support
  • Automatically configure target projects from the packages you create
  • Include custom install and uninstall scripts in your packages
  • Support debugging of your packaged libraries
  • Install your own internal NuGet server
  • Configure NuGet to use different NuGet servers

How to Enter?
All you need to do is head on over to the book page and look through the product description of the book and drop a line via the comments below this post to let us know what interests you the most about this book. It’s that simple.

Winners will get an e-copy of the Book.

Deadline
The contest will close on 31st Dec 2013. Winners will be contacted by email, so be sure to use your real email address when you comment!

Tuple in C# 4.0


A Tuple in C# is an ordered sequence, means each object being of a specific type. It is introduced in C# 4.0 with dynamic programming. It can be useful when returning more than one value from a method.

A Tuple has many items. Each item can have any data type. The Tuple class provides a unified syntax for creating objects with typed fields.

Visual studio provides the intellisense for tuple object depends upon the data type of the item.

Methods


//Creates a new 1-tuple, or singleton.
public class Tuple <T1>

//Creates a new 2-tuple, or pair.
public class Tuple <T1, T2>

//Creates a new 3-tuple, or triple.
public class Tuple <T1, T2, T3>

//Creates a new 4-tuple, or quadruple.
public class Tuple <T1, T2, T3, T4>

//Creates a new 5-tuple, or quintuple.
public class Tuple <T1, T2, T3, T4, T5>

//Creates a new 6-tuple, or sextuple.
public class Tuple <T1, T2, T3, T4, T5, T6>

//Creates a new 7-tuple, or septuple.
public class Tuple <T1, T2, T3, T4, T5, T6, T7>

//Creates a new 8-tuple, or octuple.
public class Tuple <T1, T2, T3, T4, T5, T6, T7, T8>

A Tuple can be instantiated in two ways:

1. Constructor


var tuple = new Tuple<int, string>(10, "Hello World");

2. Static method


var tuple = Tuple.Create(10.10, "Hello World", 50);

Tuples are commonly used in four ways:

1. To represent a single set of data. For example, a tuple can represent a database record, and its components can represent individual fields of the record.

2. To provide easy access to, and manipulation of, a data set.

3. To return multiple values from a method without using out parameters.

4. To pass multiple values to a method through a single parameter.

Example


Tuple<int, string> tuple = new Tuple<int, string>(10, "Hello World!");
Console.WriteLine(tuple.Item1); // will print 10
Console.WriteLine(tuple.Item2); // will print "Hello World!"

Realtime Currency Converter in C# ASP.NET using Yahoo API


In this article, Let’s see how to convert worldwide currencies in realtime using Yahoo API.

Steps:

1. Create a ASP.NET empty project, call it as “RealtimeCurrencyConverterUsingYahooAPI”.

2. Add a webpage called “Default.aspx” to the project.

3. Since we are using jQuery, include the jQuery latest library in the project. Add a reference to it on “Default.aspx” page.


<script src="jquery-1.10.2.js"></script>

4. Add the following webmethod in code behind.


using System;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Web.Services;

[WebMethod]
public static Decimal ConvertCurrency(decimal amount, string fromCurrency, string toCurrency)
{
WebClient client = new WebClient();
Stream response = client.OpenRead(string.Format("http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s={0}{1}=X", fromCurrency.ToUpper(), toCurrency.ToUpper()));
StreamReader reader = new StreamReader(response);
string yahooResponse = reader.ReadLine();
response.Close();
if (!string.IsNullOrWhiteSpace(yahooResponse))
{
string[] values = Regex.Split(yahooResponse, ",");
if (values.Length > 0)
{
decimal rate = System.Convert.ToDecimal(values[1]);
return rate * amount;
}
}
return 0;
}

The webmethod simple get response from yahoo URL. Parses it and returns the calculated result back on the screen.

5. To call this webmethod from “Default.aspx”, just add the following jQuery Code.


<script type="text/javascript">

$(document).ready(function () {
$('#submit').click(function () {
var errormsg = "";
var amount = $('#txtAmount').val();
var fromCurrency = $('#drpFromCurrency').val();
var toCurrency = $('#drpToCurrency').val();
$.ajax({
type: "POST",
url: "Default.aspx/ConvertCurrency",
data: "{amount:" + amount + ",fromCurrency:'" + fromCurrency + "',toCurrency:'" + toCurrency + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('#results').html(amount + ' ' + fromCurrency + ' equals ' + data.d.toFixed(2) + ' ' + toCurrency);
},
error: function (jqXHR, exception) {
$('#results').html(jqXHR.responseText);
}
});
});
});

</script>

If you don’t know how to call a webmethod in jQuery, Please refer this.

6. To style the table, I have just added a stylesheet and referred it in the “Default.aspx” page. You can generate such styles very easily from here.

7. Now run the project and you will find the output like e.g

Source Code Download:

Github [Repository Link]

Box.com [Direct Download Link]

jQuery IP Location Plugin – jqIpLocation Example


In this post, we will see how to get location of an IP address. To achieve this, we will use jquery’s popular plugin “jqIpLocation”.

About jqIpLocation plugin:

jqIpLocation is a jQuery Plugin that returns the location of an IP address in JSON format. You can get country, country code, city name, region name, latitude and longitude information about IP address location.

Now Let’s see how it works with an Example.

1. Create a new asp.net project in Visual Studio, name it as “jqIpLocationPluginExample”.

2. Select the Empty template for web forms.

3. Once the project is created, add a webpage, call it as “Default.aspx”.

4. Download the plugin from here. Extract the rar file and copy the folder to our project.

5. Include the Javascript resources into our Default.aspx page’s <head> section.


<head>
<script src="jqIpLocation/jquery-1.6.3.min.js"></script>
 <script src="jqIpLocation/jqIpLocation.js"></script>
</head>

6. Create a table on page, consider following code snippet.


<table class="CSSTableGenerator">
 <tbody>
 <tr>
 <td>IP</td>
 <td>
 <asp:Label ID="lblIP" runat="server" ClientIDMode="Static"></asp:Label>
 </td>
 </tr>
 <tr>
 <td>Country</td>
 <td>
 <asp:Label ID="lblCountry" runat="server" ClientIDMode="Static"></asp:Label>
 </td>
 </tr>
 <tr>
 <td>Country Code</td>
 <td>
 <asp:Label ID="lblCountryCode" runat="server" ClientIDMode="Static"></asp:Label>
 </td>
 </tr>
 <tr>
 <td>City</td>
 <td>
 <asp:Label ID="lblCity" runat="server" ClientIDMode="Static"></asp:Label>
 </td>
 </tr>
 <tr>
 <td>Region</td>
 <td>
 <asp:Label ID="lblRegion" runat="server" ClientIDMode="Static"></asp:Label>
 </td>
 </tr>
 <tr>
 <td>Latitude</td>
 <td>
 <asp:Label ID="lblLatitude" runat="server" ClientIDMode="Static"></asp:Label>
 </td>
 </tr>
 <tr>
 <td>Longitude</td>
 <td>
 <asp:Label ID="lblLongitude" runat="server" ClientIDMode="Static"></asp:Label>
 </td>
 </tr>
 </tbody>
 </table>

If you observe, I have applied “CSSTableGenerator” class to table, which I have generated from here. I have added it in “StyleSheet1.css” file in the project and included the reference for the same.

7. Add the following Javascript code that will returns you IP Location information in JSON format.


<script type="text/javascript">
 $(function () {

var ipAddress = "213.243.4.20";

$.jqIpLocation({
 ip: ipAddress,
 success: function (location) {
 $("#lblIP").text(ipAddress);
 $("#lblCountry").text(location.countryName);
 $("#lblCountryCode").text(location.countryCode);
 $("#lblCity").text(location.cityName);
 $("#lblRegion").text(location.regionName);
 $("#lblLatitude").text(location.latitude);
 $("#lblLongitude").text(location.longitude);
 }
 });

});
 </script>

8. Now save everything and run the project, you will see following output.

Please note: I have hard coded IP address, you can change and try with some another IP.

Live Demo 1 | Live Demo 2

Source Code Download:

Github [Repository Link]

Box.com [Direct Download Link]