March 30, 2013

Hypertext Transfer Protocol


Introduction:

The Hypertext Transfer Protocol (HTTP) is designed to enable between client and server and work as a Request-Response Protocol. A web browser may be client and an application on a computer that host a website may be the server.

The Life Cycle begins as:

A client (browser) submits an HTTP request to the server; then server returns
a response to a client. The response contains status information about request
and may also the request content.”


HTTP Protocols:

Three HTTP protocols are present:
  1. HTTP Persistent: HTTP Persistence connection is also called “HTTP keep-alive” or “HTTP connection reuse”, is the idea of using single TCP connection to send and receive multiple HTTP requests/responses, as opposed to opening new connection for every single request/response pair.
  2. HTTP Compression: HTTP compression is an ability that can build into web servers and web clients to make better use of available bandwidth and provide greater transmission speeds between both.
  3. HTTPS: HTTPS is widely used communication protocol for secure communication over computer network with especially wide deployment on the internet. Technically it is not a protocol, it is result of simply layering the HTTP protocol on the top of SSL/TLS protocol thus adding the security capabilities of SSL/TLS to standard HTTP communication.

HTTP Request Methods:

There are nine HTTP request methods are present but most widely two of them use named as GET and POST.
  1. GET:
  • It can be cached.
  • It remains in the browser history.
  • It can be bookmarked.
  • It should never be used when dealing with sensitive data.
  • It have length restriction.
  • It should be only use to retrieve data
  1. POST:
  • It cannot be cached.
  • It don't remain in browser history.
  • It cannot be bookmarked.
  • It has no restriction on data length.
  1. HEAD: Same as GET but returns only headers and no document body.
  2. PUT: Upload a representation of the specified URI.
  3. DELETE: Delete the specified resource.
  4. OPTIONS: Returns the HTTP methods that the server supports.
  5. CONNECT: Converts the request connection to a transparent TCP/IP tunnel.

Compare GET vs POST:

  1. Back Button/Reload:
  • GET: Harmless
  • POST: Data will be re-submitted (alert the user about re submission)
  1. Bookmarked
  • GET: Can be bookmarked
  • POST: Cannot be bookmarked
  1. Cached
  • GET: Can be cached
  • POST: Not cached
  1. Encoding Type
  • GET: application/x-www-form-urlencoded
  • POST: application/x-www-form-urlencodede or multipart/form-data (For binary data)
  1. History
  • GET: Parameter remains in browser history
  • POST: Parameters are not saved in browser history
  1. Restriction on data length
  • GET: Maximum URL length is 2048 characters
  • POST: No restriction
  1. Restrictions on data type
  • GET: Only ASCII characters are allowed
  • POST: No restriction. Binary data is also allowed
  1. Security
  • GET: GET is less secure than POST because data sent is the part of URL.
  • POST: POST is little safer than GET because the parameters are not stored in browsers history or in web server logs.
  1. Visibility
  • GET: Data is visible to everyone in the URL
  • POST: Data is not displayed in URL
HTTP Status Codes:

There are five types of Status classes present in HTTP Status which are
  1. 1xx Informational
This class of status code indicates a provisional response consisting only of the Status-Line and optional headers, and is terminated by an empty line.

  • 100 Continue: This means that server has receive the request headers and that client should proceed to send the request body.
  • 101 Switching Protocols: This means requester has asked the server to switch protocols and server is acknowledging that it will do so.
  • 102 Processing: This code indicates that server has received and in processing the request but no response is available yet. This prevents the client from timing out and assuming the request was lost.
  1. 2xx Success
This class of status code indicates the action requested by client was received, understood, accepted and processed.

  • 200 OK: Standard response for successful HTTP requests.
  • 201 Created: This means that the request has been fulfilled and resulting in a new resource being created.
  • 202 Accepted: This code indicates that request has been accepted for processing but the processing has not be completed.
  • 203 Non-Authoritative Information: Means server successfully processed the request but is returning information that may be from another resource.
  • 204 No Content: Means server successfully processed the request, but is not returning any content.
  • 205 Reset Content: Means server successfully processed the request, but is not returning any content. Unlike 204 response, this response requires that the requester reset the document view.
  • 206 Partial Content: Means server is delivering only part of resource due to range header send by the client.
  • 207 Multi Status: Means the message body that follow is an XML message and can contain the number of separate response codes, depending on how many sub-requests were made.
  • 208 Already Reported: Means the number of DAV binding have already been enumerated in a previous reply to this request and are not be included again.
  • 250 Low on Storage Space: Means the sever receive this warning after receiving a RECORD request that it may not be able to fulfill completely due to insufficient storage space.
  • 226 IM Used: Means the sever has fulfilled the GET request for the resource and the response is the representation of the result of one or more instance manipulations applied to the current instance.
  1. 3xx Redirection
