Wednesday, 26 November 2014

Extension Method

Introduction

Extension methods are a new feature in C# 3.0. An extension method enables us to add methods to existing types without creating a new derived type, recompiling, or modify the original types. We can say that it extends the functionality of an existing type in .NET. An extension method is a static method to the existing staticclass. We call an extension method in the same general way; there is no difference in calling.

Feature and Property of Extension Methods 

The following list contains basic features and properties of extension methods:
  1. It is a static method.
  2. It must be located in a static class.
  3. It uses the "this" keyword as the first parameter with a type in .NET and this method will be called by a given type instance on the client side.
  4. It also shown by VS intellisense. When we press the dot (.) after a type instance, then it comes in VS intellisense.
  5. An extension method should be in the same namespace as it is used or you need to import the namespace of the class by a using statement.
  6. You can give any name for the class that has an extension method but the class should be static.
  7. If you want to add new methods to a type and you don't have the source code for it, then the solution is to use and implement extension methods of that type.
  8. If you create extension methods that have the same signature methods as the type you are extending, then the extension methods will never be called.

Using the Code

We create an extension method for a string type so string will be specified as a parameter for this extension method and that method will be called by a string instance using the dot operator.


In the above method WordCount(), we are passing a string type with this so it will be called by the stringtype variable, in other words a string instance.
Now we create a static class and two static methods, one for the total word count in a string and another for the total number of characters in a string without a space.


using System;
namespace ExtensionMethodsExample
{
   public static class Extension
    {
       public static int WordCount(this string str)
       {
           string[] userString = str.Split(new char[] { ' ', '.', '?' },
                                       StringSplitOptions.RemoveEmptyEntries);
           int wordCount = userString.Length;
           return wordCount;
       }
       public static int TotalCharWithoutSpace(this string str)
       {
           int totalCharWithoutSpace = 0;
           string[] userString = str.Split(' ');
           foreach (string stringValue in userString)
           {
               totalCharWithoutSpace += stringValue.Length;
           }
           return totalCharWithoutSpace;
       }
    }
}

Now we create an executable program that has a string as an input and uses an extension method to count the total words in that string and the total number of characters in that string then show the result in a console screen.

using System;
namespace ExtensionMethodsExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string userSentance = string.Empty;
            int totalWords = 0;
            int totalCharWithoutSpace = 0;
            Console.WriteLine("Enter the your sentance");
            userSentance = Console.ReadLine();
            //calling Extension Method WordCount
            totalWords = userSentance.WordCount();
            Console.WriteLine("Total number of words is :"+ totalWords);
            //calling Extension Method to count character
            totalCharWithoutSpace = userSentance.TotalCharWithoutSpace();
            Console.WriteLine("Total number of character is :"+totalCharWithoutSpace);
            Console.ReadKey();
        }
    }
}



~Suraj K
Continue Reading →

Tuesday, 25 November 2014

Ordering data in LINQ queries by more than one column

In this post I am going to show how to do ordering when you require to order data by using multiple columns.
In this post, I am going to show how to do ordering when you require to order data by using multiple columns.
By using .Orderby(x=>x.Columnname) in a LINQ query, we can easily order data in a source collection. Most new developers make use of the same function twice.Orderby(x=>x.Columnname).Orderby(x=>x.Columnname) and thinks that will do the ordering in multiple columns.

IEnumerable<Employee> emp = dc.Employees
                                 .OrderBy(x => x.Name)
                                 .OrderBy(x => x.Desc);

But it always does the order by the column you specified in the last OrderBy() method.
Following are two solutions to achieve:

Solution 1

