Wednesday 26 November 2014

Extension Method

Introduction
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 static class. 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 and must be located in a static class.
  2. You can give any name for the class that has an extension method but the class should be static.
  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. 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.
  7. 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 string type 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();
        }
    }
}



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.
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<Employeeemp = 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<Employeeemp = 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.Namee.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:







  • The @@identity function returns the last identity created in the same session across all scopes.
  • The scope_identity() function returns the last identity created in the same session and the same scope.
  • The ident_current(name) returns the last identity created for a specific table or view in any session.
  • The identity() function is not used to get an identity, it's used to create an identity in a select...into query.

The session is the database connection. The scope is the current query or the current stored procedure.

A situation where the scope_identity() and the @@identity functions differ, is if you have a trigger on the table. If you have a query that inserts a record, causing the trigger to insert another record somewhere, the scope_identity() function will return the identity created by the query, while the @@identity function will return the identity created by the trigger.

So, normally you would use the scope_identity() function.

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 →

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() { 0123 };         
           Console.WriteLine("Pass by Value");
           PassByValue(arrayList);
        
           // What should be the output of below line ??
           Console.WriteLine(arrayList[1]);

           arrayList = new ArrayList() { 0123 };
           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() { 101102103104 };
        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() { 101102103104 };
        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 →

Static Constructor in C#

Introduction:

Here I will explain what is static constructor in c# with example. Static constructor in c# is used to create static fields of the class and to write the code that needs to be executed only once.

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.

Static Constructor
When we declared constructor as static it will be invoked only once for any number of instances of the class and it’s during the creation of first instance of the class or the first reference to a static member in the class. Static constructor is used to initialize static fields of the class and to write the code that needs to be executed only once.

using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
static Sample()
{
Console.WriteLine("Static Constructor");
}
public Sample()
{
param1 = "Sample";
param2 = "Instance Constructor";
}
}
class Program
{
static void Main(string[] args)
{
// Here Both Static and instance constructors are invoked for first instance
Sample obj=new Sample();
Console.WriteLine(obj.param1 + " " + obj.param2);
// Here only instance constructor will be invoked
Sample obj1 = new Sample();
Console.WriteLine(obj1.param1 +" " + obj1.param2);
Console.ReadLine();
}
}
}


When we run above program we will get output like as shown below
Output
Static Constructor
Sample Instance Constructor
Sample Instance Constructor

Importance points of static constructor

-      Static constructor will not accept any parameters because it is automatically called by CLR.
-      Static constructor will not have any access modifiers.
-      Static constructor will execute automatically whenever we create first instance of class
-      Only one static constructor will allowed.

I hope it helps to know about static constructor. 

Continue Reading →

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives