Wednesday 17 December 2014

LINQ Query Example.

Where Clause
To retrieve a list of accounts where the Name contains “Bhimsen”. 

var ListName = from a in DataContext.Account
                    where a.Name.Contains("Bhimsen")
                    select a;
 foreach (var a in ListName)
 {
  System.Console.WriteLine(a.Name);
 }

To retrieve a list of accounts where the Name contains “Bhimsen” and Address is “New Delhi”.

 var ListNameAdd = from a in DataContext.Account
                    where a.Name.Contains(“Bhimsen")
                    where a.Address1 == "Redmond"
                    select a;

 foreach (var a in ListNameAdd)
 {
  System.Console.WriteLine(a.Name + " " + a.Address1);
 }

Equals Operator
To retrieve a list of contacts where the Name is “Bhimsen”

 var LstEql = from c in DataContext.ContactSet
                     where c.Name.Equals("Bhimsen")
                     select new
                     {
                      c.Name,
                      c.Address1
                     };
 foreach (var c in LstEql)
 {
  System.Console.WriteLine(c.Name + " " + c.Address1_City);
 }

To retrieve a list of contacts where the FamilyStatusCode is 3. This corresponds to the Marital Status option of Divorced.
 var LstEql = from c in DataContext.Contact
                     where c.FamilyStatusCode.Equals(3)
                     select new
                     {
                      c.FirstName,
                      c.LastName,
                      c.Address1
                     };
 foreach (var c in LstEql)
 {
  System.Console.WriteLine(c.FirstName +" " + c.LastName);
 }

Not Equals Operator
To retrieve a list of contacts where the Address is not “Bhagalpur”.

 var NtEql = from c in DataContext.Contact
                 where c.Address != "Bhagalpur"
                 select new
                 {
                  c.FirstName,
                  c.LastName,
                  c.Address1
                 };
 foreach (var c in NtEql)
 {
  System.Console.WriteLine(c.FirstName + " " + c.LastName + " " +
  c.Address1_City);
 }

And , another example :

 var query_ne2 = from c in svcContext.ContactSet
                 where !c.FirstName.Equals("Colin")
                 select new
                 {
                  c.FirstName,
                  c.LastName,
                  c.Address1_City
                 };

 foreach (var c in query_ne2)
 {
  System.Console.WriteLine(c.FirstName + " " +
   c.LastName + " " + c.Address1_City);
 }

Distinct Operator
To retrieve a distinct list of contact names. Although there may be duplicates, each name will be listed only once.

 var DistName = (from c in DataContext.Contact
                       select c.Name).Distinct();
 foreach (var c in DistName)
 {
  System.Console.WriteLine(c);
 }
}

Join and Simple Where Clause
To retrieve the account Name and the contact Name where the account Name contains “Kumar” and the contact Name contains “Bhimsen” and the contact is the Primary Contact for the account.

 var LstJoin = from c in DataContext.Contact
                    join a in DataContext.Account
                    on c.ContactId equals a.PrimaryContactId.Id
                    where a.Name.Contains("Kumar")
                    where c.LastName.Contains("Bhimsen")
                    select new
                    {
                     account_name = a.Name,
                     contact_name = c.LastName
                    };

 foreach (var c in LstJoin)
 {
  System.Console.WriteLine(c.account_name)
 }

Simple Inner Join
To retrieve information about an account and the contact listed as the primary contact for the account.

 var query_join1 = from c in svcContext.ContactSet
                   join a in svcContext.AccountSet
                  on c.ContactId equals a.PrimaryContactId.Id
                   select new
                   {
                    c.FullName,
                    c.Address1_City,
                    a.Name,
                    a.Address1_Name
                   };
 foreach (var c in query_join1)
 {
  System.Console.WriteLine("acct: " +
   c.Name +
   "\t\t\t" +
   "contact: " +
   c.FullName);
 }

Self Join
To retrieve information about accounts where an account is the parent account for an account.

var query_join5 = from a in svcContext.AccountSet
                   join a2 in svcContext.AccountSet
                   on a.ParentAccountId.Id equals a2.AccountId

                   select new
                   {
                    account_name = a.Name,
                    account_city = a.Address1_City
                   };
 foreach (var c in query_join5)
 {
  System.Console.WriteLine(c.account_name + "  " + c.account_city);
 }
}

Double and Multiple Joins
The following sample shows how to retrieve information from account, contact and lead where the contact is the primary contact for the account and the lead was the originating lead for the account.

 var query_join4 = from a in svcContext.AccountSet
                   join c in svcContext.ContactSet
                   on a.PrimaryContactId.Id equals c.ContactId
                   join l in svcContext.LeadSet
                   on a.OriginatingLeadId.Id equals l.LeadId
                   select new
                   {
                    contact_name = c.FullName,
                    account_name = a.Name,
                    lead_name = l.FullName
                   };
 foreach (var c in query_join4)
 {
  System.Console.WriteLine(c.contact_name +
   "  " +
   c.account_name +
   "  " +
   c.lead_name);
 }

The following sample shows how to retrieve account and contact information where an account is the parent account for an account and the contact is the primary contact for the account.
 var query_join6 = from c in svcContext.ContactSet
                   join a in svcContext.AccountSet
                   on c.ContactId equals a.PrimaryContactId.Id
                   join a2 in svcContext.AccountSet
                   on a.ParentAccountId.Id equals a2.AccountId
                   select new
                   {
                    contact_name = c.FullName,
                    account_name = a.Name
                   };
 foreach (var c in query_join6)
 {
  System.Console.WriteLine(c.contact_name + "  " + c.account_name);
 }


Join Using Entity Fields
The following sample shows how to retrieve information about accounts from a list

 var list_join = (from a in svcContext.AccountSet
                  join c in svcContext.ContactSet
                  on a.PrimaryContactId.Id equals c.ContactId
                  where a.Name == "Contoso Ltd" &&
                  a.Address1_Name == "Contoso Pharmaceuticals"
                  select a).ToList();
 foreach (var c in list_join)
 {
  System.Console.WriteLine("Account " + list_join[0].Name
      + " and it's primary contact "
      + list_join[0].PrimaryContactId.Id);
 }

Late-Binding Left Join
The following sample shows a left join. A left join is designed to return parents with and without children from two sources. There is a correlation between parent and child, but no child may actually exist.

 var query_join8 = from a in svcContext.AccountSet
                   join c in svcContext.ContactSet
                   on a.PrimaryContactId.Id equals c.ContactId
                   into gr
                   from c_joined in gr.DefaultIfEmpty()
                   select new
                   {
                    contact_name = c_joined.FullName,
                    account_name = a.Name
                   };
 foreach (var c in query_join8)
 {
  System.Console.WriteLine(c.contact_name + "  " + c.account_name);
 }