Always make use of ThenBy() after OrderBy() because OrderBy() returns an IOrderedEnumerable which then exposes the methods ThenBy() and ThenByDescending(). This means that we can OrderBy on multiple fields by chaining OrderBy() and ThenBy() together.
IEnumerable<Employee> emp = dc.Employees
                                  .OrderByx => x.Name)
                                 .ThenBy((x => x.Desc);

Solution 2

If you don't want to go for Lambda expression, you can easily achieve multiple ordering:
var emp = from e in dc.Employees
          orderby e.Name, e.Desc
          select e;

As you can see, in the above statement, after order by, you can add multiple columns and do the ordering on the multiple columns.
Continue Reading →

Get Enums in List() object


public enum PaymentType
    {
        Unknown = 0,
        Points = 1,
        Comps = 2,
        Promo = 3,
        Cash = 4,
        UnPaid = 5
    }

public static List<string> paymentTypes = null;

if (paymentTypes == null)
            {

       List<PaymentType> paymentValues = Enum.GetValues(typeof(PaymentType)).Cast<PaymentType>().ToList<PaymentType>();
                paymentTypes = new List<string>();
                foreach (var item in paymentValues)
                {
                    paymentTypes.Add(item.ToString());
                }

            }

Now check output in paymentTypes object.
Continue Reading →

Thursday, 20 November 2014

@@IDENTITY, SCOPE_IDENTITY() , IDENT_CURRENT







Open Microsoft Sql server management studio

Create following two tables and trigger





Now we will execute following commands but within same session (with in same query window)

Result of both select statements is empty. 


Now we will execute following commands but within same session (with in same query window)


Note: Insert statement on table1 will insert value ‘1' in table 1 and trigger will insert value ‘100' in table2


So we have two insert on single insert


One in table1 and another in table2 so we have two scope one is current related to table1 one another is global scope related two table1 and table2


Now open a new query window (new session) and execute the following commands:







 So we have two scenario to compare session and scope
SessionScope
@@IDENTITYSame SessionGlobal scope value
SCOPE_IDENTITY()Same SessionLocal scope value
IDENT_CURRENT()May be differentDepends on table name passed in parameter
Conclusion:
SELECT @@IDENTITY: returns the last identity value generated for any table in the current session, across all scopes(i.e. global scope).

SELECT IDENT_CURRENT : returns the last identity value generated for any table in the current session and the current scope(i.e. local scope).

SELECT SCOPE_IDENTITY(): returns the last identity value generated for a specific table in any session and any scope(i.e. global scope).


Continue Reading →

Monday, 17 November 2014

Events in ASP.NET Master and Content Pages

Both master pages and content pages can contain event handlers for controls. For controls, events are handled locally—a control in a content page raises an event in the content page, and a control in the master page raises an event in the master page. Controls events are not sent from the content page to the master page. Similarly, you cannot handle an event from a master page control in a content page.
In some cases, the same event is raised in both the content and the master page. For example, both pages raise Init and Load events. The general rule for how events are raised is that the initialization events are raised from the innermost control to the outermost one, and all other events are raised from the outermost control to the innermost one. It is helpful to remember that the master page is merged into the content page and treated as a control in the content page.
The following is the sequence in which events occur when a master page is merged with a content page:


  1. Content page PreInit event.
  2. Master page controls Init event.
  3. Content controls Init event.
  4. Master page Init event.
  5. Content page Init event.
  6. Content page Load event.
  7. Master page Load event.
  8. Master page controls Load event.
  9. Content page controls Load event.
  10. Content page PreRender event.
  11. Master page PreRender event.
  12. Master page controls PreRender event.
  13. Content page controls PreRender event.
  14. Master page controls Unload event.
  15. Content page controls Unload event.
  16. Master page Unload event.
  17. Content page Unload event.
The sequence of events in master and content pages rarely is important for you as page developer. However, if you are creating event handlers that depend on the availability of certain controls, you will find it helpful to understand the event sequence in master and content pages.
Continue Reading →

Thursday, 13 November 2014

Private Constructor in C#

Introduction:

Here I will explain what is private constructor in c# with example. Private constructor in c# is used to restrict the class from being instantiated when it contains every member as static.

Description:

Constructor is a special method of a class which will invoke automatically whenever instance or object of class is created. Constructors are responsible for object initialization and memory allocation of its class. If we create any class without constructor, the compiler will automatically create one default constructor for that class. There is always at least one constructor in every class. If you want to know more about constructors check this article constructors in c#.

Private Constructor

Private constructor is a special instance constructor used in a class that contains static member only. If a class has one or more private constructor and no public constructor then other classes is not allowed to create instance of this class this mean we can neither create the object of the class nor it can be inherit by other class. The main purpose of creating private constructor is used to restrict the class from being instantiated when it contains every member as static.

using System;
namespace ConsoleApplication3
{
public class Sample
{
public string param1, param2;
public Sample(string a,string b)
{
param1 = a;
param2 = b;
}
private Sample()  // Private Constructor Declaration
{
Console.WriteLine("Private Constructor with no prameters");
}
}
class Program
{
static void Main(string[] args)
{
// Here we don't have chance to create instace for private constructor
Sample obj = new Sample("Welcome","to Aspdotnet-Suresh");
Console.WriteLine(obj.param1 +" " + obj.param2);
Console.ReadLine();
}
}
}


Output

Welcome to Aspdotnet-Suresh

In above method we can create object of class with parameters will work fine. If create object of class without parameters it will not allow us create.

// it will works fine
Sample obj = new Sample("Welcome","to Aspdotnet-Suresh");
// it will not work because of inaccessability
Sample obj=new Sample();


Important points of private constructor

-      One use of private construct is when we have only static member.
-      Once we provide a constructor that is either private or public or any, the compiler will not allow us to add public constructor without parameters to the class.
-      If we want to create object of class even if we have private constructors then we need to have public constructor along with private constructor

I hope it helps to know about private constructor.
Continue Reading →

Static Class

A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.
Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.
The main features of a static class are:
Creating a static class is therefore much the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated.
Example:
static class CompanyInfo
{
    public static string GetCompanyName() { return "CompanyName"; }
    public static string GetCompanyAddress() { return "CompanyAddress"; }
    //...
}

Another post related Static Class - Click Me
Continue Reading →

Thursday, 6 November 2014

Reference Type And Value Type in C#

Introduction:  The Types in .NET Framework are either treated by Value Type or by Reference Type. A Value Type holds the data within its own memory allocation and a Reference Type contains a pointer to another memory location that holds the real data. Reference Type variables are stored in the heap while Value Type variables are stored in the stack.

   This article will give you a clear insight on what happens when a reference type is passed by value and what would happen when it is passed by reference.

Value Type:

A Value Type stores its contents in memory allocated on the stack. When you created a Value Type, a single space in memory is allocated to store the value and that variable directly holds a value. If you assign it to another variable, the value is copied directly and both variables work independently. Predefined datatypes, structures, enums are also value types, and work in the same way. Value types can be created at compile time and Stored in stack memory, because of this, Garbage collector can't access the stack.

e.g.

int x = 10;

Here the value 10 is stored in an area of memory called the stack.

Reference Type:

Reference Types are used by a reference which holds a reference (address) to the object but not the object itself. Because reference types represent the address of the variable rather than the data itself, assigning a reference variable to another doesn't copy the data. Instead it creates a second copy of the reference, which refers to the same location of the heap as the original value. Reference Type variables are stored in a different area of memory called the heap. This means that when a reference type variable is no longer used, it can be marked for garbage collection. Examples of reference types are Classes, Objects, Arrays, Indexers, Interfaces etc.

e.g.

int[] iArray = new int[20];
In the above code the space required for the 20 integers that make up the array is allocated on the heap.

Write down the following code and try guessing the output without running the program:

class Program{
    
static void Main(string[] args)
    {
           
// Pass reference type by value
           ArrayList arrayList = new ArrayList() { 0, 1, 2, 3 };         
           Console.WriteLine("Pass by Value");
           PassByValue(arrayList);
        
           // What should be the output of below line ??
           Console.WriteLine(arrayList[1]);

   
        arrayList = new ArrayList() { 0, 1, 2, 3 };
           Console.WriteLine("Pass by Reference");
           PassByReference(ref arrayList);

           // What should be the output of below line ??
          Console.WriteLine(arrayList[1]);
          Console.Read();
    }
    private static void PassByValue(ArrayList arrayList)
    {
        Console.WriteLine(arrayList[1]);
        
// Now Change the first position value        
        arrayList[1] = 90;
        arrayList = 
new ArrayList() { 101, 102, 103, 104 };
        Console.WriteLine(arrayList[1]);
    }
    private static void PassByReference(ref ArrayList arrayList)
    {
        Console.WriteLine(arrayList[1]);
        // Now Change the first position value
         arrayList[1] = 90;
         arrayList = 
new ArrayList() { 101, 102, 103, 104 };
        Console.WriteLine(arrayList[1]);
    }
}

Interpretation

First we'll take the case of passing value types by reference.

Let's have a look at the PassbyValue function:


The first line of code obviously would look out for value placed at second index in the arrayList and print out 1. After that, we change the value present at second index to 90. In the third line, since we had passed the reference type by value; it created a copy of original memory block pointing to the original memory location. But as soon we re-create the object, this loses the reference to the original memory location and acts as a different arrayList object then onwards. However, the changes done to the arrayList before the re-creation of object still persists. That's why, when we try to access the second index value, after the PassByValue function, we still get the output as 90.


Now, let's have a look at the Pass by Reference function:



Here too the first line of code output would be the same as reflected by the PassByValue function. The second would again change the value present at the second index to 90. In the third line, since we had passed the reference type by reference, it would just re-initialize its value to the new array (note that here the original memory location is getting new values overwritten here), thus the value for arrayList[1] inside the function would be 102 and after that the newly changed array would be referred everywhere, even outside the function.



Difference:



Conclusion
Passing reference types by Value creates a copy of the memory location and thus it is possible to change the value of the original reference type object inside the function (as soon we re-create that object). Passing reference types by ref doesn't create any copy of the object; it impacts the original reference object.
Continue Reading →

Topics

ADO .Net (2) Ajax (1) Angular Js (17) Angular2 (24) ASP .Net (14) Azure (1) Breeze.js (1) C# (49) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DI (3) Dotnet (21) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (9) Lamda (3) Linq (11) Mongodb (1) MVC (48) NodeJS (7) RDLC (1) Report (1) Sql Server (29) SSIS (3) SSRS (2) UI (1) WCF (12) Web Api (10) Web Service (1) XMl (1)