This class of status code indicates that further action needs to be taken by the user agent to fulfill the request. The action required may be carried out by the user agent without with the user if and only if the method used in second request is GET or HEAD.

  • 300 Multiple Choices: Indicates multiple options for the resource that the client may follow.
  • 301 Moved Permanently: This and all future requests should be redirected to the given URL.
  • 302 Found: This code means the original describing phrase “Moved Temporarily” but the popular browsers implemented 302 with the functionality of 303.
  • 303 See Other: Means the response to the request can be found under another URL using GET method. It should assume that the server has received the data and redirect should be issued with separate GET message.
  • 304 Not Modified: Indicates that the resource has not been modified since the version specified by request headers.
  • 305 Use Proxy: The requested resource is only available through a proxy whose address is provided in the response.
  • 306 Switch Proxy: No longer used. Originally meant “Subsequent requests should use the specified proxy.”
  • 307 Temporary Redirect: The request should be repeated with another URI, however future request should still use the Original URI.
  • 308 Permanent Redirect: The request and all future request should be repeated using another URI.
  1. 4xx Client Error
This class of status code intended for cases in which client seemed to be erred. These are applicable to any request method.

  • 400 Bad Request: The request cannot be fulfilled by bad request.
  • 401 Unauthorized: Similar to 403 but use when authentication is required and has failed or has not yet been provided.
  • 402 Payment Required: This code might be used as part of some form of digital cash but that has not happen and this code is not usually used.
  • 403 Forbidden: The request was valid request but server is refusing to respond it.
  • 404 Not Found: The requested resource could not be found but may be available again in future.
  • 405 Method Not Allowed: A request was made of resource using a request method not supported by that request.
  • 406 Not Acceptable: The requested resource is only capable of generating content according to accept headers sent in the request.
  • 407 Proxy Authentication Required: The client must first authenticate itself with the proxy.
  • 408 Request Timeout: The server time out waiting for request.
  • 409 Conflict: Indicates that request could not be processed because of conflict in the request.
  • 410 Gone: Indicate that resource requested is no longer available and will not be available again.
  • 411 Length Required: The request didn't specified the length of its content which is required by requested resource.
  • 412 Preconditioned Failed: The server does not meet one of the precondition that the requester put on the request.
  • 413 Request Entity Too Large: The request is larger than the server is willing or able to process.
  • 414 Request URI Too Long: The URI provided was too long for the server to process.
  • 415 Unsupported Media Type: The request entity has media type which the server or resource does not support.
  • 416 Requested Range Not Satisfiable: The client has asked for a portion of the file, but the server cannot supply that portion.
  • 417 Expectation Failed: The server cannot meet the requirements of the Expect-request header field.
  • 422 Unprocessable Entity : The request was well-formed but was unable to followed due to semantic errors.
  • 423 Locked: The resource that is being accessed is locked.
  • 424 Failed Dependency: The request failed due to failure of a previous request.
  • 426 Upgrade Required: The client should switch to a different protocol.
  • 429 Too Many Request: The user is sent too many request in a given amount of time.
  • 431 Request Header Field Too Large: The server is unwilling to process the request because either an individual header fields collectively are too large.
  • 451 Parameter Not Understood: The recipient of request does not support one or more parameters contained in the request.
  • 452 Conference Not Found: The conference indicated by Conference header field is unknown to media server.
  • 453 Not Enough Bandwidth: The request was refused because there was insufficient bandwidth.
  • 454 Session Not Found: The session identifier in session header is missing, invalid or timeout.
  1. 5xx Server Error
This class of status code are applicable to any request methods.

  • 500 Internal Server Error: A generic error message given when no more specific message is suitable.
  • 501 Not Implemented: The server either does not recognized the request method or its lack the ability to fulfill the request.
  • 502 Bad Gateway: The server was acting as a gateway or proxy and received an invalid response from the upstream server.
  • 503 Service Unavailable: The service is currently unavailable, generally this is temporarily state.
  • 504 Gateway Timeout: The server was acting as a gateway or proxy and received an invalid response from the upstream server.
  • 505 HTTP Version Not Supported: The server does not support the HTTP protocol version used in request.
  • 507 Insufficient Storage: The server is unable to store the representation needed to complete request.
  • 508 Loop Detected: The server detected an infinite loop while processing the request.
  • 510 Not Extended: Further extensions to the request are required for the server to fulfill it.
  • 511 Network Authentication Required: The client need to authenticate to gain network access.
  • 551 Option Not Supported: An option given in an Require or the Proxy-Require field was not supported.