Greater Than Operator
The following sample shows how to retrieve a list of contacts with an Anniversary date later than February 5, 2010.

 var query_gt1 = from c in svcContext.ContactSet
                 where c.Anniversary > new DateTime(2010, 2, 5)
                 select new
                 {
                  c.FirstName,
                  c.LastName,
                  c.Address1_City
                 };

 foreach (var c in query_gt1)
 {
  System.Console.WriteLine(c.FirstName + " " +
   c.LastName + " " + c.Address1_City);
 }


The following sample shows how to retrieve contacts with a CreditLimit greater than $20,000.

 var query_gt2 = from c in svcContext.ContactSet
                 where c.CreditLimit.Value > 20000
                 select new
                 {
                  c.FirstName,
                  c.LastName,
                  c.Address1_City
                 };
 foreach (var c in query_gt2)
 {
  System.Console.WriteLine(c.FirstName + " " +
   c.LastName + " " + c.Address1_City);
 }

Greater Than or Equals and Less Than or Equals Operators
The following sample shows how to retrieve contacts with a CreditLimit greater than $200 and less than $400.

 var query_gele1 = from c in svcContext.ContactSet
                   where c.CreditLimit.Value >= 200 &&
                   c.CreditLimit.Value <= 400
                   select new
                   {
                    c.FirstName,
                    c.LastName
                   };
 foreach (var c in query_gele1)
 {
  System.Console.WriteLine(c.FirstName + " " + c.LastName);
 }

Contains Operator
The following sample shows how to retrieve contacts where the Description contains “Alpine”.
 var query_contains1 = from c in svcContext.ContactSet
                       where c.Description.Contains("Alpine")
                       select new
                       {
                        c.FirstName,
                        c.LastName
                       };
 foreach (var c in query_contains1)
 {
  System.Console.WriteLine(c.FirstName + " " + c.LastName);
 }


Not Contain Operator
The following sample shows how to retrieve contacts where the Description does not contain “Coho”.

 var query_contains2 = from c in svcContext.ContactSet
                       where !c.Description.Contains("Coho")
                       select new
                       {
                        c.FirstName,
                        c.LastName
                       };
 foreach (var c in query_contains2)
 {
  System.Console.WriteLine(c.FirstName + " " + c.LastName);
 }

StartsWith and EndsWith Operators
The following sample shows how to retrieve contacts where FirstName starts with “Bri”.

 var query_startswith1 = from c in svcContext.ContactSet
                         where c.FirstName.StartsWith("Bri")
                         select new
                         {
                          c.FirstName,
                          c.LastName
                         };
 foreach (var c in query_startswith1)
 {
  System.Console.WriteLine(c.FirstName + " " + c.LastName);
 }

The following sample shows how to retrieve contacts where LastName ends with “cox”.
 var query_endswith1 = from c in svcContext.ContactSet
                       where c.LastName.EndsWith("cox")
                       select new
                       {
                        c.FirstName,
                        c.LastName
                       };
 foreach (var c in query_endswith1)
 {
  System.Console.WriteLine(c.FirstName + " " + c.LastName);
 }

And and Or Operators
The following sample shows how to retrieve contacts where Address1_City is “Redmond” or “Bellevue” and a CreditLimit that is greater than $200.

 var query_andor1 = from c in svcContext.ContactSet
                    where ((c.Address1_City == "Redmond" ||
                    c.Address1_City == "Bellevue") &&
                    (c.CreditLimit.Value != null &&
                    c.CreditLimit.Value >= 200))
                    select c;

 foreach (var c in query_andor1)
 {
  System.Console.WriteLine(c.LastName + ", " + c.FirstName + " " +
   c.Address1_City + " " + c.CreditLimit.Value);
 }


OrderBy Operator
The following sample shows how to retrieve contacts ordered by CreditLimit in descending order.

 var query_orderby1 = from c in svcContext.ContactSet
                      where !c.CreditLimit.Equals(null)
                      orderby c.CreditLimit descending
                      select new
                      {
                       limit = c.CreditLimit,
                       first = c.FirstName,
                       last = c.LastName
                      };
 foreach (var c in query_orderby1)
 {
  System.Console.WriteLine(c.limit.Value + " " +
   c.last + ", " + c.first);
 }

The following sample shows how to retrieve contacts ordered by LastName in descending order and FirstName in ascending order.

 var query_orderby2 = from c in svcContext.ContactSet
                      orderby c.LastName descending,
                      c.FirstName ascending
                      select new
                      {
                       first = c.FirstName,
                       last = c.LastName
                      };

 foreach (var c in query_orderby2)
 {
  System.Console.WriteLine(c.last + ", " + c.first);
 }

First and Single Operators
The following sample shows how to retrieve only the first contact record returned and retrieve only one contact record that matches the criterion.

using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 Contact firstcontact = svcContext.ContactSet.First();

 Contact singlecontact = svcContext.ContactSet.Single(c => c.ContactId == _contactId1);
 System.Console.WriteLine(firstcontact.LastName + ", " +
  firstcontact.FirstName + " is the first contact");
 System.Console.WriteLine("==========================");
 System.Console.WriteLine(singlecontact.LastName + ", " +
  singlecontact.FirstName + " is the single contact");
}

Retrieving Formatted Values
The following sample shows how to retrieve the label for an optionset option, in this case the value for the current record status.


using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 var list_retrieve1 = from c in svcContext.ContactSet
                      where c.ContactId == _contactId1
                      select new { StatusReason = c.FormattedValues["statuscode"] };
 foreach (var c in list_retrieve1)
 {
  System.Console.WriteLine("Status: " + c.StatusReason);
 }
}

Skip and Take Operators without Paging
The following sample shows how to retrieve just two records after skipping two records where the LastName is not “Parker” using the Skip and Takeoperators.

 var query_skip = (from c in svcContext.ContactSet
                   where c.LastName != "Parker"
                   orderby c.FirstName
                   select new
                       {
                        last = c.LastName,
                        first = c.FirstName
                       }).Skip(2).Take(2);
 foreach (var c in query_skip)
 {
  System.Console.WriteLine(c.first + " " + c.last);
 }

FirstOrDefault and SingleOrDefault Operators
The FirstOrDefault operator returns the first element of a sequence, or a default value if no element is found. The SingleOrDefault operator returns a single, specific element of a sequence, or a default value if that element is not found. The following sample shows how to use these operators.

 Contact firstorcontact = svcContext.ContactSet.FirstOrDefault();

 Contact singleorcontact = svcContext.ContactSet
  .SingleOrDefault(c => c.ContactId == _contactId1);


 System.Console.WriteLine(firstorcontact.FullName +
  " is the first contact");
 System.Console.WriteLine("==========================");
 System.Console.WriteLine(singleorcontact.FullName +
  " is the single contact");