HTTP Header Fields:

There are six types of header fields presents which are:

  1. HTTP Cookie:
A cookie is usually a small piece of data sent from website and store into user's browser while a user is browsing a website. There are seven types of cookies present which are:

  • Session Cookie: A user's session cookie for a website exists in temporary memory only while the user is reading and navigating the website.
  • Persistent Cookie: This cookie is use to record a vital piece of information such as how the user initially came to website. It is also called “Tracking Cookies”.
  • Secure Cookie: This cookie is use via HTTPS and has secure attribute enabled, ensuring that cookie is always encrypted when transmitting from client to server.
  • HTTPOnly Cookie: Only supported by most modern browsers. It is use when only transmitted HTTP or HTTPS request and restricted access from others.
  • Third Party Cookie: These cookies are set with domains different from one shown in the address bar.
  • Super Cookie: This cookie is use for tracking technologies that do not rely on HTTP cookies.
  • Zombie Cookie: This cookie is automatically recreated after the user has deleted them. This is accomplished by script store in content of cookie in other location.

  1. HTTP Etag
It is one of the several mechanisms that HTTP provides for web cache validation and which allows a client to make conditional requests. This allow cache to more efficient and saves bandwidth, as a web server does not need to send a full response if the content has not changed.

  1. HTTP Location
It returned responses from HTTP servers under two circumstances.

  • To ask web browser to load different page. In this circumstances, HTTP Status Code of 3xx should be sent. It is passed as part of response by a web server when request URI has: Move Temporarily or More Permanently
  • To provide information about the location of the newly created resource. In this circumstance, location header should be sent HTTP Status Code of 201 & 202.

  1. HTTP Referer
That identifies the address of web page that linked to resource being requested. By clicking the referer, the new web page can see when request originated. Referer logging is used to allow websites and web servers to identify when people are visiting them for statistical puposes.

  1. DNT
The DNT (Do not track) header is HTTP proposed header field use to disable either its tracking or cross-site user tacking of web applications.

  1. X-Forwaded-For
A header field for identifying the originated IP address of client connecting to a web server through an HTTP proxy or load balancer.

March 27, 2013

LINQ Query Examples

This post contains many samples of LINQ queries. Here I show queries related to:

  1. Simple Where Clause
  2. Join and Simple Where Clause
  3. Distinct Operator
  4. Simple Inner Join
  5. Self Join
  6. Double or Multiple Joins
  7. Join using Entity Fields
  8. Late-Binding Left Join
  9. Equals Operator
  10. Not Equals Operator
  11. Method Based LINQ Query with Where Clause
  12. Greater Than Operator
  13. Greater Than or Equals and Less Than or Equals Operator
  14. Contain Operator
  15. Does Not Contain Operator
  16. StartsWith and EndsWith Operator
  17. AND and OR Operator
  18. OrderBy Operator
  19. First and Single Operator
  20. Retrieve Formatted Values
  21. Skip and Take Operator without Paging
  22. FirstOrDefault or SingleOrDefault Operator
  23. Self Join with condition on Linked Entity
  24. Transformation in Where Clause
  25. Paging Sort
  26. Retrieve Related Entity Column (1 to N Relationship)
  27. .Value to Retrieve the Value of Attribute
  28. Multiple Projections, new data type casting to different types
  29. GetAttributeValue Method
  30. Math Methods
  31. Multiple Select and Where Clauses
  32. Select Many
  33. String Operation
  34. Two Where Clauses
  35. Load Property to Retrieve Related Products
All codes are written in C#, if you want code in VB.Net then convert your code here
  • Simple Where Clause
using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 var query_where1 = from a in svcContext.AccountSet
                    where a.Name.Contains("Contoso")
                    select a;
 foreach (var a in query_where1)
 {
  System.Console.WriteLine(a.Name + " " + a.Address1_City);
 }
}
  • Join and Simple Where Clause