Self Join with a Condition on the Linked Entity
The following sample shows how to retrieve the names of two accounts where one account is the parent account of the other.

 var query_joincond = from a1 in svcContext.AccountSet
                      join a2 in svcContext.AccountSet
                      on a1.ParentAccountId.Id equals a2.AccountId
                      where a2.AccountId == _accountId1
                      select new { Account = a1, Parent = a2 };
 foreach (var a in query_joincond)
 {
  System.Console.WriteLine(a.Account.Name + " " + a.Parent.Name);
 }


Transformation in the Where Clause
The following sample shows how to retrieve a specific contact where the anniversary date is later than January 1, 2010.

 var query_wheretrans = from c in svcContext.ContactSet
                        where c.ContactId == _contactId1 &&
                        c.Anniversary > DateTime.Parse("1/1/2010")
                        select new
                        {
                         c.FirstName,
                         c.LastName
                        };
 foreach (var c in query_wheretrans)
 {
  System.Console.WriteLine(c.FirstName + " " + c.LastName);
 }


Paging Sort
The following sample shows a multi-column sort with an extra condition.

 var query_pagingsort1 = (from c in svcContext.ContactSet
                          where c.LastName != "Parker"
                          orderby c.LastName ascending,
                          c.FirstName descending
                          select new { c.FirstName, c.LastName })
                          .Skip(2).Take(2);
 foreach (var c in query_pagingsort1)
 {
  System.Console.WriteLine(c.FirstName + " " + c.LastName);
 }

The following sample shows a paging sort where the column being sorted is different from the column being retrieved.

 var query_pagingsort2 = (from c in svcContext.ContactSet
                          where c.LastName != "Parker"
                          orderby c.FirstName descending
                          select new { c.FirstName }).Skip(2).Take(2);
 foreach (var c in query_pagingsort2)
 {
  System.Console.WriteLine(c.FirstName);
 }

The following sample shows how to retrieve just the first 10 records.

 var query_pagingsort3 = (from c in svcContext.ContactSet
                          where c.LastName.StartsWith("W")
                          orderby c.MiddleName ascending,
                          c.FirstName descending
                          select new
                          {
                           c.FirstName,
                           c.MiddleName,
                           c.LastName
                          }).Take(10);
 foreach (var c in query_pagingsort3)
 {
  System.Console.WriteLine(c.FirstName + " " +
   c.MiddleName + " " + c.LastName);
 }

Retrieve Related Entity Columns for 1 to N Relationships
The following sample shows how to retrieve columns from related account and contact records.

 var query_retrieve1 = from c in svcContext.ContactSet
                       join a in svcContext.AccountSet
                       on c.ContactId equals a.PrimaryContactId.Id
                       where c.ContactId != _contactId1
                       select new { Contact = c, Account = a };
 foreach (var c in query_retrieve1)
 {
  System.Console.WriteLine("Acct: " + c.Account.Name +
   "\t\t" + "Contact: " + c.Contact.FullName);
 }

Use .Value to Retrieve the Value of an Attribute
The following sample shows usage of Value to access the value of an attribute.

 var query_value = from c in svcContext.ContactSet
                   where c.ContactId != _contactId2
                   select new
                   {
                    ContactId = c.ContactId != null ?
                     c.ContactId.Value : Guid.Empty,
                    NumberOfChildren = c.NumberOfChildren != null ?
                     c.NumberOfChildren.Value : default(int),
                    CreditOnHold = c.CreditOnHold != null ?
                     c.CreditOnHold.Value : default(bool),
                    Anniversary = c.Anniversary != null ?
                     c.Anniversary.Value : default(DateTime)
                   };

 foreach (var c in query_value)
 {
  System.Console.WriteLine(c.ContactId + " " + c.NumberOfChildren +
   " " + c.CreditOnHold + " " + c.Anniversary);
 }

Multiple Projections, New Data Type Casting to Different Types
The following sample shows multiple projections and how to cast values to a different type.

 var query_projections = from c in svcContext.ContactSet
                         where c.ContactId == _contactId1
                         && c.NumberOfChildren != null &&
                         c.Anniversary.Value != null
                         select new
                         {
                          Contact = new Contact {
                           LastName = c.LastName,
                           NumberOfChildren = c.NumberOfChildren
                          },
                          NumberOfChildren = (double)c.NumberOfChildren,
                          Anniversary = c.Anniversary.Value.AddYears(1),
                         };
 foreach (var c in query_projections)
 {
  System.Console.WriteLine(c.Contact.LastName + " " +
   c.NumberOfChildren + " " + c.Anniversary);
 }

GetAttributeValue Method
The following sample shows how to use the GetAttributeValue method.

 var query_getattrib = from c in svcContext.ContactSet
                       where c.GetAttributeValue<Guid>("contactid") != _contactId1
                       select new
                       {
                        ContactId = c.GetAttributeValue<Guid?>("contactid"),
                        NumberOfChildren = c.GetAttributeValue<int?>("numberofchildren"),
                        CreditOnHold = c.GetAttributeValue<bool?>("creditonhold"),
                        Anniversary = c.GetAttributeValue<DateTime?>("anniversary"),
                       };

 foreach (var c in query_getattrib)
 {
  System.Console.WriteLine(c.ContactId + " " + c.NumberOfChildren +
   " " + c.CreditOnHold + " " + c.Anniversary);
 }

Math Methods
The following sample shows how to use various Math methods.

 var query_math = from c in svcContext.ContactSet
                  where c.ContactId != _contactId2
                  && c.Address1_Latitude != null &&
                  c.Address1_Longitude != null
                  select new
                  {
                   Round = Math.Round(c.Address1_Latitude.Value),
                   Floor = Math.Floor(c.Address1_Latitude.Value),
                   Ceiling = Math.Ceiling(c.Address1_Latitude.Value),
                   Abs = Math.Abs(c.Address1_Latitude.Value),
                  };
 foreach (var c in query_math)
 {
  System.Console.WriteLine(c.Round + " " + c.Floor +
   " " + c.Ceiling + " " + c.Abs);
 }

Use Multiple Select and Where Clauses
The following sample shows multiple select and where clauses using a method-based query syntax.

 var query_multiselect = svcContext.IncidentSet
                        .Where(i => i.IncidentId != _incidentId1)
                        .Select(i => i.incident_customer_accounts)
                        .Where(a => a.AccountId != _accountId2)
                        .Select(a => a.account_primary_contact)
                        .OrderBy(c => c.FirstName)
                        .Select(c => c.ContactId);
 foreach (var c in query_multiselect)
 {
  System.Console.WriteLine(c.GetValueOrDefault());
 }

Use SelectMany
The following sample shows how to use the SelectMany Method.

 var query_selectmany = svcContext.ContactSet
                        .Where(c => c.ContactId != _contactId2)
                        .SelectMany(c => c.account_primary_contact)
                        .OrderBy(a => a.Name);
 foreach (var c in query_selectmany)
 {
  System.Console.WriteLine(c.AccountId + " " + c.Name);
 }