using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 var query_where3 = from c in svcContext.ContactSet
                    join a in svcContext.AccountSet
                    on c.ContactId equals a.PrimaryContactId.Id
                    where a.Name.Contains("Contoso")
                    where c.LastName.Contains("Smith")
                    select new
                    {
                     account_name = a.Name,
                     contact_name = c.LastName
                    };

 foreach (var c in query_where3)
 {
  System.Console.WriteLine("acct: " +
   c.account_name +
   "\t\t\t" +
   "contact: " +
   c.contact_name);
 }
}
  • Distinct Operator
using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 var query_distinct = (from c in svcContext.ContactSet
                       select c.LastName).Distinct();
 foreach (var c in query_distinct)
 {
  System.Console.WriteLine(c);
 }
}
  • Simple Inner Join
using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 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
using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 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 or Multiple Joins
using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 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);
 }
}
  • Join using Entity Fields
using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 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
using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 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);
 }
}
  • Equals Operator
using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 var query_equals1 = from c in svcContext.ContactSet
                     where c.FirstName.Equals("Colin")
                     select new
                     {
                      c.FirstName,
                      c.LastName,
                      c.Address1_City
                     };
 foreach (var c in query_equals1)
 {
  System.Console.WriteLine(c.FirstName +
   " " + c.LastName +
   " " + c.Address1_City);
 }
}
  • Not Equals Operator
using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 var query_ne1 = from c in svcContext.ContactSet
                 where c.Address1_City != "Redmond"
                 select new
                 {
                  c.FirstName,
                  c.LastName,
                  c.Address1_City
                 };
 foreach (var c in query_ne1)
 {
  System.Console.WriteLine(c.FirstName + " " +
   c.LastName + " " + c.Address1_City);
 }
}
  • Method Based LINQ Query with Where Clause
using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 var methodResults = svcContext.ContactSet
  .Where(a => a.LastName == "Smith");
 var methodResults2 = svcContext.ContactSet
  .Where(a => a.LastName.StartsWith("Smi"));
 Console.WriteLine();
 Console.WriteLine("Method query using Lambda expression");
 Console.WriteLine("---------------------------------------");
 foreach (var a in methodResults)
 {
  Console.WriteLine("Name: " + a.FirstName + " " + a.LastName);
 }
 Console.WriteLine("---------------------------------------");
 Console.WriteLine("Method query 2 using Lambda expression");
 Console.WriteLine("---------------------------------------");
 foreach (var a in methodResults2)
 {
  Console.WriteLine("Name: " + a.Attributes["firstname"] +
   " " + a.Attributes["lastname"]);
 }
}
  • Greater Than Operator
using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 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);
 }
}
  • Greater Than or Equals and Less Than or Equals Operator
using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 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);
 }
}
  • Contain Operator
using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 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);
 }
}
  • Does Not Contain Operator
using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 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 Operator
using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 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);
 }
}
  • AND and OR Operator
using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 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
using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 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);
 }
}
  • First and Single Operator
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");
}
  • Retrieve Formatted Values
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 Operator without Paging
using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{

 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 or SingleOrDefault Operator
using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{

 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 condition on Linked Entity
using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 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 Where Clause
using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 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
using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 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);
 }
}
  • Retrieve Related Entity Column (1 to N Relationship)
using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 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);
 }
}
  • .Value to Retrieve the Value of Attribute
using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{

 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
using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 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
using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 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
using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 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);
 }
}
  • Multiple Select and Where Clauses
using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 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());
 }
}
  • Select Many
using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 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 Operation
using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 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);
 }
}
  • Two Where Clauses
using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 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);
 }
}
  • Load Property to Retrieve Related Products
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);
 }
}

Stay tuned.

March 26, 2013

Redirect after 5 seconds

This post shows the demonstration on how to redirect to another page after some seconds in Asp.net application. There are two types of code is use. One using meta tag and other one is use JavaScript. 

Use this line within <head> section of page.

<meta http-equiv="refresh" content="N; URL=other-web-address">

Here: section of page.

  • Replace N with number. For Example 5, so page will be redirect after 5 seconds.
  • Set URL to where redirection occur
The modified code will be

<meta http-equiv="refresh" content="10; URL=http://www.google.com">

If you are using Content page then instead of using above method use JavaScript code as

<script type="text/javascript">  

    delayRedirect('Login.aspx'); 

    function delayRedirect(url)
    {
        var Timeout = setTimeout("window.location='" + url + "'",5000);
    }
    
</script> 


Hope you understand well. Let me know if anybody face any issue. Stay tuned.

March 14, 2013

Duration in terms of Year/Month/Days and Hour/Minute/Second between two dates

This post will show you the duration in terms of Year, Month, Days, Hour, Minute and Second between two dates.

The output of this example is