String Operations
The following sample shows how to use various String methods.

 var query_string = from c in svcContext.ContactSet
                    where c.ContactId == _contactId2
                    select new
                    {
                     IndexOf = c.FirstName.IndexOf("contact"),
                     Insert = c.FirstName.Insert(1, "Insert"),
                     Remove = c.FirstName.Remove(1, 1),
                     Substring = c.FirstName.Substring(1, 1),
                     ToUpper = c.FirstName.ToUpper(),
                     ToLower = c.FirstName.ToLower(),
                     TrimStart = c.FirstName.TrimStart(),
                     TrimEnd = c.FirstName.TrimEnd(),
                    };

 foreach (var c in query_string)
 {
  System.Console.WriteLine(c.IndexOf + "\n" + c.Insert + "\n" +
   c.Remove + "\n" + c.Substring + "\n"
                           + c.ToUpper + "\n" + c.ToLower +
                           "\n" + c.TrimStart + " " + c.TrimEnd);
 }

Use Two Where Clauses
The following sample shows how to use two Where clauses.

 var query_twowhere = from a in svcContext.AccountSet
                      join c in svcContext.ContactSet
                      on a.PrimaryContactId.Id equals c.ContactId
                      where c.LastName == "Smith" && c.CreditOnHold != null
                      where a.Name == "Contoso Ltd"
                      orderby a.Name
                      select a;
 foreach (var c in query_twowhere)
 {
  System.Console.WriteLine(c.AccountId + " " + c.Name);
 }
}

LoadProperty to Retrieve Related Records
The following sample shows how to LoadProperty to access related records.