Let starts coding (Remember this is console application, you may change this code as you feeling better)

C# CODE:
static void Main(string[] args)
{
    DateTime startDate = Convert.ToDateTime("08/01/2012 09:00:00 AM");
    string getDuration = GetDateTimeDurationFromDateDiff(startDate, DateTime.Now);
    Console.WriteLine("Date Difference in terms of Year, Month, Days, Hour, Minute and Second: \n");
    Console.WriteLine(getDuration);
}

static string GetDateTimeDurationFromDateDiff(DateTime startDate, DateTime endDate)
{
    #region Get Year, Month, Days

    string duration = string.Empty;
    int year = 0, month = 0, days = 0;

    var timeSpan = new TimeSpan();
    timeSpan = endDate.Subtract(startDate);
    year = (timeSpan.Days / 365);

    do
    {
        for (int i = 0; i <= 12; i++)
        {
            if (endDate.Subtract(startDate.AddYears(year).AddMonths(i)).Days > 0)
            {
                month = i;
            }
            else
            {
                break;
            }
        }

        if (month > 12)
        {
            year = year + 1;
        }
    }
    while (month > 12);

    days = endDate.Subtract(startDate.AddYears(year).AddMonths(month)).Days;

    if (year > 0)
    {
        duration += year.ToString() + "Years ";
    }

    if (month > 0)
    {
        duration += month.ToString() + " Months ";
    }
    if (days > 0)
    {
        duration += days.ToString() + " Days";
    }

    #endregion

    #region Get Hours, Minutes, Seconds

    TimeSpan span = endDate.Subtract(startDate);
    duration +=
        " " + span.Hours + " hours " + span.Minutes + " minutes " + span.Seconds + " seconds ";

    #endregion

    return duration.Trim();            
}

VB.NET CODE:
Private Shared Sub Main(args As String())
    Dim startDate As DateTime = Convert.ToDateTime("08/01/2012 09:00:00 AM")
    Dim getDuration As String = GetDateTimeDurationFromDateDiff(startDate, DateTime.Now)
    Console.WriteLine("Date Difference in terms of Year, Month, Days, Hour, Minute and Second: " & vbLf)
    Console.WriteLine(getDuration)
End Sub

Private Shared Function GetDateTimeDurationFromDateDiff(startDate As DateTime, endDate As DateTime) As String
    Dim duration As String = String.Empty
    Dim year As Integer = 0, month As Integer = 0, days As Integer = 0

    Dim timeSpan = New TimeSpan()
    timeSpan = endDate.Subtract(startDate)
    year = (timeSpan.Days / 365)

    Do
        For i As Integer = 0 To 12
            If endDate.Subtract(startDate.AddYears(year).AddMonths(i)).Days > 0 Then
                month = i
            Else
                Exit For
            End If
        Next

        If month > 12 Then
            year = year + 1
        End If
    Loop While month > 12

    days = endDate.Subtract(startDate.AddYears(year).AddMonths(month)).Days

    If year > 0 Then
        duration += year.ToString() + "Years "
    End If

    If month > 0 Then
        duration += month.ToString() + " Months "
    End If
    If days > 0 Then
        duration += days.ToString() + " Days"
    End If

    Dim span As TimeSpan = endDate.Subtract(startDate)
    duration += " " + span.Hours + " hours " + span.Minutes + " minutes " + span.Seconds + " seconds "

    Return duration.Trim()
End Function

Hit Enter to move forward and Escape to backword

This post is to about some JavaScript stuff in order to gain some decent style of tab index changes. Sometimes people are searching of code in which when user hit enter tab index move forward and move backword when escape button press. 

Let's do this using simple and easy to understand JavaScript.

You should know following keycodes

  • For Enter Key    = 13
  • For Escape Key = 27

ASPX MARKUP:


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="EnterEscapeButton.aspx.cs"
    Inherits="Test_Web.EnterEscapeButton" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Enter Escape Button</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    
        $(function() {
            $('input:text:first').focus();            
            var $inp = $('input:text');
            $inp.bind('keydown', function(e) {
                var key = (e.keyCode ? e.keyCode : e.which);
                var nextIndex = 0;
                
                if (key == 13) {
                    e.preventDefault();
                    nextIndex = $inp.index(this) + 1;
                    $(":input:text:eq(" + nextIndex + ")").focus();
                }
                else if (key == 27) {
                    e.preventDefault();
                    nextIndex = $inp.index(this) - 1;
                    $(":input:text:eq(" + nextIndex + ")").focus();
                }
            });
        });
    
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div class="controlList">
        <h2>
            Hit Enter to move next and Escape to move back</h2>
        <br />
        <asp:TextBox ID="TextBox1" runat="server" /><br />
        <asp:RequiredFieldValidator ID="ReqUserName" runat="server" ErrorMessage="Enter Username" Text="*"
            ControlToValidate="TextBox1" Display="Dynamic" ForeColor="#993333"></asp:RequiredFieldValidator>
        <asp:TextBox ID="TextBox2" runat="server" /><br />
        <asp:TextBox ID="TextBox3" runat="server" /><br />
        <asp:TextBox ID="TextBox4" runat="server" /><br />
    </div>
    </form>