Contact benAndrews = svcContext.ContactSet.Where(c => c.FullName == "Ben Andrews").FirstOrDefault();
if (benAndrews != null)
{
 //benAndrews.Contact_Tasks is null until LoadProperty is used.
 svcContext.LoadProperty(benAndrews, "Contact_Tasks");
 Task benAndrewsFirstTask = benAndrews.Contact_Tasks.FirstOrDefault();
 if (benAndrewsFirstTask != null)
 {
  Console.WriteLine("Ben Andrews first task with Subject: '{0}' retrieved.", benAndrewsFirstTask.Subject);
 }



Basic LINQ Query Operations (C#)
Visual Studio 2013
Other Versions

17 out of 19 rated this helpful - Rate this topic
This topic gives a brief introduction to LINQ query expressions and some of the typical kinds of operations that you perform in a query. More detailed information is in the following topics:
LINQ Query Expressions (C# Programming Guide)
Standard Query Operators Overview
Walkthrough: Writing Queries in C# (LINQ)
  Note
If you already are familiar with a query language such as SQL or XQuery, you can skip most of this topic. Read about the "from clause" in the next section to learn about the order of clauses in LINQ query expressions.
Obtaining a Data Source
In a LINQ query, the first step is to specify the data source. In C# as in most programming languages a variable must be declared before it can be used. In a LINQ query, thefrom clause comes first in order to introduce the data source (customers) and the range variable (cust).
C#
//queryAllCustomers is an IEnumerable<Customer>
var queryAllCustomers = from cust in customers
                        select cust;
The range variable is like the iteration variable in a foreach loop except that no actual iteration occurs in a query expression. When the query is executed, the range variable will serve as a reference to each successive element in customers. Because the compiler can infer the type of cust, you do not have to specify it explicitly. Additional range variables can be introduced by a let clause. For more information, see let clause (C# Reference).
  Note
For non-generic data sources such as ArrayList, the range variable must be explicitly typed. For more information, see How to: Query an ArrayList with LINQ and from clause (C# Reference).

Filtering
Probably the most common query operation is to apply a filter in the form of a Boolean expression. The filter causes the query to return only those elements for which the expression is true. The result is produced by using the where clause. The filter in effect specifies which elements to exclude from the source sequence. In the following example, only those customers who have an address in London are returned.
C#
var queryLondonCustomers = from cust in customers
                           where cust.City == "London"
                           select cust;
You can use the familiar C# logical AND and OR operators to apply as many filter expressions as necessary in the where clause. For example, to return only customers from "London" AND whose name is "Devon" you would write the following code:
C#
where cust.City=="London" && cust.Name == "Devon"
To return customers from London or Paris, you would write the following code:
C#
where cust.City == "London" || cust.City == "Paris"
For more information, see where clause (C# Reference).
Ordering
Often it is convenient to sort the returned data. The orderby clause will cause the elements in the returned sequence to be sorted according to the default comparer for the type being sorted. For example, the following query can be extended to sort the results based on the Name property. Because Name is a string, the default comparer performs an alphabetical sort from A to Z.
C#
var queryLondonCustomers3 =
    from cust in customers
    where cust.City == "London"
    orderby cust.Name ascending
    select cust;
To order the results in reverse order, from Z to A, use the orderby…descending clause.
For more information, see orderby clause (C# Reference).
Grouping
The group clause enables you to group your results based on a key that you specify. For example you could specify that the results should be grouped by the City so that all customers from London or Paris are in individual groups. In this case, cust.City is the key.
C#
// queryCustomersByCity is an IEnumerable<IGrouping<string, Customer>>
  var queryCustomersByCity =
      from cust in customers
      group cust by cust.City;

  // customerGroup is an IGrouping<string, Customer>
  foreach (var customerGroup in queryCustomersByCity)
  {
      Console.WriteLine(customerGroup.Key);
      foreach (Customer customer in customerGroup)
      {
          Console.WriteLine("    {0}", customer.Name);
      }
  }
When you end a query with a group clause, your results take the form of a list of lists. Each element in the list is an object that has a Key member and a list of elements that are grouped under that key. When you iterate over a query that produces a sequence of groups, you must use a nested foreach loop. The outer loop iterates over each group, and the inner loop iterates over each group's members.
If you must refer to the results of a group operation, you can use the into keyword to create an identifier that can be queried further. The following query returns only those groups that contain more than two customers:
C#
// custQuery is an IEnumerable<IGrouping<string, Customer>>
var custQuery =
    from cust in customers
    group cust by cust.City into custGroup
    where custGroup.Count() > 2
    orderby custGroup.Key
    select custGroup;

Joining
Join operations create associations between sequences that are not explicitly modeled in the data sources. For example you can perform a join to find all the customers and distributors who have the same location. In LINQ the join clause always works against object collections instead of database tables directly.
C#
var innerJoinQuery =
    from cust in customers
    join dist in distributors on cust.City equals dist.City
    select new { CustomerName = cust.Name, DistributorName = dist.Name };
In LINQ you do not have to use join as often as you do in SQL because foreign keys in LINQ are represented in the object model as properties that hold a collection of items. For example, a Customer object contains a collection of Order objects. Rather than performing a join, you access the orders by using dot notation:
from order in Customer.Orders...
For more information, see join clause (C# Reference).
Selecting (Projections)
The select clause produces the results of the query and specifies the "shape" or type of each returned element. For example, you can specify whether your results will consist of complete Customer objects, just one member, a subset of members, or some completely different result type based on a computation or new object creation. When theselect clause produces something other than a copy of the source element, the operation is called a projection. The use of projections to transform data is a powerful capability of LINQ query expressions. For more information, see Data Transformations with LINQ (C#) and select clause (C# Reference).


Monday 15 December 2014

ASP.NET Interview Question

What is ASP.NET? 
ASP.NET is a specification developed by Microsoft to create dynamic Web applications, Web sites, and Web services. It is a part of .NET Framework. You can create ASP.NET applications in most of the .NET compatible languages, such as Visual Basic, C#, and J#. The ASP.NET compiles the Web pages and provides much better performance than scripting languages, such as VBScript. The Web Forms support to create powerful forms-based Web pages. You can use ASP.NET Web server controls to create interactive Web applications. With the help of Web server controls, you can easily create a Web application.

What is ASP.NET page life cycle? Also describe the page life cycle events.
In ASP.NET, when we execute a Web page, it passes through the following stages, which are known as Web page lifecycle.
1.  Init ( page Initialisation)
2.  Load
3.  Render
4.  Unload

And these stages can be further classified into different page life cycle events. Which are following :

Init (Page Initialisation):

a. PreInit :  During this stage, ASP.NET makes sure the page either parsed or compiled and a cached version of the page can be sent in response. During this stage sets the Request and Response page properties and the page check the page request is either a postback or a new request
b. Init : During this stage, the page initialize and the control's Unique Id property are set.
c. Init Complete : It indicates that page identification completed and initialized.

Load : During this stage, if the request is postback, the control properties are loaded without loading the view state and control state otherwise loads the view state. Its events can be classified as follows:
a. Preload
b. Load
c. Load Complete

Validation: During this stage, the controls are validated.

Postback event handling : During this stage, if the request is a postback, handles the event.

Render :  During this stage, the page invokes the render method to each control for return the output. At this stage all the Asp.net control converts into HTML control and loads the .dll of the website or an application.

Unload:  During this stage, When the page is completely rendered and sent to the client, the page is unloaded.

What is State Management? How many ways are there to maintain a state in .NET? 
State management is used to store information requests. The state management is used to trace the information or data that affect the state of the applications. There are two ways to maintain a state in .NET, Client-Based state management and Server-Based state management. The following techniques can be used to implement the Client-Based state management:
1. View State
2. Hidden Fields
3. Cookies
4. Query Strings
5. Control State

The following techniques can be used to implement Server-Based state management:
1. Application State
2. Session State

What is IIS? 
Internet Information Services (IIS) is created by Microsoft to provide Internet-based services to ASP.NET Web applications. It makes your computer to work as a Web server and provides the functionality to develop and deploy Web applications on the server. IIS handles the request and response cycle on the Web server. It also offers the services of SMTP and FrontPage server extensions. The SMTP is used to send emails and use FrontPage server extensions to get the dynamic features of IIS, such as form handler.

What is Query String? What are its advantages and limitations? 
The Query String helps in sending the page information to the server. The Query String has the following advantages:
1. Every browser works with Query Strings.
2. It does not require server resources and so does not exert any kind of burden on the server.

The following are the limitations of Query String:
1. Information must be within the limit because URL does not support many characters.
2. Information is clearly visible to the user, which leads to security threats.

What is actually returned from server to the browser when a browser requests an .aspx file and the file is displayed?
When a browser requests an .aspx file then the server returns a response, which is rendered into a HTML string.

How can you display all validation messages in one control?
The ValidationSummary control displays all validation messages in one control.
Which two new properties are added in ASP.NET 4.0 Page class? The two new properties added in the Page class are MetaKeyword and MetaDescription.

What is tracing? Where is it used? 
Tracing displays the details about how the code was executed. It refers to collecting information about the application while it is running. Tracing information can help you to troubleshoot an application. It enables you to record information in various log files about the errors that might occur at run time. You can analyze these log files to find the cause of the errors. In .NET, we have objects called Trace Listeners. A listener is an object that gets the trace output and stores it to different places, such as a window, a file on your locale drive, or a SQL Server. The System.Diagnostics namespace contains the predefined interfaces, classes, and structures that are used for tracing. It supplies two classes, Trace and Debug, which allow you to write errors and logs related to the application execution. Trace listeners are objects that collect the output of tracing processes.

What is the difference between authentication and authorization? 
Authentication verifies the identity of a user and authorization is a process where you can check whether or not the identity has access rights to the system. In other words, you can say that authentication is a procedure of getting some credentials from the users and verify the user's identity against those credentials. Authorization is a procedure of granting access of particular resources to an authenticated user. You should note that authentication always takes place before authorization.

How can you register a custom server control to a Web page? 
You can register a custom server control to a Web page using the @Register directive.

Which ASP.NET objects encapsulate the state of the client and the browser?
The Session object encapsulates the state of the client and browser.

Differentiate globalization and localization. 
The globalization is a technique to identify the specific part of a Web application that is different for different languages and make separate that portion from the core of the Web application. The localization is a procedure of configuring a Web application to be supported for a specific language or locale.

What is ViewState? 
The ViewState is a feature used by ASP.NET Web page to store the value of a page and its controls just before posting the page. Once the page is posted, the first task by the page processing is to restore the ViewState to get the values of the controls.

Which method is used to force all the validation controls to run? 
The Page.Validate() method is used to force all the validation controls to run and to perform validation.

Which method has been introduced in ASP.NET 4.0 to redirect a page permanently?
The RedirectPermanent() method added in ASP.NET 4.0 to redirect a page permanently. The following code snippet is an example of the RedirectPermanent() method: RedirectPermanent("/path/Aboutus.aspx");

How can you send an email message from an ASP.NET Web page?
You can use the System.Net.Mail.MailMessage and the System.Net.Mail.SmtpMail classes to send an email in your Web pages. In order to send an email through your mail server, you need to create an object of the SmtpClient class and set the server name, port, and credentials.

What is the difference between the Response.Write() and Response.Output.Write() methods?
The Response.Write() method allows you to write the normal output; whereas, the Response.Output.Write() method allows you to write the formatted output.

What does the Orientation property do in a Menu control? 
Orientation property of the Menu control sets the horizontal or vertical display of a menu on a Web page. By default, the orientation is vertical.

Differentiate between client-side and server-side validations in Web pages. 
Client-side validations take place at the client end with the help of JavaScript and VBScript before the Web page is sent to the server. On the other hand, server-side validations take place at the server end.

How does a content page differ from a master page?
A content page does not have complete HTML source code; whereas a master page has complete HTML source code inside its source file.
Suppose you want an ASP.NET function (client side) executed on the MouseOver event of a button.

Where do you add an event handler?
The event handler is added to the Add() method of the Attributes property.

What is the default timeout for a Cookie? 
The default time duration for a Cookie is 30 minutes.

What are HTTP handlers in ASP.NET?
HTTP handlers, as the name suggests, are used to handle user requests for Web application resources. They are the backbone of the request-response model of Web applications. There is a specific event handler to handle the request for each user request type and send back the corresponding response object. Each user requests to the IIS Web server flows through the HTTP pipeline, which refers to a series of components (HTTP modules and HTTP handlers) to process the request. HTTP modules act as filters to process the request as it passes through the HTTP pipeline. The request, after passing through the HTTP modules, is assigned to an HTTP handler that determines the response of the server to the user request. The response then passes through the HTTP modules once again and is then sent back to the user. You can define HTTP handlers in the <httpHandlers> element of a configuration file. The <add> element tag is used to add new handlers and the <remove> element tag is used to remove existing handlers. To create an HTTP handler, you need to define a class that implements the IHttpHandler interface.

What are the events that happen when a client requests an ASP.NET page from IIS server?
The following events happen when a client requests an ASP.NET page from the IIS server:
1. User requests for an application resource.
2. The integrated request-processing pipeline receives the first user request.
3. Response objects are created for each user request.
4. An object of the HttpApplication class is created and allocated to the Request object.
5. The HttpApplication class processes the user request.

Explain file-based dependency and key-based dependency. 
In file-based dependency, you have to depend on a file that is saved in a disk. In key-based dependency, you have to depend on another cached item.

How can you implement the postback property of an ASP.NET control?
You need to set the AutoPostBack property to True to implement the PostBack property of controls.

Explain how Cookies work. Give an example of Cookie abuse.
The server tells the browser to put some files in a cookie, and the client then sends all the cookies for the domain in each request. An example of cookie abuse is large cookies affecting the network traffic.

Explain login controls. 
Login controls are built-in controls in ASP.Net for providing a login solution to ASP.NET application. The login controls use the membership system to authenticate a user credentials for a Web site. There are many controls in login controls.
1. ChangePassword control - Allows users to change their password.
2. CreateUserWizard control - Provides an interface to the user to register for that Web site.
3. Login control - Provides an interface for user authentication. It consists of a set of controls, such as TextBox, Label, Button, CheckBox, HyperLink.
4. LoginView control - Displays appropriate information to different users according to the user's status.
5. LoginStatus control - Shows a login link to users, who are not authenticated and logout link, who are authenticated
6. LoginName control - Displays a user name, if the user logs in.
7. PasswordRecovery control - Allows users to get back the password through an e-mail, if they forget.

What is the use of PlaceHolder control? Can we see it at runtime? 
The PlaceHolder control acts as a container for those controls that are dynamically generated at runtime. We cannot see it at runtime because it does not produce any visible output. It used only as a container.

What setting must be added in the configuration file to deny a particular user from accessing the secured resources? 
To deny a particular user form accessing the secured resources, the web.config file must contain the following code:
<authorization >
<deny users="username" />
</authorization>

What are the event handlers that can be included in the Global.asax file? 
The Global.asax file contains some of the following important event handlers:
1. Application_Error
2. Application_Start
3. Application_End
4. Session_Start
5. Session_End

What is the difference between page-level caching and fragment caching?
In the page-level caching, an entire Web page is cached; whereas, in the fragment caching, a part of the Web page, such as a user control added to the Web page, is cached.

List of all templates of the Repeater control.
The Repeater control contains the following templates:
1. ItemTemplate
2. AlternatingltemTemplate
3. SeparatorTemplate
4. HeaderTemplate
5. FooterTemplate


Saturday 6 December 2014

SQL Server Interview Question

What is the difference between primary key and unique key ?
1. A primary key does not allows a null value where as unique key allows null value.
2. Primary key created cluster index by default. Whereas unique key creates non clustered index.
3. There are only one primary key in any table while there are multiple unique key in a single table.

What is the difference between implicit and explicit transaction?
1. Implicit transaction is auto commit, there are no beginning and ending of the transaction while explicit transaction has beginning and end and rollback command.
2. In explicit transaction, if error occurs between transaction then it can be roll back where as it is not possible in implicit transaction.

What is #temp and @table variable in SQL server?

#Temp table : it is temporary table that is generally created to store session specific data.  #Temp table is visible only to the current scope. Generally ,the table gets clear up automatically when the current procedure goes out of scope.
@Table variable : @Table variable is similar to temporary table except with more flexibility. It is not physically stored in hard disk. We should choose it when we need to store less than 100 records.

How are transaction used?
Transaction allows you to group SQL command into single unit. The transaction begins with certain task and ends when all task within it are completed. The transaction completes successfully only if all command within it complete successfully. The whole things fail if command fails. The begin transaction, Rollback and commit transaction are used to work within transaction.

What is difference between procedure and function?
1. Procedure may have 0 to n return parameter. Whereas function return single parameter.
2. Procedure may have input and output parameter where as function may have only input parameter.
3. A procedure can use select and DML statement, where as function can use only select statement
4. Procedure can use Try … catch for error handling where as function cannot use it.
5. Procedure can call function where function cannot call procedure.
6. Procedure can go for transaction management where as function can’t.

What is the difference between clustered and non-clustered index?
Clustered Index : A clustered index is a special type of index where records are physically stored in a table. There may be a single clustered index in a table. And leaf node of clustered index contains a data page.
Non-Clustered Index : A non-clustered index is a special type of index where logical order of index does not  match a physical stored order of the row on the disk. It contains pointer to the data that stored in data page.

Or simply we can say that.

Clustered Index: Clustered index physically rearrange the data that users inserts in your tables. It is nothing but a dictionary type data where actual data remains.

Non-Clustered Index: It Non-Clustered Index contains pointers to the data that is stored in the data page. It is a kind of index backside of the book where you see only the reference of a kind of data.

What is Trigger?

A trigger is special type of store procedure which executes automatically in place of or after data modification (Insert, Update, Delete).  It allows us to execute a batch of SQL code when either an insert, update or delete command is executed against a specific table. There are four types of trigger.  They are :-
1. Insert
2. Update
3. Delete
4. Instead of

What is cursor?
A cursor is a database object used by application to maintain data in a set on row by row basis.

What is constraints?
SQL Server uses constraints to enforce limitations on the data that can be entered into a particular column in table. There are following types of constraints.
Unique, Default, Check, Primary Key, Foreign Key, Not Null.

What is difference between Truncate and Delete?
1. In TRUNCATE we cannot rollback. Where as in DELETE we can rollback.
2. Delete keep the lock over each row where Truncate keeps the lock on table not on all the row.
3. Counter of the Identity column is reset in Truncate where it is not reset in Delete.
4. Trigger is not fired in Truncate where as trigger is fired in Delete.
5. Truncate delete whole record of table at a time where as delete does it one by one.

How do you implement one-to-one, one-to-many and many-to-many relationships while designing tables?
One-to-One relationship can be implemented as a single table and rarely as two tables with primary and foreign key relationships.
One-to-Many relationships are implemented by splitting the data into two tables with primary key and foreign key relationships.
Many-to-Many relationships are implemented using a junction table with the keys from both the tables forming the composite primary key of the junction table.

What is difference between union All statement and Union?

The main difference between union All statement and Union is Union All statement is much faster then union. Because Union all statement does not look for duplicate rows, but on the other hand union statement does not look for duplicate rows, where or not exist.




Thursday 4 December 2014

Interview Question on C# Programming concept

What is data type and how many types of data types are  in .Net ?
A data type is a data storage format that can contain a specific type or range value. Whenever you declare variable, each variable must be assigned a specific data type. Some common data types includes integers, float, character etc.
There are two types of data type are available in .Net , they are :
1. Value Type
2. Reference type
Value Type : Value type refers to the data type that contains the data. Means that, the exact value or data is directly stored in this data type. It means when you assign a value type variable to another variable, It copies the value not reference. It stores the value in stack memory. Int, float, char are value type variable.
Reference Type : Refers to the data type that can access data by reference . Reference is an address where the actual data are stores. It stores in the heap memory. String, array, object etc are reference type.

What is difference between int and int32 ?
There are no difference between  int and int32. Int32 is a class and int is an alias name for it.

What is difference between constant and read only variable?
Constent : 
1. Constant are dealt with at compiler time.
2. Constant support value type variable.
3. Constant should be used when it is very unlikely that the value will ever change.
Read only : 
1. Read only veriable are evaluated at runtime.
2. It can hold reference type variable.
3. Read only variable should be used when runtime calculation is required.

What is difference between Boxing and unboxing ?
When value type is converted to an object(reference) type are known as boxing and a value type are known as unboxing.
Ex :
 int I =123;
object obj = i // (boxing )
int  I = int (obj)   // (unboxing )

What is the difference between value type and reference type?
1. Value type memory allocates in stack where as reference type memory manages in heap.
2. Value type contains variable and reference type directly stores in memory.

What is tuple? How can you instantiate a tuple?
Tupple is a fix size collection that can have element of either same or different data type . Similar to array a user must have to specify the size of tupple at the time of declaration. Tupple are allowed to hold up from 1 to 8 element and if there are more than 8 element. Then 8th element can be defined as another tupple. Tupple can be specified as parameter or return type of the method.
There are two method to instantiate a tupple. They are :
1. New Operator : Ex Tuple<string, int> t = new Tuple<string, int> (“Bhimsen”, 2)
2. Create Factory Method : Ex     Tuple<int,int> t = Tuple.Crete<int,int> (2, 4)

What is Enumeration? 
Enumeration is defined as a value type that consists of a set of named values. These values are constants and are called enumerators. An enumeration type is declared using the enum keyword. Each enumerator in an enumeration is associated with an underlying type that is set, by default, on the enumerator. The following is an example that creates an enumeration to store different varieties of fruits:
 enum Fruits {Mango, Apple, orange, Guava};
 In the preceding example, an enumeration Fruits is created, where number 0 is associated with Mango, number .

What is delegate ?
A delegate is similar to class that is used for storing the reference to a method and invoking that method at runtime as required. A deligate can hold the reference of only those method whose signature are same as that of delegate.
When delegate contains the reference of multiple method are called multicast delegate. Some of the examples of delegates are type-safe functions, pointers, or callbacks.

What is an array?
 An array is defined as a homogeneous(identical) collection of elements, stored at contiguous memory locations, which can be referred by the same variable name. All the elements of an array variable can be accessed by index values. An Index value specifies the position of a particular element in an array variable. Index number starts from 0.
EX :            int  arr[5] = {6,20,13,40,55}
In the above emample “arr” is the name of array. [5] is the size of array. And index number for element  6 is 0, 20 at 1st index, 13 at 2nd index and so on.

What is ArrayList?
Array is whose size can increase and decrease dynamically. Array list can hold item of different types.  As Array list can increase and decrease size dynamically you do not have to use the REDIM keyword. You can access any item in array using the INDEX value of the array position.

What is a Hashtable? 
Hashtable is a data structure that implements the IDictionary interface. It is used to store multiple items and each of these items is associated with a unique string key. Each item can be accessed using the key associated with it. In short, hashtable is an object holding the key-value pairs.

What is difference between HashTable and ArrayList?
You can access array using INDEX value of array, but how many times you know the real value of index. Hashtable provides way of accessing the index using a user identified KEY value, thus removing the INDEX problem.

What is the function of the Try-Catch-Finally block? 
The try block encloses those statements that can cause exception and the catch block handles the exception, if it occurs. Catch block contains the statements that have to be executed, when an exception occurs. The finally block always executes, irrespective of the fact whether or not an exception has occurred. The finally block is generally used to perform the cleanup process. If any exception occurs in the try block, the program control directly transfers to its corresponding catch block and later to the finally block. If no exception occurs inside the try block, then the program control transfers directly to the finally block.


Difference between Ref and Out parameter.

Ref and out parameters are used to pass an argument within a method. In this article, you will learn the differences between these two parameters.
Ref
The ref keyword is used to pass an argument as a reference. This means that when value of that parameter is changed in the method, it gets reflected in the calling method. An argument that is passed using a ref keyword must be initialized in the calling method before it is passed to the called method.
Out
The out keyword is also used to pass an argument like ref keyword, but the argument can be passed without assigning any value to it. An argument that is passed using an out keyword must be initialized in the called method before it returns back to calling method.

EX :

 class Program
    {

        static void Main(string[] args)
        {
         
            string name="Bhimsen";
            string address="Bhagalpur";
            int value = 1;
            Program program=new Program();
            Console.WriteLine("Name Before Calling RefMethod : " + name);
            program.RefMethod(ref name);
            Console.WriteLine("Name After Calling RefMethod : " + name);
            Console.WriteLine("Address Before Calling OutMethod : " + address);
            program.OutMethod(out address, out value);
            Console.WriteLine("Address After Calling OutMethod : " + address);
            Console.WriteLine("value After Calling OutMethod : " + value);
            Console.ReadLine();
           // Console.ReadKey();
        }
        private void RefMethod(ref string nameRef)
        {
            nameRef = "Kumar Bhimsen";
        }
        private void OutMethod(out string AddressOut,out int argval)
        {
            AddressOut = "Nathnagar, Bhagalpur";
            argval = 2 + 5;
        }
    }



Tuesday 2 December 2014

.Net Framework Interview Question.

What is .Net Framework ?
1. .Net framework is a complete development and execution environment. That allows the developer to develop , run and deploy the following application.
a. Console application.
b. Windows application
c. Web application
d. Service oriented application (WCF)
e. Web service
f. Windows service
g. WPF, WWF etc.
2. .Net framework support the object oriented programming model for multiple language such as, C#, VB, vC++, J# etc.
3. It support the language interoperability .Interoperability implies that each language can use the code written in some other language.
4. It provides a common set of tools enables easy integration of module developed with one another.
5. It also enables the developers to create sharable component to be used in distributed computing architecture.

What is the need of .Net framework ?
.Net framework was designed to fulfill the following goals.
1. Interoperability
2. Cross platform support
3. Language Independence
4. Base class library.
5. Easy development
6. Security etc.
Interoperability: .Net framework supports interoperability between new application and existing application. It implies that the code written in one language can be used in some other language.
Cross Platform support: Each .Net compitable language, such as C# , VB, VC++ provides its own compiler to compile code to MSIL . After that , the common runtime engine compile MSIL code to native code with the help of Just In Time (JIT) compiler and then run the application.
Language Independence: .Net framework provides the multiple language support by using the feature known as common type system. That is built into common language runtime.
Base Class Library: The base class library provide the fundamental building block for any application you develop. These application could be windows , web, console, or service oriented. The BCL mostly serves as the main point of interaction with the CLR.
Easy Deployment: .Net framework makes the task of employment easier. In most cases , to install an application along with component on the target computer.
Security: .net framework provides security model that allows you to authorize and authenticate the user.

What is the main component of .Net Framework ?
Following are the main component of the .Net Framework.
1. .Net Framework library
2. CLR
3. DLR (Dynamic Language Runtime )
4. Application Domain
5. Runtime host
6. CTS  ( Common Type System)
7. Metadata
8. Cross Language Interoperability
9. Security
10. Side by side execution
11. Profiling etc.

What is IL or MSIL?

IL stands for Intermediate Language. It is also known as MSIL(Microsoft Intermediate Language)  or  CIL (Common Intermediate Language ). All the .Net language such as C#, J#,VB uses there own compiler. the compiler compile the code into IL and after than common runtime engine convert the IL code into natinve code with the help of JIT compiler.
What is assembly Manifest ?
Assembly manifest stores the assembly metadata. It contains all the metadata needed to do the following things :-
1. Version of assembly
2. Security Identity
3. Scope of assembly
4. Resolve reference to resource of class

Assembly manifest contains PE file either .exe or .dll

What is Common Type System?

CTS is a component of CLR (Common Language Runtime) through which .Net framework provide support for multiple language. Because it contains a type system, that is  common across all the language. Two common type system language do not require type conversion when calling the code written in another language. CTS provide a base set of data type for all language supported by .net framework. This means that the size of integer and long variable is same across all language.

Which method do you use to enforce garbage collection in .Net? and which method use to suppress the process inside GC forcibly?
System.GC.Collect() method enforce garbage collection.   And GC.Supressfinalize() method used to suppress finalize forcibly.

What is difference between finalize and dispose method ?
Dispose and finalize both method are used by CLR to perform the garbage collection of runtime object of .Net. The finalize () method is called automatically by runtime. CLR has a garbage collector. Which periodically check for object in heap that are no longer referenced by any object or program. It calls the finalize method to free the memory used by an object. The Dispose() method is called by programmer. It is also a method to release the memory used by object. The dispose method needs to be explicitly called in code to reference an object from the heap. The dispose method can be invoked only by the class that implement the idisposable class.

What is managed and unmanaged code in .Net framework ?
Managed Code : Managed code is the code that executed directly by CLR instead of operating system. The language compiler compile the managed code to IL or MSIL. This code does not depend on the machine configuration and can be executed on different machine. Manage code process are as follows :-
Choose Language Compiler --> Compile code to MSIL -->Compile MSIL to Native Code -->Execute the code
Unmanaged Code : Unmanaged code is the code that is executed directly by the operating system outside the CLR environment. It is directly compiled to native machine code which depends on the machine configuration. In unmanaged code, The allocation of memory , Type safety and security is required to be taken care of by the developer. If unmanaged code is not properly handled. It may result in memory leak. 

What is garbage collection? Explain the difference between garbage collection in 4.0 and earlier version.
Garbage collection prevent memory leaks during execution of programs. It is a low priority process that manages the allocation and deallocation of memory in your application. It checks for unreferenced variable and objects. If GC  find any object that is no longer uses by application, it frees up the memory that  object.
GC has changed a bit in .Net framework 4.0. It contains following overload method.
1. GC.collect ()
2. GC.collect (int, GC collection method)

Generation of garbage collection :
1. Generation  0  :  when an object is initialized.
2. Generation  1  :  The object under the GC process.
3. Generation  2  :  whenever new object are created and added to memory. It adds generation 0 and generation 1.

What is namespace in .Net framework ?

Namespace has two basic functionality :-
1. It is a logically group type.
2. In object oriented world many times it is possible that , programmer will use the same class name by qualifying namespace with class name, this collision is able to remove. 

What is assembly in .net framework ?
Every software has an execuitable file (.exe) apart from the .exe file, there are some dynamic link library (.dll) and Library file (.lib) that contains the compiled code of some commonly used function. These file are shipped along with the software. Any software package includes an executed file along with some DLL and LIB file that are necessary to run the application. In term of .net runtime, the process of packing is called assembly. An assembly contains MSIL, Metadata file are required to execute a .Net program successfully. There are two types of assembly. They are  : 
1. Private Assembly 
2. Public assembly

What is difference between Assembly and namespace ?
1. An assembly is a physical grouping of logical unit. While namespace is logically group of class.
2. A namespace can span multiple assembly.
3. It is a collection of name wherein each name is unique. While assembly is an output unit. It contains a unit of development and deployment.

What’s the difference between private and shared assembly?
Private assembly is used inside an application only and does not have to be identified by a strong name. Shared assembly can be used by multiple applications and has to have a strong name.

What is global assembly  catch (GAC ) ?
While using shared assembly, To avoid assembly being overwritten by the different or same assembly .  Shared assembly are placed in a special directory in the file system are known as global assembly catch.

Or

GAC is a central repository (cache) in a system in which assemblies are registered to share among various applications that execute on local or remote machines. .NET Framework provides the GAC tool (gacutil.exe utility), which is used to view and change the content of GAC of a system. Adding new assemblies to GAC and removing assemblies from GAC are some of the tasks that can be performed by using the gacutil.exe utility. GAC can contain multiple versions of the same .NET assembly. CLR checks GAC for a requested assembly before using information of configuration files.

What is MSIL ?
.Net is shipped with compiler of all programming language to develop program. There are separate compiler for the VB, C#, VC++ etc. All compilers produce an intermediate code after compiling source code. The intermediate code is common for all language and  it is understandable into .net environment. This intermediate code is known as IL or MSIL.

What is the component and services of CLR? 
There are several component of CLR, Which are as follows :
1. CTS
2. MSIL
3. Execution Support Function
4. Security
5. Garbage collection
6. Class loader
7. Memory layout

Services of CLR :

1. Loading and execution of program
2. Memory Isolation for application
3. Verification of type safety.
4. Compilation of MSIL to native code
5. Providing Metadata
6. Interoperability with other system
7. Managing exception and error
8. Debugging and profiling.