</body>
</html>

Display Page as a Popup Window from Grdi View Button Click

This post will show you a demonstration how can you show a page as popup window from GridView Button click event. Let me tell you how to achieve this.

The output of this example is as:



Let starts coding,

ASPX MARKUP :

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="PageAsPopup.aspx.cs" Inherits="Test_Web.PageAsPopup" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Page as Popup</title>
    <script language="javascript" type="text/javascript">

        function ShowPage(id,url) 
        {
            window.showModalDialog(url + '?id=' + id , window, 
                'dialogHeight:500px;dialogWidth:650px;center:yes;help:no;resizable:no;status:no');
        }
   
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
            OnRowDataBound="GridView1_OnRowDataBound" Width="100%">
            <Columns>
                <asp:TemplateField HeaderText="ID">
                    <ItemTemplate>
                        <asp:Label ID="lblID" runat="server" Text='<%# Bind("ID")%>'>
                        </asp:Label>
                    </ItemTemplate>
                    <HeaderStyle HorizontalAlign="Center" />
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate>
                        <asp:Label ID="lblName" runat="server" Text='<%# Bind("Name")%>'>
                        </asp:Label>
                    </ItemTemplate>
                    <HeaderStyle HorizontalAlign="Center" />
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Country">
                    <ItemTemplate>
                        <asp:Label ID="lblCountry" runat="server" Text='<%# Bind("Country")%>'>
                        </asp:Label>
                    </ItemTemplate>
                    <HeaderStyle HorizontalAlign="Center" />
                </asp:TemplateField>
                <asp:TemplateField HeaderText="City">
                    <ItemTemplate>
                        <asp:Label ID="lblCity" runat="server" Text='<%# Bind("City")%>'>
                        </asp:Label>
                    </ItemTemplate>
                    <HeaderStyle HorizontalAlign="Center" />
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <input id="lnkPopup" runat="server" type="button" value="Open Page" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <EmptyDataTemplate>
                No record found!
            </EmptyDataTemplate>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

CODE BEHIND :

C# CODE
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        var dataTable = new DataTable();
        dataTable.Columns.Add("ID");
        dataTable.Columns.Add("Name");
        dataTable.Columns.Add("Country");
        dataTable.Columns.Add("City");

        dataTable.Rows.Add("1", "Martin", "UK", "London");
        dataTable.Rows.Add("2", "Micheal", "USA", "NewYork");
        dataTable.Rows.Add("1", "Smith", "UAE", "Dubai");

        GridView1.DataSource = dataTable;
        GridView1.DataBind();
    }
}

protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow) 
    {
        var linkPopup = (HtmlInputButton)e.Row.FindControl("lnkPopup");
        linkPopup.Attributes.Add("onclick", "ShowPage('" + e.Row.Cells[0] + "','PopupPage.aspx')");
    }
}


VB.NET CODE
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    If Not IsPostBack Then
        Dim dataTable = New DataTable()
        dataTable.Columns.Add("ID")
        dataTable.Columns.Add("Name")
        dataTable.Columns.Add("Country")
        dataTable.Columns.Add("City")

        dataTable.Rows.Add("1", "Martin", "UK", "London")
        dataTable.Rows.Add("2", "Micheal", "USA", "NewYork")
        dataTable.Rows.Add("1", "Smith", "UAE", "Dubai")

        GridView1.DataSource = dataTable
        GridView1.DataBind()
    End If
End Sub

Protected Sub GridView1_OnRowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
    If e.Row.RowType = DataControlRowType.DataRow Then
        Dim linkPopup = DirectCast(e.Row.FindControl("lnkPopup"), HtmlInputButton)
        linkPopup.Attributes.Add("onclick", "ShowPage('" + e.Row.Cells(0) + "','PopupPage.aspx')")
    End If
End Sub