Blog Stats
  • Posts - 35
  • Articles - 0
  • Comments - 7
  • Trackbacks - 2

 

Sunday, October 15, 2006

Perform a Case-IN sensitive Search in .NET Using XPath


The following code shows to how to perform a case-sensitive search in .NET using XPath.

and contains is used as like operator in xpath.

XML File:
<?xml version="1.0" encoding="utf-8"?>
<USERS>
  <USER>
    <NAME>sharvan</NAME>
    <PASSWORD>dhaka</PASSWORD>
  </USER>
</USERS>

Code File:

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Xml" %>
<%@ Page Language="C#" Debug="true" %>

<SCRIPT runat="server">
void Page_Load(object sender, System.EventArgs e)
{
    if(!Page.IsPostBack)
    {
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(Server.MapPath("user.xml")); 
 XmlNodeList nodeList = xmlDoc.SelectNodes("Users/User[contains(translate(Name,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz'),translate('Sharvan', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'))]");
 Response.Write(nodeList.Count.ToString());
    }
}


1. Case of matching the beginning of some text.
miCommunities% LIKE where wildcard is at end

 Corresponding XPath expression predicate,
[ starts-with( Name , 'miCommunities')]

2. Case of matching within some text.
%miCommunities% LIKE where there is a wildcard at both ends

 Corresponding XPath expression predicate,
[ contains( Name , 'miCommunities')]
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Search in Xml File through XPATH


Using xpath you can find elements in a xml file.
There is more to XML then just a way of describing data. Over the years, a number of XML-based standards have emerged. Among the most fundamental ones are XSD (XML Schema Definition), XPath Query, XSLT (Extensible Stylesheet Language Transformation), SOAP (Simple Object Access Protocol), and WSDL (Web Services Description Language). All build on top of the XML syntax.

The Sample XML Document for the Series of Articles

This series of articles assumes that you are familiar with XML itself. The sample XML document used throughout the articles is a list of employees, which must have for each employee the first name, last name, phone number, and e-mail address, and also can provide the job title and a Web address.

<?xml version="1.0" encoding="utf-8"?>
<Employees>
   <Employee ID="1">
      <FirstName>Klaus</FirstName>
      <LastName>Salchner</LastName>
      <PhoneNumber>410-727-5112</PhoneNumber>
      <EmailAddress>klaus_salchner@hotmail.com</EmailAddress>
      <WebAddress>http://www.enterprise-minds.com</WebAddress>
      <JobTitle>Sr. Enterprise Architect</JobTitle>
   </Employee>
   <Employee ID="2">
      <FirstName>Peter</FirstName>
      <LastName>Pan</LastName>
      <PhoneNumber>604-111-1111</PhoneNumber>
      <EmailAddress>peter.pan@fiction.com</EmailAddress>
      <JobTitle>Sr. Developer</JobTitle>
   </Employee>
</Employees>

A quick note to editing XML documents in Visual Studio .NET 2003: When you open up a XML document, you see at the bottom of the window an "XML" and "Data" tab. The XML tab allows you to edit the XML. It also formats the XML nicely for you with indentions and all that. The Data tab parses the XML and shows a data grid. You can add new nodes by adding new rows to the data grid and entering corresponding values. Using the example data, this would be new Employees.

You also can show a document outline through the "View | Other Windows | Document Outline" menu, which shows you a hierarchy of all the nodes in the XML document. Selecting a node in the "document outline" will automatically select it in the XML document too.

The Fundamentals of XPath Queries

Once you have data in XML format, you will want to be able to navigate and search its nodes. You don't want to have to parse the whole XML document to find that there are two Employee nodes. That would be terribly inefficient. You want to apply an XPath query, which then gives you all the matching nodes. To find all Employee nodes, you would run the following XPath query:

//Employee

If you use the table above, this query will return two nodes, each representing an employee. This makes it very easy to find matching nodes and walk through the result set.

XPath is a standard (XPath 1.0) and can be found at http://www.w3.org/TR/xpath/. The working draft of XPath 2.0 can be found at http://www.w3.org/TR/2001/WD-xpath20-20011220/. Let's look more closely at some of the most common XPath operators.

Operator Description
/ (child operator) Refers to the root of the XML document when used at the beginning of the XPath expression. The child operator is used to specify the next child to select. The expression "/Employees/Employee", for, example says, start at the root of the XML document, select the Employees node and then select all the Employee child nodes within the Employees node. This will return the two Employee nodes in the sample XML document.
// (recursive descendant operator) The recursive descendant operator indicates to include all descendant nodes in the search. Using the operator at the beginning of the XPath expression means you start from the root of the XML document. The expression "//LastName" starts at the root and finds any LastName node. The expression "/Employees//LastName" selects the Employees node and then, within that node, finds any LastName node. It yields the same result, but searches in a different way.
* (wildcard operator) The wildcard operator finds any node. The expression "/*" finds any node under the root, which in our case is Employees. The expression "/Employees/*" means find any node under the Employees node, which in our case results with the two Employee nodes. Now what is the difference between the "/Employees" and "/Employees/*" expression? The first expression returns the Employees node but the second node finds any node under the Employees node, meaning it returns the two Employee nodes. The expression "//*" means to select any node including descendant nodes, so it will effectively list every single node in the complete XML document.
. (current context operator) The current context operator refers to the current context. For example, you have written some code that selected the Employees node and then from there you run the expression "./Employee", which means it starts out from the currently selected Employees node and then selects the two Employee nodes. The expression "Employee" would yield the same result because it also starts out from the current context. Similar the expression ".//LastName" means start from the current context, the Employees node, and find any LastName node including any descendant nodes.
.. (parent operator) The parent operator refers to the parent. For example, the expression "/Employees/Employee/.." returns the Employees node because you navigate down to the Employee nodes and then tell it to return its parent, which is the Employees node.
@ (attribute operator) The attribute operator refers to an attribute instead of an element. The expression "/Employees//@ID" selects any ID attribute it finds under the Employees node. Now, keep in mind that the XPath query always returns the selected node. In the case of an attribute, the node below it is its value. So, the expression really two returns nodes, each with the value of each selected attribute. Furthermore, you can use the wildcard operator with attributes, so "/Employees//@*" means any attribute underneath the Employees node.
[ ] (filter operator) You can apply a filter operator to filter the selected nodes. This works with attributes and with elements. The expression "/Employees/Employee[@ID=1]" returns any Employee node under the Employees node that has an ID attribute with the value one. You also can apply filters that just say that an attribute or element with that name needs to be present. For example, the expression "/Employees/Employee[WebAddress]" returns Employee nodes that have a WebAddress node as child. The expression "/Employees/Employee[FirstName='Klaus']" returns the Employee node that has a FirstName node with the value Klaus.
text() function The "text()" function refers to the text of the selected node or attribute. The expression "//Employee//text()" does not list all the descendant nodes of all Employee nodes but rather the value for each descendant node. The expression "//Employee/FirstName[text()='Klaus']" lists all FirstName nodes which have a value of Klaus.
[ ] (collection operator) When your expression returns more then one node with the same name, you have a collection returned. The expression "//Employee" returns two Employee nodes, which is nothing more than a collection of Employee nodes. You can apply a collection operator and specify which item from the collection you want to select. Keep in mind that the index starts at one. The expression "//Employee[2]" returns the second Employee node. The order of the selected nodes is the same order as in the XML document. You can use the collection operator in any blend, such as "//Employee[1]/LastName", which selects the first Employee node and then from there the LastName node.
( ) (group operator) The collection operator can sometimes have some odd side effects. Assume you have two Employee nodes and each has two Job nodes. What does the expression "//Employee/Job[1]" return? It returns the first Job node for each selected Employee node. But, using the group operator allows you to apply explicit precedence to selections. The expression "(//Employee/Job)[4]" first selects all Job nodes for all Employee nodes and from that collection it returns the fourth node. The group operator can only be applied to the top level expression; for example, "//Employees/(Employee/FirstName)" is invalid.
comment() function Returns a comment node. The expression "//comment()" returns any comment node in the XML. The expression "/Employees/comment()" returns the comment nodes under the Employees node.
node() function XML documents consist of elements, attributes, and their values, each being a node. So, in XPath expressions you can use a node() function instead of a node name or the text() function. It is a generic way to address a node. The expressions "//Employee/JobTitle/node()" and "//Employee/JobTitle/text()" return the same result, the value of both JobTitle nodes. But, "//Employee//node()" will not just return the elements but also the values of each element, because both are nodes.
| (union or set operator) Returns the union of one or more location paths. The expression "//LastName | //FirstName" returns all the LastName and FirstName nodes. It preserves the order of the elements as in the XML and does not return any duplicates. The two location paths "//Employee[@ID=1] | //Employee[FirstName='Klaus']" return the same nodes but the union of these two returns just the one unique node.

The table does not represent a complete list, but it lists the most basic operators and functions. As you can see from the samples, this already enables you to build fairly complex XPath queries. Keep in mind that the precedence of the operators is the group operator, followed by the filter operator, the child operator, and recursive descendant operator followed by the rest.

Let's spend a few minutes on a few basic terms commonly used. You have seen that I use the term XPath expression and XPath query interchangeably. An XPath expression is also called a "Location Path," because you are selecting one or more locations in your XML document and, to be able to do so, you specify the path to it. The expression "//Employees/Employee" is a path to certain locations in your XML document you want to select. It is the path to these locations. The "Location Path" consists of "Location Steps."

 

Your path has two steps: First, go to the Employees node and then, from there, go to all the Employee nodes. Each "Location Step" consists of an axis, a node-test, and a predicate or filter. The axis defines the relationship between your current location and the next location you specify. When no location is specified (see table below), child is assumed. The node-test is the node you want to select. You provide the name of the node or the wildcard operator for any node. The predicate or filter is any filter you apply by using the filter operator. The expression //child::Employees/child::Employee" is the same as "//Employees/Employee". Let's look closer at some of the most common axes:

Axes Description
ancestor:: This returns all ancestors of the selected node. The expression "/Employees/Employee/JobTitle/ancestor::*" selects the JobTitle of each Employee node and then returns all its ancestors up to the root, so it returns the Employee node with the ID one, the Employee node with the ID two, and the Employees node itself. This makes it easy to find all ancestors of your nodes. But, you also can look for a specific ancestor; for example, with the expression "//JobTitle[ancestor::Employee/@ID=1]", you select all JobTitle nodes that have an ancestor node Employee with an ID attribute of the value one.
child:: This axis is the default if none is specified and has the same result as the child operator. For example, the expression "/child::Employees/child::Employee" selects all the Employee nodes in the Employees node.
self:: This has the same result as the current context operator. The expression "//*/self::JobTitle" first selects all nodes in the XML document and then refers to the current context and from there selects only the nodes of the type JobTitle. The expression "//*/./JobTitle" returns the same result using the current context operator.
ancestor-or-self:: Same as the ancestor axis, but it includes the current context. The expression "//JobTitle/ancestor-or-self::*" lists both Employee nodes, both JobTitle nodes, and the Employees node. But, on the other hand, the expression "//JobTitle/ancestor::*" does not return the two JobTitle nodes.
attribute:: The attribute axis returns the same as the attribute operator; it walks the attributes instead of the elements. The expression "//attribute::*" as well as "//@*" return all the attributes in your XML document.
descendant:: The descendant operator returns the same as the recursive descendant operator. It returns all descendant nodes. The expression "//Employee/descendant::*" as well as "//Employee//*" return all descendant nodes under the two Employee nodes.
descendant-or-self:: Same as the descendant axis but it includes the current context. So, the expression "//Employee/descendant-or-self::*" lists both Employee nodes, including all its descendant nodes. But, on the other hand, the expression "//Employee/descendant::*" does not return the two Employee nodes.
following:: Selects all the nodes following the current context node, which includes all siblings (nodes at the same hierarchy level) and its children but not their descendants. The expression "//Employee[@ID=1]/following::*" selects the Employee node with the attribute ID value of one and then returns all its following Employee nodes, in our case only the one with the attribute ID value of two, and its children, but not the descendants of the children.
following-sibling:: Returns the same as the following axis but includes only siblings and no children and not their descendants. So, the expression "//Employee[@ID=1]/following-sibling::*" returns only the Employee node with the attribute ID value of two.
preceding:: Selects all the nodes preceding the current context, which includes all siblings (nodes at the same hierarchy level), and its children but not its descendants. The expression "//Employee[@ID=2]/preceding::*" selects the Employee node with the attribute ID value of two and then returns all its preceding Employee nodes—in our case, only the one with the attribute ID value of one, and its children but not the descendants of the children.
preceding-sibling:: Returns the same as the preceding axis but includes only siblings and no children and not its descendants. So, the expression "//Employee[@ID=2]/preceding-sibling::*" returns only the Employee node with the attribute ID value of one.

The axes give you more control over which nodes you want to select. It makes it easy to find ancestors, descendants, following, and preceding nodes. Unfortunately, you cannot not run XPath queries against an XML document from within the Visual Studio .NET 2003 IDE. The overall support of XPath is rather weak in Visual Studio.

You can, however, use commercial tools such as XML Spy from Altova (http://www.altova.com), Stylus Studio from Sonic Software (http://www.stylusstudio.com), or as I use a simple freeware tool called "Visual XPath" (http://weblogs.asp.net/nleghari/articles/27951.aspx). It is very useful to use such tools so you can experiment with XPath and easily create the right XPath query you need plus visually verify that you got the expected result. Here are a few more examples to study:

Sample 1

/descendant::JobTitle[ancestor::Employee/@ID=2]

Selects all descendant JobTitle nodes that have as an ancestor an Employee node with the attribute ID value of two. The result will be as follows:

<JobTitle>
   Sr. Developer
</JobTitle>

Sample 2

//Employee[WebAddress and LastName='Salchner']/attribute::ID

Selects all descendant Employee nodes that have a WebAddress child node and a LastName child node with the value Salchner. From the result, it selects the ID attribute, which returns the values of the selected attributes. The result returns 1, the value of the selected ID attribute.

Sample 3

//JobTitle[ancestor::*/@ID=1]

Selects all descendant JobTitle nodes that have any ancestor node with an attribute ID value of one. The result is as follows:

<JobTitle>
   Sr. Enterprise Architect
</JobTitle>

Understanding the base operators, functions, and axes allows you to build very powerful XPath queries and easily select the XML elements, attributes, or nodes you require. In your filter, you can use a number of boolean and comparison expressions as well as string functions. Here is a list of the most common ones:

Expression or Function Description
and (logical and) Allows you to have two or more logical 'and' conditions in your filter. For example, the expression "//Employee[FirstName='Klaus' and LastName='Salchner']" checks for both the FirstName and LastName.
or (logical or) Allows you to have two or more logical 'or' conditions in your filter. The expression "//Employee[FirstName='Klaus' or FirstName='Peter']" checks for nodes that have as FirstName either Klaus or Peter.
= (equal operator) For example, "//FirstName[.='Klaus']".
!= (unequal operator) For example, "//FirstName[.!='Klaus']".
not() (not operator) For example, "//Employee[not(FirstName='Klaus')]".
"<=" or "&lt;=" (less then equal operator) For example, "//Employee[@ID<=1]".
"<" or "&lt;" (less then operator) For example, "//Employee[@ID<2]".
">=" or "&gt;=" (greater equal operator) For example, "//Employee[@ID>=2]".
">" or "&gt;" (greater operator) For example, "//Employee[@ID>2]".
position() Returns the position or index relative to all the selected nodes. The expression "//Employee[position()=1]" returns the first Employee node.
last() Returns the position or index of the last of all selected nodes. The expression "//Employee[position()=last()]" returns the last Employee node.
concat() Concatenates two strings together. You can specify two string literals or actual node names. The following expression, //Employee[concat(FirstName,LastName)=concat('Klaus','Salchner')], concatenates the FirstName and LastName together and compares them to the concatenated string literals 'Klaus' and 'Salchner'. All matching nodes are returned.
contains() Checks whether the first string contains the second string. You can specify node names or string literals. The following expression, "//Employee[contains(FirstName,'Kl')]", returns all nodes containing the string 'Kl' in the FirstName node.
starts-with() Checks whether the first string starts with the second string. You can specify node names or string literals. The following expression, "//Employee[starts-with(FirstName,'Kl')]", returns all nodes starting with the string 'Kl' in the FirstName node.
substring-after() Checks whether the first string contains the second string and returns the remaining string after the first occurrence. The expression "//Employee[substring-after(FirstName,'Kl')='aus']" first looks whether the string 'Kl is included in the FirstName node and returns the remaining string after the first occurrence. The FirstName node containing 'Klaus' contains the string 'Kl' and the remaining string returned is 'aus'. It selects all nodes that match this criteria.
substring-before() Checks whether the first string contains the second string and returns the preceding string before the first occurrence. The expression "//Employee[substring-before(FirstName,'aus')='Kl']" first looks whether the string 'aus is included in the FirstName node and returns the preceding string before the first occurrence. The FirstName node containing 'Klaus' contains the string 'aus' and the preceding string returned is 'Kl'. It selects all nodes which match this criteria.
substring() Returns a sub-string starting at the position specified and with the number of characters specified. This allows you to cut out a sub-string from the specified string. You can specify a node or string literal. The expression "//Employee[substring(FirstName,2,3)='lau']" takes the node FirstName and returns a sub-string starting at position two for three characters in length. The FirstName node containing 'Klaus' returns the sub-string 'lau'. It selects all nodes that match this criteria.
string-length() Returns the length of a string. You can give a node name or string literal. The expression "//Employee[string-length(LastName)>=8]" returns all nodes that have a LastName node of greater or equal of eight characters.

The table does not contain a complete list but explains the most common expression and functions. For a complete list, please refer to the XPath standard.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

XPath Introduction


XPath is a language for finding information in an XML document. XPath is used to navigate through elements and attributes in an XML document.

What is XPath?

  • XPath is a syntax for defining parts of an XML document
  • XPath uses path expressions to navigate in XML documents
  • XPath contains a library of standard functions
  • XPath is a major element in XSLT
  • XPath is a W3C Standard

XPath Path Expressions

XPath uses path expressions to select nodes or node-sets in an XML document. These path expressions look very much like the expressions you see when you work with a traditional computer file system.

XPath Standard Functions

XPath includes over 100 built-in functions. There are functions for string values, numeric values, date and time comparison, node and QName manipulation, sequence manipulation, Boolean values, and more.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

X509Chain Class


Namespace: System.Security.Cryptography.X509Certificates
Assembly: System (in system.dll) 

The X509Chain object has a global error status called ChainStatus that should be used for certificate validation. The rules governing certificate validation are complex, and it is easy to oversimplify the validation logic by ignoring the error status of one or more of the elements involved. The global error status takes into consideration the status of each element in the chain.

The following code example opens the current user's personal certificate store, allows you to select a certificate, then writes certificate and certificate chain information to the console. The output depends on the certificate you select.

using
System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.IO;

class TestX509Chain
{
    static void Main(string[] args)
    {
        //Create new X509 store from local certificate store.
        X509Store store = new X509Store("MY", StoreLocation.CurrentUser);
        store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite);

        //Output store information.
        Console.WriteLine ("Store Information");
        Console.WriteLine ("Number of certificates in the store: {0}", store.Certificates.Count);
        Console.WriteLine ("Store location: {0}", store.Location);
        Console.WriteLine ("Store name: {0} {1}", store.Name, Environment.NewLine);
   
        //Put certificates from the store into a collection so user can select one.
        X509Certificate2Collection fcollection = (X509Certificate2Collection)store.Certificates;
        X509Certificate2Collection collection = X509Certificate2UI.SelectFromCollection(fcollection, "Select an X509 Certificate", "Choose a certificate to examine.", X509SelectionFlag.SingleSelection);
        X509Certificate2 certificate = collection[0];
        X509Certificate2UI.DisplayCertificate(certificate);
        //Output chain information of the selected certificate.
        X509Chain ch = new X509Chain();
        ch.Build (certificate);
        Console.WriteLine ("Chain Information");
        ch.ChainPolicy.RevocationMode = X509RevocationMode.Online;
        Console.WriteLine ("Chain revocation flag: {0}", ch.ChainPolicy.RevocationFlag);
        Console.WriteLine ("Chain revocation mode: {0}", ch.ChainPolicy.RevocationMode);
        Console.WriteLine ("Chain verification flag: {0}", ch.ChainPolicy.VerificationFlags);
        Console.WriteLine ("Chain verification time: {0}", ch.ChainPolicy.VerificationTime);
        Console.WriteLine ("Chain status length: {0}", ch.ChainStatus.Length);
        Console.WriteLine ("Chain application policy count: {0}", ch.ChainPolicy.ApplicationPolicy.Count);
        Console.WriteLine ("Chain certificate policy count: {0} {1}", ch.ChainPolicy.CertificatePolicy.Count, Environment.NewLine);
        //Output chain element information.
        Console.WriteLine ("Chain Element Information");
        Console.WriteLine ("Number of chain elements: {0}", ch.ChainElements.Count);
        Console.WriteLine ("Chain elements synchronized? {0} {1}", ch.ChainElements.IsSynchronized, Environment.NewLine);
   
        foreach (X509ChainElement element in ch.ChainElements)
        {
            Console.WriteLine ("Element issuer name: {0}", element.Certificate.Issuer);
            Console.WriteLine ("Element certificate valid until: {0}", element.Certificate.NotAfter);
            Console.WriteLine ("Element certificate is valid: {0}", element.Certificate.Verify ());
            Console.WriteLine ("Element error status length: {0}", element.ChainElementStatus.Length);
            Console.WriteLine ("Element information: {0}", element.Information);
            Console.WriteLine ("Number of element extensions: {0}{1}", element.Certificate.Extensions.Count, Environment.NewLine);

            if (ch.ChainStatus.Length > 1)
            {
                for (int index = 0; index < element.ChainElementStatus.Length; index++)
                {
                    Console.WriteLine (element.ChainElementStatus[index].Status);
                    Console.WriteLine (element.ChainElementStatus[index].StatusInformation);
                }
            }
        }
        store.Close();
    }
}

Revoked property

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Digital Certification X509Certificate C# Asp.net


Any application of cryptography in building a secured infrastructure uses many of encryption, hashing and signature ciphers. In fact all the cryptographic solutions that are available today include a comprehensive infrastructure with many ciphers, extensive security policies, rich tools for creating, deploying and managing secure applications and other integrated set of cryptographic services. One such infrastructure that comes with Windows 2000 is Public Key Infrastructure (PKI).

The challenge for any such PKI is relating the public-key with the entity that owns it, and also the publication and management of public-keys. The standard mechanism to achieve this is digital certification. This part of the article discusses digital certificates and their implementation in FCL and Web Service Enhancements (WSE 1.0) for Microsoft .NET. It also digresses into Windows 2000 PKI. 

Digital Certification

Digital certification is an application in which a certification authority signs a special message m, containing the name of user and the users public-key in such a way that any one can verify that the message was signed by no one other than the centralized certification authority.  This message m along with its signature is called digital certificate or digital id. A typical digital certificate contains the subjects name, subjects public-key, subjects public-key algorithm and parameters, unique id of the certificate, validity period of the certificate, certificate issuer name and the issuers signature.

To understand the need for digital certification, revisit the scenario explained in Digital Signing section of Cryptographic Applications of this article where our fictitious personalities Alice and Bob exchange digitally signed messages between them. In this Alice sends a digitally signed message to Bob; Bob ensures that the message was not altered in transit by verifying the mathematical validity of the signature using the public-key of Alice (PBa). 

Alice signs the message with her private-key (PKa) of signature key-pair and sends the signature along with the message to Bob.



Bob verifies the validity of the signature using Alices public-key (PBa).

The big challenge in this solution is publicizing the Alices public-key.

1.How Bob gets Alices public-key?

2.How can Bob be sure that the key he received is Alices public-key and not someone elses?

An apparent quick solution for this problem is Alice handing over her public-key to Bob in a secured manner. But this presupposes that Alice and Bob have had some form of secured communication prior. Even If Alice publicizes her public-key in this way, it is not scalable. If she needs to have similar secured communication with say 100 more users then this process becomes a nightmare. Also for Bob getting public-key in this way and managing them is a nightmare.

If both Bob and Alice can trust some intermediary who in a secured way can bind a public-key to the owner of it, the problem will be solved. Alice can simply ask this intermediary to certify her public key. Bob needs to trust only this intermediary. He can verify that trusted intermediary certified the public-key. Since both Alice and Bob need to trust the public-key with one person, this scales for any number of users. For anyone with whom Alice needs to communicate she can send the same certificate.  Also Bob can verify the public-key for all the users who are certified by the intermediary.      

 

 

 

Alice signs the message with her private-key and sends her certificate along with the message and signature to Bob. Bob verifies the validity of the signature using Alices public-key that he extracts from the Alice certificate issued by certifying authority 

X 509 Certification 

There are three certification methods that are commonly used now 

1.Directory Methods (X 509 Certificates and CAs)

2.Referal Methods (PGP)

3.Collabrative Methods (SKIP)

 Of these X 509 devised by ITU-T is the de facto standard. X 509 digital certificates associates the public-key with the distinguished name, defined by X 500, of the user.

Certificate Chain 

 X 509 digital certificates are signed messages by themselves, wherein the certifying authority (hereafter referred as CA) is the signer of the message. CA uses public-key of its signature key pair to sign users digital certificate. However this does not solve the Bobs problem of binding the public-key to owner of it. How do Bob bind the public-key of CA to CA? Chicken and Egg Problem? Bob now needs to find a certificate issued by a superior CA attesting the identity of this CA. By doing this Bob starts constructing a chain of certificates, each attesting the subordinate CAs identity, terminating in a certificate issued by someone that Bob implicitly trusts. Such a certificate is called a trusted root certificate. Trusted root certificate forms the root of a hierarchy of public-keys/identity bindings that Bob accepts as authentic. The CA that issued the trusted root certificate is called Root-CA, and the one that issued certificate to Alice is called Issuing-CA. All the other CAs between the root and the issuing CAs are called Intermediate-CA. When Bob chooses to explicitly trust a particular trusted root certificate, he is also implicitly trusting all the certificates issued by that trusted root CA, as well as all certificates issued by any subordinate CA certified by the trusted root.

Certificate Contents

In addition to the users distinguished name and public-key, digital certificate also contain other information. Following Picture shows the content of Version 1 X 509 digital certificates.

 

Version 2 X 509 digital certificates introduced two more fields,

Issuer Unique ID: Makes the issuer name unambiguous if it is used by more than one entity.

Subject Unique ID: Makes the subject name unambiguous if it is used by more than one entity.

Version 3 X 509 digital certificates allowed adding any number of custom fields, called Extensions, to the certificate.

Following pictures shows a Version 3 X 509 digital certificate issued by the Certification Server in Windows 2000 Advanced Server.  

Following are the details of the certificate           

Version 1 Fields

Version: V3
Serial Number:
6106 C4F8 0000 0000 0002
Valid From:
Friday, December 20, 2002 7:55:34 PM
Valid To:
Monday, December 20, 2004 7:48:02 PM
Subject:
CN = w2k-as-1224.PGVIJAY.com
Public Key:
RSA (1024 bits) 3081 8902 8181 00A5 4F71 CE5C B897 BBB5 DE85 790A E590 DCD5 6720 8B65 A98F 0A56 652E BC60 DF7B 783C 9DF0 373C AFD0 B447 4BAD BF56 C940 164B 534C 4CD9 A602 87B4 EF02 C8CB F9FA 89E2 53CB 350D 6096 416B EB16 E9F8 8DA2 5769 112F 3DE4 28FE 6CF5 9673 8093 A65A 3BB7 C420 9A7E 718E CF64 2725 3E71 F6A7 4E00 9A00 38B8 7F9F FC39 DD0E 9255 437B 5F02 0301 0001
Issuer:
CN = Pgvijay, OU = pgvijay home, O = pgvijay Inc, L = Stamford, S = ct, C = US, E = pgvijay@msn.com
Signature Algorithm:
sha1RSA

Version 2 Fields
Subject Key Identifier:
2377 9A5E EA96 93A3 7409 021E FCDA B713 A368 0C34
Authority Key Identifier:
KeyID=BF9A 4988 5536 A242 7512 9AE2 FC68 CF27 6CA6 C283 Certificate Issuer: Directory Address: CN=Pgvijay, OU=pgvijay home, O=pgvijay inc, L=Stamford, S=ct, C=US, E=pgvijay@msn.com Certificate Serial Number=6D81 BF9C E657 C88B 42FD A72C 44D3 39E6

Version 3 Fields
Key usage:
Digital Signature, Key Encipherment (A0) See the side bar 2.
Enhanced Key Usage:
Client Authentication (1.3.6.1.5.5.7.3.2), Server Authentication (1.3.6.1.5.5.7.3.1)
Certificate Template:
Domain Controller
Subject: Alternative Name:
Other Name: 1.3.6.1.4.1.311.25.1=0410 9BF6 C540 6777 CD4C 965F 82D4 ADE4 7440 DNS Name=w2k-as-1224.PGVIJAY.com

CRL Distribution Point: 

[1]CRL Distribution Point

Distribution Point Name:
Full Name:
              
URL=ldap:///CN=Pgvijay,CN=w2k-as-1224,CN=CDP,CN=Public%20Key%20Services,CN=Services,CN=
Configuration,DC=PGVIJAY,DC=com?certificateRevocationList?base?objectclass=cRLDistributionPoint

[2]CRL Distribution Point

Distribution Point Name:

Full Name:

            URL=http://w2k-as-1224.pgvijay.com/CertEnroll/Pgvijay.crl

Authority Information Access:

[1]Authority Info Access

     Access Method=Certification Authority Issuer(1.3.6.1.5.5.7.48.2)

     Alternative Name:

          URL=ldap:///CN=Pgvijay,CN=AIA,CN=Public%20Key%20Services,CN=Services,CN=Configuration,DC=PGVIJAY,DC=com?cACertificate?base?objectclass=certificationAuthority

[2]Authority Info Access

     Access Method=Certification Authority Issuer(1.3.6.1.5.5.7.48.2)

     Alternative Name:

          URL=http://w2k-as-1224.pgvijay.com/CertEnroll/w2k-as-1224.PGVIJAY.com_Pgvijay.crt

Thumbprint Algorithm: sha1

Thumbprint: 8C14 83A7 CAAE ED61 DCBE A15E 7E9A B2A0 7713 F138

 

Certificate Revocation Lists 

A certificate revocation list (CRL) is the list of certificates that were revoked by the CA for some reason like the subjects private key being compromised. CA publishes the CRL at well-known places. Certificate issued by the Certificate Server of Windows 2000 PKI has the pointer to CRL also in it as a version 3 extension. 

The above certificate states that the CRL will be published in

1.Web server (http://w2k-as-1224.pgvijay.com/CertEnroll/Pgvijay.crl)

2.Active directory server (ldap:///CN=Pgvijay,CN=w2k-as-1224,CN=CDP,CN=Public%20Key%20Services,CN=Services,CN=Configuration,
 DC=PGVIJAY,DC=com?certificateRevocationList?base?objectclass=cRLDistributionPoint)
     

Certificate Trust Lists 

A certificate trust list (CTL) enables controlling the trust of the purpose and of the validity period of certificates that are issued by any external certification authorities (Windows 2000 PKI comes with Certificate Server and this becomes Internal certificate authority in the domain. Any CA that is not part of Windows 2000 domain, like Verisign etc, becomes external certificate authority). Typically, a certification authority issue certificates for a wide variety of purposes, such as secure e-mail or client authentication. But in situations when the trust of these certificates is to be limited, a certificate trust list is created. Suppose, for example, a certification authority named Abc CA is capable of issuing certificates for server authentication, client authentication, code signing, and secure e-mail. However, the certificates issued by Abc CA needs to be trusted only for the purpose of client authentication, a certificate trust list that limit the purpose for which certificates issued by Abc CA to client authentication is created. Any certificates issued for another purpose by Abc CA are not accepted for use by any computer to which this certificate trust list is applied. 

Digital Certificate Support in CryptoAPI

Physical Store

Physical certificate store provides a grouping of certificates, certificate revocation lists (CRLs), and certificate trust lists (CTLs). Certificate store has only the pointers to the certificates and not the certificate themselves; instead certificates are persisted in permanent storages like file, registry (local or remote machine), active directory server, and smart card etc. Physical stores in turn are also located in different physical storages as the certificates. They can also be created on memory for temporary purposes. 

Certificate Store Providers

CryptoAPI has predefined store provider types for different locations where a physical store can be persisted.

Logical Stores 

Sometime a certificate might need to be member of several different logical groups. For this a logical collection of physical stores, called logical stores, is used. Any operation performed on the logical store is performed on the underlying physical stores. For instance, opening the logical store opens all the underlying physical stores, enumerating the certificates in the logical store enumerates all the certificates in all the underlying physical stores etc., An individual physical store can be a member of more than one logical store.

System Stores

Microsoft Windows 2000 comes with five predefined logical collection stores, namely MY, CA, TRUST, ROOT and USERDS. These stores are called system stores. Each of the following system store location has some or all of these system stores; and in addition they can also have other user created logical stores.

 As said before every logical store in each of above locations have associated physical stores. For instance system stores at Current User has the following physical store association 

Following picture shows a sample association between MY system store and the physical stores.

For more details on the store location please refer MSDN.

Key Databases in Cryptographic Service Providers (CSP)

Cryptography Service Providers in CrytpAPI persists the asymmetric key pairs across multiple sessions in a key database. These key databases have multiple key containers, which are identified by unique names. Windows creates a key container for each user of the machine. The key container is named after the user name. All the keys that belong to the user are kept in this container.

There are usually two key pairs in each container: key-exchange key pair and signature key pair. While the former is used to encrypt session keys, the later is used to create digital signatures. (For more details refer previous parts of this article).

Microsoft CSPs stores their key database in two different locations based on the type of the application, interactive standalone applications or non-interactive service applications. While Windows NT keeps the key containers in registry, Windows 2000 keeps them in file. Windows NT keeps key-database under the registry keys HKEY_CURRENT_USER\Software\Microsoft\Cryptography\UserKeys and HKEY_LOCAL_MACHINE\Software \Microsoft\Cryprography\MachineKeys for stand-alone applications and for non-interactive service applications respectively. Windows NT keeps key-database in a file under directories \Documents and settings\\Application Data\Microsoft\Crypto\RSA\ and \Documents and settings\All Users\Application Data\Microsoft \Crypto\RSA\Machinekeys for stand-alone applications and for non-interactive service applications respectively.  

Cryptography Support in Microsoft.Net 

System.Security.Cryptography.X509Certificates namespace provides classes to work with X509v3 Digital Certificates. 

However the namespace does not have full support to work with digital certificates, for instance there is no support for very important tasks such as

1.Loading certificates from a certificate store.
2.Finding the private-key associated with the public-key of digital certificate, from the key database.
3.Reading X509 Version 2 Fields (Loads a v2 certificate but does not have methods to get the fields)
4.Reading X509 Version 3 Fields (Loads a v3 certificate but does not have methods to get the fields)
5.Working with CRL and CTL.

However X509Certificate class provides static methods to load a certificate from a file.

public static X509Certificate CreateFromCertFile(string filename); 

Following snippet shows how to load a certificate from file msn.cer/. 

Following is the output generated by the above snippet. Output is edited for brevity. 

1.2.840.113549.1.1.1 is the OID for RSA. For more details refer MSDN 

Following picture shows the msn.cer certificate used by MSN. The certificate is available as a part of the attached sample. 

 

Web Service Extensions for Microsoft.Net 

Microsoft.Web.Services.Security.X509 namespace of Web Service Extensions (WSE 1.0) attempts to bridge the gap between the extensive X509 support in CrytpoAPIs and the limited X509 support in FCL. It has an X509Certificate class, which derives from the X509Certificate in the FCL. It also has a class to work with Certificate store X509CertificateStore. To use WSE a reference to Microsoft.Web.Services.dll should be added to the project. 

Microsoft.Web.Services.Security.X509.X509Certificate class has a property to find the associated private key. 

Microsoft.Web.Services.Security.X509.X509Certificate first finds the public-key, the asymmetric algorithm of the public-key and the subject name from the certificate. Then it attempts to load the default CSP that can work with the asymmetric key cipher in the certificate. In this sample the public-key cipher is RSA and the key size of 1024 bits (certificate file is attached with the sample). So it attempts to load "Microsoft Enhanced Cryptographic Provider v1.0" CSP using System.Security.Cryptography.RSACryptoServiceProvider. Then it attempts to load the corresponding private-key from the key container named after the subject-name (in this sample pgvijay) from the CSPs key database. 

Following snippet shows how to use it. 

Certificate Store in WSE 1.0

Microsoft.Web.Services.Security.X509.X509CertificateStore class provides partial CryptoAPI certificate store support. The X509CertificateStore class constructor takes the store provider, store location and store name. 

public X509CertificateStore(X509CertificateStore.StoreProvider provider,  X509CertificateStore.StoreLocation location, string storeName); 

It only supports four store providers, namely system, file, collection and memory; but all the store locations defined by the CryptoAPI. 

X509CertificateStore class provides methods to search for certificates based on subject name, key identifier and the hash value. Following snippet shows one such code 

 Following snippet shows how to find the asymmetric key pair when given the subject name of the certificate.     

Certificate Services in Windows 2000 

Windows 2000 Public Key Infrastructure comes with a Certificate Server. To generate a certificate for a user using the certificate server navigate to the CertServ Web Application installed in the CA Server (http://w2k-as-1224/CertSrv/). 

 

Select Request a certificate in this page and say Next. 

Select Advanced request in this page and say Next 

 Select Submit a certificate request to this CA using a form. In this page and say Next

Fill up the page as shown above. This creates a 1024 bits RSA key-pair and stores the key set in the key container BobKeys of the CSP Microsoft Base Cryptographic Provider v1.0. The key set can be user as both signature key pair and key exchange key pair. 

Selecting Install this certificate will install the certificate in the default store of the local machine.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Read Response of a web request in a byte Array with C# Asp.net


this code snippet read the respone fo a web request through binary reader
 
private byte[] getByte(string URL)
{
HttpWebRequest wrGETURL = (HttpWebRequest)WebRequest.Create(URL);
System.Net.HttpWebResponse webresponse = (HttpWebResponse)wrGETURL.GetResponse();
string ct = webresponse.ContentType;
Stream objStream = webresponse.GetResponseStream();
BinaryReader breader = new BinaryReader(objStream);
byte[] buffer = breader .ReadBytes((int)webresponse.ContentLength);
return buffer;
}
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Force a page to download a file c# asp.net


string Id= "0";
try
{
this.EnableViewState = false;
Response.ContentType = "text/.txt";
string Filename = System.Web.HttpContext.Current.Server.MapPath("txt/");
Filename = Filename + Id + ".txt";
Response.WriteFile(Filename);
// Response.Write("string");
string strFilename = Id + ".txt";
Response.Buffer = true;
Response.AddHeader("Content-Disposition", "attachment; filename=" + ID+".txt");
}
catch (Exception ex) { Response.Write(ex.ToString()); }
Response.End();
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Create .VCF File(outlook contact file) with C#


This is code of to create vcf card on the fly
 
//sdBuild is string builder

sdBuild.Append("N:" + strCn + System.Environment.NewLine);
sdBuild.Append("FN:" + strCn +System.Environment.NewLine);
//// encoding to base 64
certString64 = certString64 + System.Environment.NewLine + "KEY;X509;ENCODING=BASE64:" + System.Environment.NewLine;
certString64 = certString64 + Convert.ToBase64String((byte[])valuess) + System.Environment.NewLine;
//// encoding to base 64 ends here
sdBuild.Append(certString64);

sdBuild.Append(System.Environment.NewLine+"ORG: None;"+System.Environment.NewLine);
sdBuild.Append("TITLE:" + strTitle +System.Environment.NewLine);
sdBuild.Append("NOTE;ENCODING=QUOTED-PRINTABLE:This is a note associated with this"+System.Environment.NewLine);
sdBuild.Append("contact=0D=0A"+System.Environment.NewLine);
sdBuild.Append("TEL;WORK;VOICE:"+System.Environment.NewLine);
sdBuild.Append("TEL;HOME;VOICE:" + strHomePh +System.Environment.NewLine);
sdBuild.Append("TEL;CELL;VOICE:" + strMobile +System.Environment.NewLine);
sdBuild.Append("TEL;WORK;"+System.Environment.NewLine);
sdBuild.Append("ADR;WORK:;;" + strState + ";" + strCo +System.Environment.NewLine);
sdBuild.Append("LABEL;WORK;ENCODING=QUOTED-PRINTABLE:" + strCo +System.Environment.NewLine);
sdBuild.Append("751234 =0D=0AUnited States of America" +System.Environment.NewLine);
sdBuild.Append("URL:"+System.Environment.NewLine);
sdBuild.Append("URL:"+System.Environment.NewLine);
sdBuild.Append("EMAIL;PREF;INTERNET:" + streMail +System.Environment.NewLine);
sdBuild.Append("REV:"+System.Environment.NewLine);
sdBuild.Append("END:VCARD");
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

How to change the ower of tables in Microsoft SQL Server database


To do this, execute the following command on every table

exec sp_changeobjectowner '?????', 'DBO' - where ????? is the name of your database table.

Also below is the stored procedure through which you can change the owner for every table in the database.

EXEC sp_changeobjectowner @oldownerplusobject, @new

create procedure _ChangeObjectOwner (@type varchar(1),@old varchar(20),@new

varchar(20))

as

declare @ObjectName varchar(100)

declare @oldownerplusobject varchar(50) begin declare Cursor_Object cursor for select [name] from sysobjects where type=@type and xtype=@type open Cursor_Object FETCH NEXT FROM Cursor_Object INTO @ObjectName WHILE @@FETCH_STATUS = 0 begin

set @oldownerplusobject=@old+'.'+@ObjectName

EXEC sp_changeobjectowner @oldownerplusobject, @new

print 'Permission Changed for ' + @oldownerplusobject +' to ' + @new + ' :

Process Done'

FETCH NEXT FROM Cursor_Object INTO @ObjectName end close Cursor_Object deallocate Cursor_Object end

exec _ChangeObjectOwner 'p','xxx','yyy'
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

How to change the ower of tables in Microsoft SQL Server database


To do this, execute the following command on every table

exec sp_changeobjectowner '?????', 'DBO' - where ????? is the name of your database table.

Also below is the stored procedure through which you can change the owner for every table in the database.

EXEC sp_changeobjectowner @oldownerplusobject, @new

create procedure _ChangeObjectOwner (@type varchar(1),@old varchar(20),@new

varchar(20))

as

declare @ObjectName varchar(100)

declare @oldownerplusobject varchar(50) begin declare Cursor_Object cursor for select [name] from sysobjects where type=@type and xtype=@type open Cursor_Object FETCH NEXT FROM Cursor_Object INTO @ObjectName WHILE @@FETCH_STATUS = 0 begin

set @oldownerplusobject=@old+'.'+@ObjectName

EXEC sp_changeobjectowner @oldownerplusobject, @new

print 'Permission Changed for ' + @oldownerplusobject +' to ' + @new + ' :

Process Done'

FETCH NEXT FROM Cursor_Object INTO @ObjectName end close Cursor_Object deallocate Cursor_Object end

exec _ChangeObjectOwner 'p','xxx','yyy'
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

LDAP Get Info from Active Directory


To retrive all imformation from avtive directory through ldap protocol
 
 
using objX509Cert = System.Security.Cryptography.X509Certificates;

string filter = "mail=*";
xd = lcl.LDAPInfo(filter);

public XmlDocument LDAPInfo(string filter)
{
XmlDocument xd = new XmlDocument();
string domainAndUsername = string.Empty;
string userName = string.Empty;
string passWord = string.Empty;
string Sur = "";
string Cn = "";
string Name = "";
string GName = "";
string DGname = "";
string Member = "";
string Init = "";
string Postal = "";
string Loc = "";
string C = "";
string Mobile = "";
string HomePh = "";
string Title = "";
string Co= "";
string State = "";
string eMail = "";

string Password = "";
string SAM = "";

string MemOf = "";
string UID = "";
string Desc = "";
string UserCert = "";
string UserCertName = "";
string certno = "";
string certString64="";

Boolean chkpass = false;
AuthenticationTypes at = AuthenticationTypes.Anonymous;
StringBuilder sbb = new StringBuilder();


//****Connecting to LDAP active directory
domainAndUsername = @"LDAP://YourDomain/c=CH";
userName = "username" ;
passWord = "password";
//at = AuthenticationTypes.Secure;

//Create the object necessary to read the info from the LDAP directory
DirectoryEntry entry = new DirectoryEntry(domainAndUsername,userName, passWord,at);
DirectorySearcher mySearcher = new DirectorySearcher(entry);
SearchResultCollection results;
mySearcher.Filter = filter;

try
{
results = mySearcher.FindAll();

if (results.Count > 0)
{
sbb.Append("");
foreach(SearchResult resEnt in results)
{
sbb.Append("");
ResultPropertyCollection propcoll=resEnt.Properties;
//sbb.Append("" + propcoll.PropertyNames.Count+"");
Sur = "";
Cn = "";
Name = "";
GName = "";
DGname = "";
Member = "";
Init = "";
Postal = "";
Loc = "";
C = "";
Mobile = "";
HomePh = "";
Title = "";
Co = "";
State = "";
Password = "";
SAM = "";
MemOf = "";
UID = "";
Desc = "";
UserCert = "";
UserCertName = "";
certString64="";
//string vCardn;

StringBuilder strBMails = new StringBuilder();
StringBuilder strBCert = new StringBuilder();

foreach(string key in propcoll.PropertyNames)
{
string values = "";
if (propcoll[key].Count > 0)
values = propcoll[key][0].ToString();

#region Switch
switch (key)
{
case "sn":
Sur = values.ToString();
break;
case "cn":
Cn = values.ToString();
break;
case "name":
Name = values.ToString();
break;
case "givenname":
GName = values.ToString();
break;
case "distinguishedname":
DGname = values.ToString();
break;
case "member":
Member = values.ToString();
break;
case "initials":
Init = values.ToString();
break;
case "postalcode":
Postal = values.ToString();
break;
case "l":
Loc = values.ToString();
break;
case "c":
C = values.ToString();
break;
case "mobile":
Mobile = values.ToString();
break;
case "homephone":
HomePh = values.ToString();
break;
case "title":
Title = values.ToString();
break;
case "co":
Co = values.ToString();
break;
case "st":
State = values.ToString();
break;
case "mail":
BMails.Append("");
foreach (object valuess in propcoll[key])
{
eMail = valuess.ToString();
strBMails.Append("" + valuess.ToString() + "");
}
strBMails.Append("");
break;
case "password":
strPassword = values.ToString();
break;
case "samaccountname":
strSAM = values.ToString();
break;
case "memberof":
strMemOf = values.ToString();
break;
case "uid":
strUID = values.ToString();
break;
case "description":
strDesc = values.ToString();
break;
case "usercertificate;binary":
strBCert.Append("");
foreach (object valuess in propcoll[key])
{
FileStream fs = File.Create("./tempcer1.cer");
BinaryWriter bw = new BinaryWriter(fs);
bw.Write((byte[])valuess);
bw.Close();

objX509Cert.X509Certificate myCert = objX509Cert.X509Certificate.CreateFromCertFile("./tempcer1.cer");


strBCert.Append("" + myCert.GetSerialNumberString() + "");
strBCert.Append("" + myCert.GetName() + "");
strBCert.Append("" + myCert.GetExpirationDateString() + "");

strcertno = myCert.GetSerialNumberString();
FileInfo fi = new FileInfo("./tempcer1.cer");
if (File.Exists(myCert.GetSerialNumberString() + ".cer"))
File.Delete(myCert.GetSerialNumberString() + ".cer");
fi.MoveTo(myCert.GetSerialNumberString() + ".cer");

string cerPath = System.Web.HttpContext.Current.Server.MapPath("./Certificate/");
if (File.Exists(cerPath + myCert.GetSerialNumberString() + ".cer"))
File.Delete(cerPath + myCert.GetSerialNumberString() + ".cer");
fi.CopyTo(cerPath + myCert.GetSerialNumberString() + ".cer");
chkpass = true;

}
strBCert.Append("");
break;
}
#endregion

}
sbb.Append("" + strSur + "");
sbb.Append("" + strCn + "");
sbb.Append("" + strName + "");
sbb.Append(strBMails);
sbb.Append(strBCert);
sbb.Append("" + strGName + "");
sbb.Append("" + strGName + "");
sbb.Append("" + strMember + "");
sbb.Append("" + strInit + "");
sbb.Append("" + strPostal + "");
sbb.Append("" + strLoc + "");
sbb.Append("" + strC + "");
sbb.Append("" + strMobile + "");
sbb.Append("" + strHomePh + "");
sbb.Append("");
sbb.Append("" + strCo + "");
sbb.Append("" + strState + "");
sbb.Append("" +strPassword + "");
sbb.Append("" + strSAM + "");
sbb.Append("" + strMemOf + "");
sbb.Append("" + strUID + "");
sbb.Append("" + strDesc + "");
sbb.Append("");


}
sbb.Append("");


xd.LoadXml(sbb.ToString());
return xd;
}
}
catch (Exception ex)
{
string msg = ex.Message;
}
sbb.Append("No");
xd.LoadXml(sbb.ToString());
return xd;
}
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Clear Project List from Start Page


Here is a nice tips to clear the Recent project list or File list from Visual Studio .Net
Run--> RegEdit and navigate to

HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\\ProjectMRUList delete unnecessary list.

similarly for FileMRuList.

Make sure not disturb other key from the registry.
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

How to get the HTML name attribute of ASP.Net Control c# as.net


//Function to get the HTML name of the server control from the Client Id

// Parameters:

// clientId - Control.ClientId

// serverId - Control.id


private string GetHTMLNameById(string clientId, string serverId)

{

int pos = serverId.IndexOf('_');

string HTMLName = "";

if(pos >= 0)

{

pos = clientId.IndexOf(serverId);

HTMLName = clientId.Remove(pos, serverId.Length);

HTMLName = HTMLName.Replace('_', '$');

HTMLName += serverId;

}

else

HTMLName = clientId.Replace('_', '$');

return HTMLName;

}
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Lightweight Directory Access Protocol (LDAP)


In computer networking, the Lightweight Directory Access Protocol, or LDAP ("ell-dap"), is a networking protocol for querying and modifying directory services running over TCP/IP. An LDAP directory usually follows the X.500 model: it is a tree of entries, each of which consists of a set of named attributes with values. While some services use a more complicated "forest" model, the vast majority use a simple starting point for their database organization.

An LDAP directory often reflects various political, geographic, and/or organizational boundaries, depending on the model chosen. LDAP deployments today tend to use Domain Name System (DNS) names for structuring the topmost levels of the hierarchy. Further into the directory might appear entries representing people, organizational units, printers, documents, groups of people or anything else which represents a given tree entry, or multiple entries.

Protocol overview
A client starts an LDAP session by connecting to an LDAP server, by default on TCP port 389. The client then sends operation requests to the server, and the server sends responses in return. With some exceptions the client need not wait for a response before sending the next request, and the server may then send the responses in any order.

The basic operations are, in order:

Bind - authenticate, and specify LDAP protocol version,
Start TLS - protect the connection with Transport Layer Security (TLS), to have a more secure connection,
Search - search for and/or retrieve directory entries,
Compare - test if a named entry contains a given attribute value,
Add a new entry,
Delete an entry,
Modify an entry,
Modify DN - move or rename an entry,
Abandon - abort a previous request,
Extended Operation - generic operation used to define other operations,
Unbind - close the connection, not the inverse of Bind.
In addition the server may send "Unsolicited Notifications" that are not responses to any request, e.g. before it times out a connection.

A common alternate method of securing LDAP communication is using an SSL tunnel. This is denoted in LDAP URLs by using the URL scheme "ldaps". The standard port for LDAP over SSL is 636.
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Serialize & Deserialize c# asp.net


Serialize (convert an object instance to an XML document):

// Assuming obj is an instance of an object
XmlSerializer ser = new XmlSerializer(obj.GetType());
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.IO.StringWriter writer = new System.IO.StringWriter(sb);
ser.Serialize(writer, obj);
XmlDocument doc = new XmlDocument();
doc.LoadXml(sb.ToString());

Deserialize (convert an XML document into an object instance):

//Assuming doc is an XML document containing a serialized object and objType is a System.Type set to the type of the object.
XmlNodeReader reader = new XmlNodeReader(doc.DocumentElement);
XmlSerializer ser = new XmlSerializer(objType);
object obj = ser.Deserialize(reader);
// Then you just need to cast obj into whatever type it is eg:
MyClass myObj = (MyClass)obj;
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

How to convert a string to a byte array and convert a byte array to a string c# asp.net


Convert a string to a byte array

string myString = "a test string";
byte[] myByteArray = new byte[myString.Length];
int i = 0;
foreach(char c in InStr.ToCharArray())
{
myByteArray [i] = (byte)c;
i++;
}

Convert a byte array to a string

System.Text.Encoding enc = System.Text.Encoding.ASCII;
byte[] myByteArray = enc.GetBytes("a text string);
string myString = enc.GetString(myByteArray );
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Split function in MS Sql, Split string


There is no in bulit function to split values in sql. i have created a tabular function that can split a string in a table.

Create function [dbo].[StrFunc_Split]
(
@InputStr nvarchar(4000),
@SplitChar nchar
)
returns @Splittings table
(
Position int,
Value nvarchar(4000)
)
as
begin
declare @Index int,
@LastIndex int,
@SNo int
set @LastIndex = 0
set @Index = charindex(@SplitChar, @InputStr)
set @SNo=0
while @Index > 0
begin
set @SNo=@SNo+1
insert into @Splittings(Position, Value)
values(@SNo, substring(@InputStr, @LastIndex, @Index - @LastIndex))
set @LastIndex = @Index +1
set @Index = charindex(@SplitChar, @InputStr, @LastIndex)
end
set @SNo=@SNo+1
insert into @Splittings(Position, Value)
values(@SNo, substring(@InputStr, @LastIndex, len(@InputStr) - @LastIndex + 1))
return
end
------------------------------------------------
to use this function

select * from StrFunc_Split('asdsad,asdsa,ff,fe3,5d,',',')
-------------------------------------------------


create FUNCTION [dbo].[getM]
(@idss varchar(8000))
RETURNS varchar(8000)
AS
BEGIN
declare @cnt int
--select @return = 'ff'
select @cnt=count(*) from(select id from tbl_ where id in(select value from StrFunc_Split(@idss,','))) as cnt
declare @i int
declare @ids varchar(1000)
set @ids='0'
declare @id varchar(10)
set @i=0
declare @return varchar(8000)
set @return=''
declare @mSch varchar(1000)
while @i<@cnt begin select top 1 @mSch=id,@id=id from ( select top 200 nam,id from tbl_ where id in(select value from StrFunc_Split(@idss,',')) and id not in(select value from StrFunc_Split(@ids,',')) order by id ) as tbl order by id desc if len(@return) = 0 set @return = isnull(@mSch,'') else set @return=@return+'
'+isnull(@mSch,'')
set @ids=@ids+','+@id
set @i=@i+1
end
return @return
end
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Diff DataReader/DataAdapter


The DataReader provides forward, read-only access to the data read from the database. It provides no mechanisms for randomly accessing the data.

A DataAdapter, along with a DataTable or DataSet, provides random access to data. In addition, the data can be changed in the DataTable or DataSet, and the DataAdapter can be used to update the data in the database.

Of the two access methods, the DataReader is the lightest and fastest and is preferable when you need to only read the data, as reflected in the results we show for our sample application in. in an example reads 10KB and 100KB records from a SQL Server database table containing 500KB rows. The table contains five columns, of which three are retrieved in the query. The data indicates that using a DataAdapter is anywhere from 3868% slower than using a DataReader.
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Preventing Multiple Logins in ASP.NET


We talked about the fact that the classic ASP Session_OnEnd handler is widely known to be pretty unreliable. However, in ASP.NET the corresponding Global class handler, Session_End, is very reliable. Then we talked about "what if" scenarios, such as what if the ASP.NET worker process was recycled? If so, I reasoned, it didn't matter whether you were using Session, Application or Cache, all of your stuff would be lost. The only exceptions to this would be if you were using the ASP.NET State Server service for your Session, or the SQL Server Session option. In particular, there is a second script available for the SQL Server Session option that does not use the TempDB, and this means that even if the whole machine goes down, when it comes back up, the Session data will still be there. Both StateServer and SQL Server Session options run out of process, so it really doesn't matter if the ASPNET_WP.EXE worker process is recycled - the sessions, which run out of the ASP.NET worker process and rely on the Session  Cookie that's stored at the browser, will still be there.

The main issue is that if you put some sort of "lock" on the user record because somebody has logged in, and then they close their browser and you don't have a reliable way of determining that their session has expired so you can remove the lock, you are likely to get calls to your Tech Support desk from users complaining they cannot log in! (trust me, I have good reports that this has happened...)

The big problem, it turns out, is that with StateServer and SQL Server Sessions, the Session_End event in Global is never fired. Only InProc mode fires this. So in order to avoid Tech Support coming after us with hatchets and knives, we would need to come up with some sort of reliable surrogate for the Session_End event. Robbe took off on his own angle  here and wrote an excellent article about using the Cache class to handle some of these issues. You can read it here. Robbe also discusses how to use the callback mechanism in the Cache class to handle the situation where the item is removed from the Cache. In fact, he's determined that this even fires when the ASP.NET worker process recycles under normal conditions (such as when specified in machine.config), thereby enabling us to serialize Cache items to a database for later rehydration.

As it often turns out, sometimes the simplest solution to a problem is also the most elegant and even the most scalable. The solution to the multiple login problem that I came up with and present here simply uses the Cache with SlidingExpiration as a surrogate for a Session_End event. First, here's the logic:

1) User logs in, we check the Cache using username+password as the key for the Cache Item. If the Cache item exists, we know that the login is already in use, so we kick them out. Otherwise, we authenticate them (database, etc) and let them in.

2) After we have let them in, we set a new Cache item entry with a key consisting of their username+password, with a sliding expiration equal to the current Session Timeout value. We can also set a new Session variable, Session["user"], with a value of the username+password, so that we can do continuous page request checking and Cache updating on every page request during the user's session. This gives us the infrastructure for "duplicating" the missing Session_End functionality.

3) Now we need a way to update the Cache expiration on each page request. You can do this very elegantly in the Application_PreRequestHandlerExecute handler in Global, because the Session object is available and "live" in this handler. In addition, this event is fired on every page request, so we don't need to put a single line of extra code in any of our pages. We use the Session["user"] value to get this user's key to retrieve their Cache Item, thus resetting it and automatically setting the sliding expiration to a fresh timeout value. Whenever you access a Cache item, its SlidingExpiration property (if properly configured) is automatically updated. When a user abandons their session and no pages are requested for a period of time, the SlidingExpiration
of their Cache Item eventually expires, and the item is automatically removed
from the Cache, thereby allowing somebody with the same username and password to log in again. No fuss, no muss! Works with InProc, StateServer and SQL Server Session modes!

Now let's take a look at some code as to how this can be implemented, in its most basic form:

In web.config (StateServer mode, with a one minute timeout to make testing easier):



&lt;sessionState

mode="StateServer"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data
source=127.0.0.1;user id=sa;password=letmein"
cookieless="false"

timeout="1"
/&gt;


In Global.asax.cs:
protected
void Application_PreRequestHandlerExecute(Object sender, EventArgs
e)
{
// Let's write a message to show this got
fired---

Response.Write("SessionID: "
+Session.SessionID.ToString() + "User key: " +(string)Session["user"]);

if(Session["user"]!=null) // e.g. this is after an
initial logon

{
string
sKey=(string)Session["user"];
// Accessing the
Cache Item extends the Sliding Expiration automatically

string
sUser=(string)
HttpContext.Current.Cache[sKey];
}
}


In your Login Page "Login" button handler:

private void Button1_Click(object sender, System.EventArgs e)
{

//validate your user here (Forms Auth or Database,
for example)
// this could be a new "illegal" logon, so we need to
check
// if these credentials are already in the Cache

string sKey=TextBox1.Text+TextBox2.Text;
string
sUser=Convert.ToString(Cache[sKey]);
if (sUser==null
sUser==String.Empty){
// No Cache item, so sesion
is either expired or user is new sign-on
// Set the cache item and
Session hit-test for this user---

TimeSpan SessTimeOut=new
TimeSpan(0,0,HttpContext.Current.Session.Timeout,0,0);
HttpContext.Current.Cache.Insert(sKey,sKey,null,DateTime.MaxValue,SessTimeOut,

System.Web.Caching.CacheItemPriority.NotRemovable,null);
Session["user"]=TextBox1.Text+TextBox2.Text;
// Let them in - redirect to main page,
etc.

Label1.Text="&lt;Marquee&gt;&lt;h1&gt;Welcome!&lt;/h1&gt;&lt;/marquee&gt;";

}
else
{
// cache item exists, so too bad...

Label1.Text="&lt;Marquee&gt;&lt;h1&gt;&lt;font
color=red&gt;ILLEGAL LOGIN
ATTEMPT!!!&lt;/font&gt;&lt;/h1&gt;&lt;/marquee&gt;";
return;
}

}


You can try logging in with any username / password you want. If you try again, you won't get in (unless you wait long enough for the Cache Item to expire). Each time you try, the SlidingCache timeout property of the Cache item gets updated (same with any page request). You can try logging in from another browser window, or even another machine. It doesn't matter, you won't be able to abuse the Big Brother license login policy.

There are certainly trade-offs to be considered when dealing with Sessions on a web farm. StateServer normally is set up to act as a central session server for all the servers in a web farm. By definition, you have to pick a machine and all the web.config entries point to the IP address of that machine. However, I know of at least one organization that uses StateServer on each and every machine on a web farm, and sticky IP to make sure that everybody always returns to the machine where their Session was started. While this configuration might seem like "shooting yourself in the foot", it is conceiveable that an organization might opt for this where redundancy, rather than scalability, is the overriding consideration. (Of course, if you have StateServer and Sticky IP on every machine in the farm, and only one SQL Server with no clustering and failover, the jury might still be out on how much redundancy you have actually achieved).

If your overriding concern is that the particular StateServer machine may "go down" then your only other option would be to use the SQL Server session mode and choose the SQL Script
"InstallPersistSqlState.sql" which specifically does not use the TempDB (TempDB disappears when a machine is rebooted).

There is no sharing of cache between web applications on a farm. Also it was brought to my attention by reader Paul Abraham (who has provided helpful comments on more than one occasion here) that if we have a multi-processor machine, we can configure it to webgarden mode, in which case we will have more than one worker process. Consequently, we will then have more than one instance of the System.Web.Caching.Cache class operative in our
application. (one instance of this class is created per application domain) In this context, we would then have the same problem synchronizing Cache in WebGarden mode that we would in a web farm scenario

In these situations, you can be creative with CacheDependency and CacheItemRemovedCallback. For example, on each web server (or AppDomain) your cache objects can depend on a special file, and on cache addition or removal touch that file so that cache objects on other web servers can get notified and be removed. Now that I think of it, you could even use the very same file that the dependency is created on to store the data that each server needs to get in order to update its Cache.

There is a bug in ASP.NET 1.0 where multiple web applications having cachedependency on a file at a UNC share is not working. So one workaround is to have one file per web application per web server, and during update you would touch all of them. Another thing to remember about a server farm - if you are sharing Session state with StateServer or SQL Server, the SessionID, which is contained in a browser cookie or munged on the URL does get transmitted for the
particular user no matter which server their request lands on.

So if you match the ASP.NET Session ID to the username+Password of the login, you have a method to check the Cache on any of the servers to handle both session checking and timeout updating. There is also an excellent article by David Burgett on MSDN about using in-memory Datasets and a WebService to synchronize data in a farm.

Cache Synchronization Down on the Farm

While creating a shared Cache object among servers on a farm is beyond the scope of this article, it is definitely "do-able" and hopefully the above ideas will give you some food for thought. Synchronization of Cache on a server farm is one thing that Mircrosoft left out of the Cache class. However, based on the ideas brought up in this article, it can be seen that there are likely a number of uses for such an arrangement.

One way to set up Cache synchronization among servers in a web farm is to use SQL Server and have two tables - one with a list of the servers currently active in the web farm, and a second table to hold "Update" information for the cache. This "CacheItems" table would probably
need at least three or four columns: a varchar column for the cache "key" (in this case username+password), a DateTime column for current Sliding Expiration value, another DateTime column for Absolute Expiration (if used), and finally an IMAGE column to hold the byte stream from the serialized Object Graph of the Cache item, using the BinaryFormatter., in order to store complex objects from the Cache in the same way that SQL Server Session state does. In this manner it would be possibly not only to synchronize the Cache among servers in a farm, but to actually create a backup "Persistent Cache" datastore from which a rebooting or first - time farm member machine can hydrate its Cache and "join the chorus" , so to speak.

So for example, when a session expires in the Cache on one server, you can make an update using the SQL Server to a Cache persistent storage table. This update can made through a WebRequest which is sent to each of the servers on the farm to a special aspx receiver page that is in each app domain. This receiver page basically gets the "notification" and instructs the page to go to the SQL server and update it's resident copy of the Cache from the SQL Server table described above. Each machine would have a page that is capable of handling this process, and thus every machine on the Farm would have the capability both to update the backup store and notify the other webservers, as well as to receive a notification that it needs to retrieve and process the update record(s) from SQL Server.
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

What's New in Asp.Net 2.0


1) Application-wide registration of custom controls.
One of my biggest complaints about custom controls (and this was true of both UserControls and custom controls from a custom assembly) was that you had to put a “” directive at the top of every .aspx page from which you wanted to declare an instance of the control.

One of the main purposes of custom controls was to be able to use them from multiple .aspx pages in one application. Since controls typically encapsulate elements like menus, site navigation etc., it seems counterintuitive to me that in order to reuse that code, you have to add something to each and every page. But in ASP.NET 1.0, there has to be one Register directive for each assembly/namespace combination and one for each UserControl. If you need to add a new custom control, you have to go into every page where you want to use it, and add it manually.

In ASP.NET 2.0, you can add the Register directives to the web.config.





tagPrefix="jonishappy"
namespace="JonIsHappyNamespace"/>





You might wonder, if I was so worked up over it in ASP.NET 1.0, why it is number 10 on my list and not number 1? To be fair, despite my ranting, it was annoying, but not really life-threatening. It usually wasn't too hard to find the problem in the first place, and a simple cut-and-paste operation usually fixed the problem in seconds.


2) Programmable Configuration.
This is really a .NET runtime improvement, but it is still a big win for ASP.NET. The web.config file contains all the configuration information for an ASP.NET application. In ASP.NET 1.0, in order to change something (like a database connection string in the AppSettings element) you have to open the web.config file in the text editor of your choice.

With the new version, you can go into the configuration programmatically (without having to resort to manipulating the XML directly) and change the settings of your ASP.NET applications. This makes building things like installers, administration modules, and pages much easier.


3) Web Part controls.
Even though the personalization craze of the web has somewhat died down in recent years, there still are plenty of situations in which you will need to expose customization of pages to your end users.

With Web Parts, the ASP.NET team has given us a way to do that without writing any additional code. The WebPartZone control is used to define an “area” of the page that can be customized. Each zone can be made up of multiple parts which can be a ContentWebPart control, a custom control, or a UserControl. Used in conjunction with the WebPartManager controls, you can give your end users the ability to change where the controls in their page are displayed.


4) Posting to other pages.
One programming paradigm that ASP.NET 1.0 developers had to get used to was that the HTML forms in ASP.NET 1.0 had to have their action attribute refer back to the page that created the rendered page.

This wasn’t so much a limitation on functionality, since with Response.Redirect or Server.Transfer, moving a user from one page to the other was just a matter of maintaining the page’s state for the second page to retrieve. But it was a nuisance just slightly above the @Register directive on the annoyance scale.

ASP.NET 2.0 gives controls that cause a post-back to the server the ability to change the action of the form in the HTML page, causing the page’s state and data to be posted directly to an ASP.NET page other than the one that created it.

In the ASP.NET where you are declaring the server-side controls you set the PostBackUrl property to the aspx page you’d like the form to submit to.

In the second page you can retrieve the data the user inputted into the HTML form rendered by the first page by accessing the PreviousPage property and finding each control you’d like to get data from.


5) SQL Cache Dependency.
The ASP.NET 1.0 HttpCache class was a great feature for maintaining application-level state. One of the coolest features was the ability to create a dependency between an object you placed into the cache with another object, a file, or a directory.

Since frequently the object that you put into the cache related back to a table in your database, probably the question I got asked the most often when lecturing on ASP.NET was whether an object put into the cache could be invalidated when the underlying table changed. The answer in ASP.NET 1.0 was no. The new answer is yes.

To make this work, you first have to configure the SQL Server instance using the aspnet_regsql.exe command line tool. Then create an instance of the SqlCacheDependency class and add that into the Cache object when adding your data to the Cache.


6) Master Pages.
Using implementation inheritance was a cornerstone of the ASP.NET 1.0 model. Each .aspx page was compiled into a .NET class, and System.Web.UI.Page was that class’ eventual base class.

One oft-used technique in ASP.NET 1.0 was to create a “master page class”. This class derived from Page and generally had all the common functionality that each and every .aspx page in an application needed to use. It was trivial to get ASP.NET to use this class as the base class for all classes generated from your .aspx files.

Since ASP.NET is a framework to create user interfaces, the downside of this “master base class” model was that any server-side controls that were added dynamically via this class wouldn’t appear in the .aspx file designer in Visual Studio .NET.

In ASP.NET 2.0 there is a new feature called Master Pages. Master Pages are essentially ASP.NET syntax in a file with the .master extension. A Master Page can be created and serves the same purpose as the “master base class”. There are two main differences with the Master Page model.

One, the .master pages are visually designable. Not only that, when a .aspx page uses a Master Page, the visual elements from the Master Page are displayed in the design view of the .aspx page – grayed out.

Two, the Master Page isn’t used as the base class for the .aspx file.



One complaint that was heard around the world about ASP.NET 1.0 wasn’t really an ASP.NET problem, but a Visual Studio .NET (VS.NET) problem. Although ASP.NET supposed a number of different compilation and deployment models, VS.NET was fairly myopic in its view of how everyone should develop ASP.NET web applications. VS.NET’s model wasn’t wrong for every scenario, but it was wrong in enough instances to warrant a fairly bad rap when developing ASP.NET.

In ASP.NET 2.0, VS.NET (specifically VS.NET 2005) is much more flexible. It is flexible in terms of what part of an ASP.NET application may be open in the IDE at one time (no more solution files). VS.NET 2005 allows you to use a “codebehind” file or not, it is up to you, where VS.NET 2002/2003 both strictly enforced the “codebehind” file model.


8) Visual Studio .NET /ASP.NET compilation model.
In close connection with item number 4, VS.NET 2005 also frees the intrepid developer to compile at will. In fact, late compilation is the norm with 2005, which again is the opposite of the 2002/2003 model.

Part of this new lax view towards compilation goes hand in hand with new features built into ASP.NET 2.0. ASP.NET 2.0 takes advantage of the new feature built into C# and the CLR itself which allows a class to be defined in multiple files. Essentially, instead of “codebehind”, we now have “codebeside”, in which the class created from the .aspx file gets compiled into the same class that can exist in another file. This straightens out some of the weird object-oriented weirdness that sometimes ensued because of ASP.NET 1.0’s derived (.aspx ) base class (“codebehind”) model.

Also with ASP.NET 2.0 there is a command line compiler (aspnet_compile) that allows you to precompile a whole ASP.NET application. This feature is also exposed with a specialized handler which can be found at the precompile.axd endpoint in your application.


9) Provider model.
When the ASP.NET team looked at the code being written in the real world, they saw many chunks of code they felt they could build into the runtime itself. Many of these chunks need some data to back up the UI. Of course the ASP.NET team couldn’t choose a data source for every application, nor should they. So they used a layer of indirection.

This layer is known as a provider. A provider sits between the UI piece (the ASP.NET server-side control) and the data (which could be an ADO.NET data source, an XML file, or something else). The provider generally derives from a specific base class and that base class has methods that the UI piece can call to get the data necessary to render itself. ASP.NET 2.0 ships with providers for the most common types of data. If you have a different data source, you are free to build your own provider.

One standout example is membership. For membership, ASP.NET 2.0 ships a provider for Access and SQL Server, and a set of controls that allow logins, account creation, account editing, password reminders, etc. Building a gated web site with these new controls and a provider is really a snap. Expect to see more of this functionality unfold over time.


10) Declarative Databinding.
In ASP.NET 1.0, Databinding was one of the top features. Freeing developers from looping over rows of data and concatenating strings to generate HTML by allowing a control to just take a data object and run with it, with the rendered HTML being created based upon properties set on the control, was a genius idea. The only slight problem was that in order to make Databinding work, we still had to write code.

In ASP.NET 2.0, they introduce the concept of Declarative Databinding, which essentially allows you to declare the properties you want on your data source with the same declarative model you use to declare the server-side controls themselves. Datasource objects are created in the same way as server-side controls, by dragging and dropping them from the toolbox, or by adding the declaration to the .aspx file. Once configured, a datasource can be bound to a data-bound control.

Clearly, there are a lot more than just 10 new features in the ASP.NET 2.0 release; we could easily have turned this into a Top Twenty, Top Fifty or even Top One Hundred list, had we wanted. ASP.NET marks a huge new set of functionality, driven by customer demands and requests, and your Top Ten list will likely differ from my own, depending on your experience and history with ASP.NET. But in the meantime, while you're building your own list, try starting with these 10—I think you'll like these new features just as much as I do.

More links
http://quickstarts.asp.net/QuickStartv20/aspnet/doc/whatsnew.aspx
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Interview Question


classes MUST follow. It defines method signatures but cannot have any implementations; the latter must be provided by the classes that implement the interface.

C# differs from C++ in this regard because C++ lacks native language support for interfaces. As a C++ programmers you have to create an interface by defining an abstract class with pure virtual methods.

what is an abstract class.................

An Abstract class lets you define some behaviors and force your subclasses to provide others.
For example, if you have an application framework, an abstract class may provide default services such as event and message handling. Those services allow your application to plug in to your application framework. However, there is some application-specific functionality that only your application can perform. So instead of trying to define these behaviors, the abstract class can declare abstract methods.

Differences between Interfaces and Abstract classes Which we use ?

I. multiple inheritance

A class may implement several interfaces but can only extend one abstract class.

II. default implementation

An interface cannot provide any code at all, much less default code. An abstract class can provide complete code, default code, and/or just stubs that have to be overridden.

III. adding functionality

If you add a new method to an interface, you must track down all implementations of that interface in the universe and provide them with a concrete implementation of that method.
If you add a new method to an abstract class, you have the option of providing a default implementation of it. Then all existing code will continue to work without change.

IV. is-a vs -able or can-do

Interfaces are often used to describe the abilities of a class, not its central identity, e.g. an Automobile class might implement the Recyclable interface, which could apply to many otherwise totally unrelated objects.

An abstract class defines the core identity of its descendants.
************************************************************************
Abstract Class vs Interface
I am assuming you are having all the basic knowledge of abstract and interface keyword. I am just briefing the basics.
We can not make instance of Abstract Class as well as Interface.
Here are few differences in Abstract class and Interface as per the definition.
Abstract class can contain abstract methods, abstract property as well as other members (just like normal class).
Interface can only contain abstract methods, properties but we don’t need to put abstract and public keyword. All the methods and properties defined in Interface are by default public and abstract.

//Abstarct Class
public abstract class Vehicles
{
private int noOfWheel;
private string color;
public abstract string Engine
{
get;
set;
}
public abstract void Accelerator();
}
//Interface
public interface Vehicles
{
string Engine
{
get;
set;
}
void Accelerator();
}
We can see abstract class contains private members also we can put some methods with implementation also. But in case of interface only methods and properties allowed.
We use abstract class and Interface for the base class in our application
View state is used by the ASP.NET page framework to automatically save the values of the page and of each control just prior to rendering to the page. When the page is posted, one of the first tasks performed by page processing is to restore view state.
State management is the process by which you maintain state and page information over multiple requests for the same or different pages.
Client-side options are:
• The ViewState property
• Hidden fields
• Cookies
• Query strings
Server-side options are:
• Application state
• Session state
• Database

Use the View State property to save data in a hidden field on a page. Because ViewState stores data on the page, it is limited to items that can be serialized. If you want to store more complex items in View State, you must convert the items to and from a string.
ASP.NET provides the following ways to retain variables between requests:
• Context.Handler object Use this object to retrieve public members of one Web form’s class from a subsequently displayed Web form.
• Query strings Use these strings to pass information between requests and responses as part of the Web address. Query strings are visible to the user, so they should not contain secure information such as passwords.
• Cookies Use cookies to store small amounts of information on a client. Clients might refuse cookies, so your code has to anticipate that possibility.
• View state ASP.NET stores items added to a page’s ViewState property as hidden fields on the page.
• Session state Use Session state variables to store items that you want keep local to the current session (single user).
• Application state Use Application state variables to store items that you want be available to all users of the application.


Debug Class
Provides a set of methods and properties that help debug your code. This class cannot be inherited.
Namespace: System.Diagnostics
Assembly: System (in system.dll)
Syntax:
public sealed class Debug

If you use methods in the Debug class to print debugging information and check your logic with assertions, you can make your code more robust without impacting the performance and code size of your shipping product.
This class provides methods to display an Assert dialog box, and to emit an assertion that will always fail. This class provides write methods in the following variations: Write, WriteLine, WriteIf and WriteLineIf.
The BooleanSwitch and TraceSwitch classes provide means to dynamically control the tracing output. You can modify the values of these switches without recompiling your application. For information on using the configuration file to set a switch, see the Switch class and the Trace Switches topic.
You can customize the tracing output's target by adding TraceListener instances to or removing instances from the Listeners collection. By default, the DefaultTraceListener class emits trace output.
You can modify the level of indentation using the Indent method or the IndentLevel property. To modify the indent spacing, use the IndentSize property. You can specify whether to automatically flush the output buffer after each write by setting the AutoFlush property to true.
To set the AutoFlush and IndentSize for Debug, you can edit the configuration file corresponding to the name of your application. The configuration file should be formatted like the following example:





The ConditionalAttribute attribute is applied to the methods of Debug. Compilers that support ConditionalAttribute ignore calls to these methods unless "DEBUG" is defined as a conditional compilation symbol. Refer to a compiler's documentation to determine whether ConditionalAttribute is supported and the syntax for defining a conditional compilation symbol.
To define the "DEBUG" conditional compilation symbol in C# and J#, add the /d:DEBUG option to the compiler command line when you compile your code or add #define DEBUG to the top of your file. In Visual Basic, add the /d:DEBUG=True option to the compiler command line or add #Const DEBUG=True to the file.
ConditionalAttribute is not supported by the C++ compiler. To provide equivalent functionality, you must enclose calls to the methods of Debug in an #if defined(DEBUG) ... #endif block, and add the /DDEBUG option to the compiler command line or add #define DEBUG to the file.
In Visual Studio 2005 projects, by default, the "DEBUG" conditional compilation symbol is defined for debug builds, and the "TRACE" symbol is defined for both debug and release builds. For information on how to disable this behavior, see the Visual Studio 2005 documentation.

Example:

// Specify /d:DEBUG when compiling.

using System;
using System.Data;
using System.Diagnostics;

class Test
{
static void Main()
{
Debug.Listeners.Add(new TextWriterTraceListener(Console.Out));
Debug.AutoFlush = true;
Debug.Indent();
Debug.WriteLine("Entering Main");
Console.WriteLine("Hello World.");
Debug.WriteLine("Exiting Main");
Debug.Unindent();
}
}
Trace Class
Provides a set of methods and properties that help you trace the execution of your code. This class cannot be inherited.
Namespace: System.Diagnostics
Assembly: System (in system.dll)
Syntax:

public sealed class Trace

You can use the properties and methods in the Trace class to instrument release builds. Instrumentation allows you to monitor the health of your application running in real-life settings. Tracing helps you isolate problems and fix them without disturbing a running system.
This class provides methods to display an Assert dialog box, and to emit an assertion that will always Fail. This class provides write methods in the following variations: Write, WriteLine, WriteIf, and WriteLineIf.
The BooleanSwitch and TraceSwitch classes provide means to dynamically control the tracing output. You can modify the values of these switches without recompiling your application. For information on using the configuration file to set a switch, see the Switch class and the How to: Configure Trace Switches topic.
You can customize the tracing output's target by adding TraceListener instances to or removing instances from the Listeners collection. By default, trace output is emitted using the DefaultTraceListener class.
The Trace class provides properties to get or set the level of Indent, the IndentSize, and whether to AutoFlush after each write.
To set the AutoFlush and IndentSize for Trace, you can edit the configuration file that corresponds to the name of your application. The configuration file should be formatted like the following example:





The ConditionalAttribute attribute is applied to the methods of Trace. Compilers that support ConditionalAttribute ignore calls to these methods unless "TRACE" is defined as a conditional compilation symbol. Refer to a compiler's documentation to determine whether ConditionalAttribute is supported and the syntax for defining a conditional compilation symbol.
To define the "TRACE" conditional compilation symbol in C# and J#, add the /d:TRACE option to the compiler command line when you compile your code or add #define TRACE to the top of your file. In Visual Basic, add the /d:TRACE=True option to the compiler command line or add #Const TRACE=True to the file.
ConditionalAttribute is not supported by the C++ compiler. To provide equivalent functionality, you must enclose calls to the methods of Trace in an #if defined(TRACE) ... #endif block, and add the /DTRACE option to the compiler command line or add #define TRACE to the file.
In Visual Studio 2005 projects, by default, the "DEBUG" conditional compilation symbol is defined for debug builds, and the "TRACE" symbol is defined for both debug and release builds. For information on how to disable this behavior, see the Visual Studio 2005 documentation.
Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows CE Platform Note: The .NET Compact Framework does not support tracing features that use a configuration file.

Example:
// Specify /d:TRACE when compiling.
using System;
using System.Diagnostics;

class Test
{
static void Main()
{
Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
Trace.AutoFlush = true;
Trace.Indent();
Trace.WriteLine("Entering Main");
Console.WriteLine("Hello World.");
Trace.WriteLine("Exiting Main");
Trace.Unindent();
}
}



While excuting the page, it will go under the fallowing steps(or fires the events) which collectivly known as Page Life cycle.
Page_Init -- Page Initialization
LoadViewState -- View State Loading
LoadPostData -- Postback data processing
Page_Load -- Page Loading
RaisePostDataChangedEvent -- PostBack Change Notification
RaisePostBackEvent -- PostBack Event Handling
Page_PreRender -- Page Pre Rendering Phase
SaveViewState -- View State Saving
Page_Render -- Page Rendering
Page_UnLoad -- Page Unloading


What is new in .Net 2005 as compared to .Net 2003
some major changes we can find are
asp.net 2.o provides file system which will avoid dependency on IIS.
asp.net 2.0 provides partial classes
asp.net 2.0 provides Master pages which wil make easy to
provide common interface to entire application.
asp.net 2.0 provides webparts which allow to change user interface at runtime according user's choice


SingleTon Class?
STC is a class which can be instantiated only ones and all subsequent objects of the class refer to the first instance. In the STC default constructer is declared as private and for creating instance there'll be one static method.


what is the different in using arraylist and array
Array is a collection of Homogeneous items, while array list is a collections of objects(any object) 2 - Array is kind of static nature...this means you can not change dimension run time, not you can add/remove existing elements from it. while ArrayList is dynamic in behovior,...you can add/remove elements from that. You can say ArrayList has behaviour "Random access" from array and "Dynamic" from Liked List
What interface of a page class is implemented to enable view state of control?
StateBag class implements the view state and manages the information that ASP.NET pages and embedded controls persist across successive posts of the same page instance. The class works like a dictionary object and implements the IStateManager interface. The Page and the Control base classes expose the view state through the ViewState property

Which interface is implemented by the page class which handle the request when a request is transfered to a page?

IHttpHandler

What is serialization in .NET?
Serialization can be defined as the process of storing the state of an object to a storage medium. During this process, the public and private fields of the object and the name of the class, including the assembly containing the class, are converted to a stream of bytes, which is then written to a data stream. When the object is subsequently deserialized, an exact clone of the original object is created.

• Binary serialization preserves type fidelity, which is useful for preserving the state of an object between different invocations of an application. For example, you can share an object between different applications by serializing it to the clipboard. You can serialize an object to a stream, disk, memory, over the network, and so forth. Remoting uses serialization to pass objects “by value” from one computer or application domain to another.

• XML serialization serializes only public properties and fields and does not preserve type fidelity. This is useful when you want to provide or consume data without restricting the application that uses the data. Because XML is an open standard, it is an attractive choice for sharing data across the Web. SOAP is an open standard, which makes it an attractive choice.

What is reflection?
Reflection is the ability to find out the information abount an object at "RUN TIME". The namespace that u use for refelection is: System.Reflection
Reflection is the process of walking the metadata about a type and finding out things; for instance, how many constructors a type has, and what the parameters are. It also allows you to dynamically create and invoke types.

What is GAC ?

GAC(Global Assembly Cache) is a machine wide code cache that stores the assemblies. And these assemblies can be share by many applications on the computer. application deployed in GAC must have a strong name.

What is lock escalation?

Lock escalation is the process of converting a lot of low level locks (like row locks, page locks) into higher level locks (like table locks). Every lock is a memory structure too many locks would mean, more memory being occupied by locks. To prevent this from happening, SQL Server escalates the many fine-grain locks to fewer coarse-grain locks.

What is a trigger?
Triggers are basically used to implement business rules. Triggers is also similar to stored procedures. The difference is that it can be activated when data is added or edited or deleted from a table in a database.

What is Normalization?
Well a relational database is basically composed of tables that contain related data. So the Process of organizing this data into tables is actually referred to as normalization

Describe the main characteristics of static functions?
The main characteristics of static functions include,
1. It is without the a this pointer,
2. It can't directly access the non-static members of its class
3. It can't be declared const, volatile or virtual.
4. It doesn't need to be invoked through an object of its class, although for convenience, it may.

What is web garden?
The process model helps enable scalability on multiprocessor computers by distributing the work to several processes, one per CPU, each with processor affinity set to its CPU. This eliminates cross-processor lock contention and is ideal for large SMP systems. This technique is called Web gardening. The configuration settings for enabling Web gardens are listed in the following table. Note that these settings take effect only after a server is restarted. IIS must be cycled in order for this change to take place.
Setting Description :
webGarden Controls CPU affinity. True indicates that processes should be affinitized to the corresponding CPU. The default is False.
cpuMask Controls the number of processes and how the Web garden works. One process is launched for each CPU where the corresponding bit in the mask set to 1. When UseCPUAffinity is set to 0, the cpuMask setting only controls the number of worker processes (number of bits set to 1). The maximum-allowed number of worker processes is the number of CPUs. By default, all CPUs are enabled; the same number of worker processes is launched as there are CPUs. The default value is 0xffffffff.
Web gardening has some side effects that you should be aware of:
If your application uses session state, it must choose an out-of-process provider (NT Service or SQL).
Application state and application statics are per process, not per computer.
Caching is per process, not per computer

ACID Property of Transactions?
• Atomicity states that database modifications must follow an “all or nothing” rule. Each transaction is said to be “atomic.” If one part of the transaction fails, the entire transaction fails. It is critical that the database management system maintain the atomic nature of transactions in spite of any DBMS, operating system or hardware failure.
• Consistency states that only valid data will be written to the database. If, for some reason, a transaction is executed that violates the database’s consistency rules, the entire transaction will be rolled back and the database will be restored to a state consistent with those rules. On the other hand, if a transaction successfully executes, it will take the database from one state that is consistent with the rules to another state that is also consistent with the rules.
• Isolation requires that multiple transactions occurring at the same time not impact each other’s execution. For example, if Joe issues a transaction against a database at the same time that Mary issues a different transaction, both transactions should operate on the database in an isolated manner. The database should either perform Joe’s entire transaction before executing Mary’s or vice-versa. This prevents Joe’s transaction from reading intermediate data produced as a side effect of part of Mary’s transaction that will not eventually be committed to the database. Note that the isolation property does not ensure which transaction will execute first, merely that they will not interfere with each other.
• Durability ensures that any transaction committed to the database will not be lost. Durability is ensured through the use of database backups and transaction logs that facilitate the restoration of committed transactions in spite of any subsequent software or hardware failures.

Few more links to Brush up your brains

www.interviewcorner.com
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Resize popup to image size


This script is used to Resize the Popup as per the Image dimensions.
http://www.scriptsearch.com/cgi-bin/jump.cgi?ID=7049
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Asp.Net Page Life Cycle


  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

WEB PART


The Major Components of the ASP.NET 2.0 WebPart Framework
Before diving into a sample WebPart-driven Web site, you must first understand the major reusable controls built into the .NET framework, which you will use to set up the site:
WebPart: A WebPart is a reusable widget on a Web page. The user can choose to add a WebPart on his page, customize the WebPart per his needs, or even define communication between various WebParts. An ASP.NET 2.0 WebPart inherits from the System.Web.UI.WebControls.WebParts.WebPart class. A good example is a widget that displays traffic. End-user customization could involve specifying a freeway, and communication with another WebPart could involve a different WebPart that has a list of freeways that the user can click, one by one, to view updated traffic information. Setting up something like that is not very difficult in ASP.NET 2.0.

WebPartManager: This control is the central policeman of the ASP.NET 2.0 WebPart framework. Each page should contain only a single WebPartManager, which is responsible for managing all functionality, events, and customization of various WebParts on that page. WebPartManager also has the ability to set various modes. So, for instance, if the user sets the WebPartManager in a Catalog mode, he could pick and choose the WebParts he wants on his page from a catalog of WebParts. Alternatively, he could put the page in Communication mode and define the various connections between different WebParts.

Various Zones: Zones are physical areas on a page. These are implemented in the following Server Controls that ship with the Framework:

WebPartZone: A WebPartZone is a control that defines an area on a page where one or more WebParts can be hosted. A WebPartZone also controls the look and feel of a WebPart inside itself. Also, any control that doesn't inherit from the WebPart class can masquerade itself as a WebPart and live inside a WebPartZone. This is done with the help of the GenericWebPart class, which inherits from the WebPart base class. By doing so, you are restricted to a subset of the functionality that a WebPart class can expose.

CatalogZone: The CatalogZone is the menu or the catalog from which a user can choose. It holds a number of CatalogPart controls, which in turn hold WebParts that are already added to the site and ready for the picking to add to various pages on the site. The user can pick WebParts from the Catalog, and add them to the various WebPartZones on the same page.There are three types of CatalogParts: DeclarativeCatalogPart, PageCatalogPart, and ImportCatalogPart.

EditorZone: This is the area on the page that prompts the user to edit his WebPart and customize it to his specific needs. A WebPart can also be customized in a Shared mode, where an administrator can configure the WebPart and all other users can view or use the WebPart but not customize it.

ConnectionsZone: This is the area of the page that prompts the end user to define communication between various WebParts on the same page. For instance, you could build an online RSS reader. One WebPart holds the user's OPML, and the other WebPart renders the RSS for a particular subscription. The connection between the two would be the OPML WebPart providing a row (the RSS URL) and the RSS reader WebPart consuming the row, and then rendering appropriately. Because this is a simple ASP.NET 2.0 Web site, you can wrap these inside an atlas:UpdatePanel or a third-party control such as the telerik AJAX Panel. You even can eliminate postbacks and replace them with AJAX callbacks with almost no code at all.
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

MVC Architecture


The goal of the MVC design pattern is to separate the application object (model) from the way it is represented to the user (view) from the way in which the user controls it (controller).

The Model object knows about all the data that need to be displayed. It also knows about all the operations that can be applied to transform that object. However, it knows nothing whatever about the GUI, the manner in which the data are to be displayed, nor the GUI actions that are used to manipulate the data. The data are accessed and manipulated through methods that are independent of the GUI. The model represents enterprise data and the business rules that govern access to and updates of this data. Often the model serves as a software approximation to a real-world process, so simple
real-world modeling techniques apply when defining the model.

The View object refers to the model. It uses the query methods of the model to obtain data from the model and then displays the information. A view renders the contents of a model. It accesses enterprise data through the model and specifies how that data should be presented. It is the view's responsibility to maintain consistency in its presentation when the model changes.

The Controller object knows about the physical means by which users manipulate data within the model. A controller translates interactions with the view into actions to be performed by the model. In a stand-alone GUI client, user interactions could be button clicks or menu selections, whereas in a Web application, they appear as GET and POST HTTP requests. The actions performed by the model include activating business processes or changing the state of the model. Based on the user interactions and the outcome of the model actions, the controller responds by selecting an appropriate view.

In GUIs, views and controllers often work very closely together. For example, a controller is responsible for updating a particular parameter in the model that is then displayed by a view. In some cases a single object may function as both a controller and a view. Each controller-view pair is associated with only one model, however a particular model can have many view-controller pairs.

Advantages

The MVC architecture has the following benefits:

1) Multiple views using the same model: The separation of model and view allows multiple views to use the same enterprise model. Consequently, an enterprise application's model components are easier to implement, test, and maintain, since all access to the model goes through these components.

2) Easier support for new types of clients: To support a new type of client, you simply write a view and controller for it and wire them into the existing enterprise model.

3) Clarity of design: By glancing at the model's public method list, it should be easy to understand how to control the model's behavior. When designing the application, this trait makes the entire program easier to implement and maintain.

4) Efficient modularity: of the design allows any of the components to be swapped in and out as the user or programmer desires - even the model! Changes to one aspect of the program aren't coupled to other aspects, eliminating many nasty debugging situations. Also, development of the various components can progress in parallel, once the interface between the components is clearly defined.

5) Ease of growth: Controllers and views can grow as the model grows; and older versions of the views and controllers can still be used as long as a common interface is maintained.

6) Distributable: With a couple of proxies one can easily distribute any MVC application by only altering the startup method of the application
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

SQL Interview Questions


What is normalization? Explain different levels of normalization?

What is denormalization and when would you go for it?

As the name indicates, denormalization is the reverse process of normalization. It's the controlled introduction of redundancy in to the database design. It helps improve the query performance as the number of joins could be reduced.

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's the difference between a primary key and a unique key?

Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn't allow NULLs, but unique key allows one NULL only.

What are user defined datatypes and when you should go for them?

User defined datatypes let you extend the base SQL Server datatypes by providing a descriptive name, and format to the database. Take for example, in your database, there is a column called Flight_Num which appears in many tables. In all these tables it should be varchar(8). In this case you could create a user defined datatype called Flight_num_type of varchar(8) and use it across all your tables.

What is bit datatype and what's the information that can be stored inside a bit column?

Bit datatype is used to store boolean information like 1 or 0 (true or false). Untill SQL Server 6.5 bit datatype could hold either a 1 or 0 and there was no support for NULL. But from SQL Server 7.0 onwards, bit datatype can represent a third state, which is NULL.

Define candidate key, alternate key, composite key?

A candidate key is one that can identify each row of a table uniquely. Generally a candidate key becomes the primary key of the table. If the table has more than one candidate key, one of them will become the primary key, and the rest are called alternate keys.

A key formed by combining at least two or more columns is called composite key.

What are defaults? Is there a column to which a default can't be bound?

A default is a value that will be used by a column, if no value is supplied to that column while inserting data. IDENTITY columns and timestamp columns can't have defaults bound to them. See CREATE DEFUALT in books online.


SQL Server architecture

What is a transaction and what are ACID properties?

A transaction is a logical unit of work in which, all the steps must be performed or none. ACID stands for Atomicity, Consistency, Isolation, Durability. These are the properties of a transaction.

Explain different isolation levels

An isolation level determines the degree of isolation of data between concurrent transactions. The default SQL Server isolation level is Read Committed. Here are the other isolation levels (in the ascending order of isolation): Read Uncommitted, Read Committed, Repeatable Read, Serializable.

CREATE INDEX myIndex ON myTable(myColumn)
What type of Index will get created after executing the above statement?

Non-clustered index. Important thing to note: By default a clustered index gets created on the primary key, unless specified otherwise.

What's the maximum size of a row?

8060 bytes. Don't be surprised with questions like 'what is the maximum number of columns per table'. Check out SQL Server books online for the page titled: "Maximum Capacity Specifications".

Explain Active/Active and Active/Passive cluster configurations

Hopefully you have experience setting up cluster servers. But if you don't, at least be familiar with the way clustering works and the two clusterning configurations Active/Active and Active/Passive. SQL Server books online has enough information on this topic and there is a good white paper available on Microsoft site.

What is lock escalation?

Lock escalation is the process of converting a lot of low level locks (like row locks, page locks) into higher level locks (like table locks). Every lock is a memory structure too many locks would mean, more memory being occupied by locks. To prevent this from happening, SQL Server escalates the many fine-grain locks to fewer coarse-grain locks. Lock escalation threshold was definable in SQL Server 6.5, but from SQL Server 7.0 onwards it's dynamically managed by SQL Server.

What's the difference between DELETE TABLE and TRUNCATE TABLE commands?

DELETE TABLE is a logged operation, so the deletion of each row gets logged in the transaction log, which makes it slow. TRUNCATE TABLE also deletes all the rows in a table, but it won't log the deletion of each row, instead it logs the deallocation of the data pages of the table, which makes it faster. Of course, TRUNCATE TABLE can be rolled back.

Explain the storage models of OLAP

Check out MOLAP, ROLAP and HOLAP in SQL Server books online for more infomation.

What are constraints? Explain different types of constraints.

Constraints enable the RDBMS enforce the integrity of the database automatically, without needing you to create triggers, rule or defaults.

Types of constraints: NOT NULL, CHECK, UNIQUE, PRIMARY KEY, FOREIGN KEY


Whar is an index? What are the types of indexes? How many clustered indexes can be created on a table? I create a separate index on each column of a table. what are the advantages and disadvantages of this approach?

Indexes in SQL Server are similar to the indexes in books. They help SQL Server retrieve the data quicker.

Indexes are of two types. Clustered indexes and non-clustered indexes. When you craete a clustered index on a table, all the rows in the table are stored in the order of the clustered index key. So, there can be only one clustered index per table. Non-clustered indexes have their own storage separate from the table data storage. Non-clustered indexes are stored as B-tree structures (so do clustered indexes), with the leaf level nodes having the index key and it's row locater. The row located could be the RID or the Clustered index key, depending up on the absence or presence of clustered index on the table.

If you create an index on each column of a table, it improves the query performance, as the query optimizer can choose from all the existing indexes to come up with an efficient execution plan. At the same t ime, data modification operations (such as INSERT, UPDATE, DELETE) will become slow, as every time data changes in the table, all the indexes need to be updated. Another disadvantage is that, indexes need disk space, the more indexes you have, more disk space is used.


Database administration

What is RAID and what are different types of RAID configurations?

RAID stands for Redundant Array of Inexpensive Disks, used to provide fault tolerance to database servers. There are six RAID levels 0 through 5 offering different levels of performance, fault tolerance. MSDN has some information about RAID levels and for detailed information, check out the RAID advisory board's homepage

What are the steps you will take to improve performance of a poor performing query?

This is a very open ended question and there could be a lot of reasons behind the poor performance of a query. But some general issues that you could talk about would be: No indexes, table scans, missing or out of date statistics, blocking, excess recompilations of stored procedures, procedures and triggers without SET NOCOUNT ON, poorly written query with unnecessarily complicated joins, too much normalization, excess usage of cursors and temporary tables.

Some of the tools/ways that help you troubleshooting performance problems are: SET SHOWPLAN_ALL ON, SET SHOWPLAN_TEXT ON, SET STATISTICS IO ON, SQL Server Profiler, Windows NT /2000 Performance monitor, Graphical execution plan in Query Analyzer.

What are the steps you will take, if you are tasked with securing an SQL Server?

Again this is another open ended question. Here are some things you could talk about: Preferring NT authentication, using server, databse and application roles to control access to the data, securing the physical database files using NTFS permissions, using an unguessable SA password, restricting physical access to the SQL Server, renaming the Administrator account on the SQL Server computer, disabling the Guest account, enabling auditing, using multiprotocol encryption, setting up SSL, setting up firewalls, isolating SQL Server from the web server etc.


What is a deadlock and what is a live lock? How will you go about resolving deadlocks?

Deadlock is a situation when two processes, each having a lock on one piece of data, attempt to acquire a lock on the other's piece. Each process would wait indefinitely for the other to release the lock, unless one of the user processes is terminated. SQL Server detects deadlocks and terminates one user's process.

A livelock is one, where a request for an exclusive lock is repeatedly denied because a series of overlapping shared locks keeps interfering. SQL Server detects the situation after four denials and refuses further shared locks. A livelock also occurs when read transactions monopolize a table or page, forcing a write transaction to wait indefinitely.

What is blocking and how would you troubleshoot it?

Blocking happens when one connection from an application holds a lock and a second connection requires a conflicting lock type. This forces the second connection to wait, blocked on the first.

How to restart SQL Server in single user mode? How to start SQL Server in minimal configuration mode?

SQL Server can be started from command line, using the SQLSERVR.EXE. This EXE has some very important parameters with which a DBA should be familiar with. -m is used for starting SQL Server in single user mode and -f is used to start the SQL Server in minimal confuguration mode. Check out SQL Server books online for more parameters and their explanations.

As a part of your job, what are the DBCC commands that you commonly use for database maintenance?

DBCC CHECKDB, DBCC CHECKTABLE, DBCC CHECKCATALOG, DBCC CHECKALLOC, DBCC SHOWCONTIG, DBCC SHRINKDATABASE, DBCC SHRINKFILE etc. But there are a whole load of DBCC commands which are very useful for DBAs. Check out SQL Server books online for more information.

What are statistics, under what circumstances they go out of date, how do you update them?

Statistics determine the selectivity of the indexes. If an indexed column has unique values then the selectivity of that index is more, as opposed to an index with non-unique values. Query optimizer uses these indexes in determining whether to choose an index or not while executing a query.

Some situations under which you should update statistics:
1) If there is significant change in the key values in the index
2) If a large amount of data in an indexed column has been added, changed, or removed (that is, if the distribution of key values has changed), or the table has been truncated using the TRUNCATE TABLE statement and then repopulated
3) Database is upgraded from a previous version


What are the different ways of moving data/databases between servers and databases in SQL Server?

There are lots of options available, you have to choose your option depending upon your requirements. Some of the options you have are: BACKUP/RESTORE, dettaching and attaching databases, replication, DTS, BCP, logshipping, INSERT...SELECT, SELECT...INTO, creating INSERT scripts to generate data.

Explian different types of BACKUPs avaialabe in SQL Server? Given a particular scenario, how would you go about choosing a backup plan?

Types of backups you can create in SQL Sever 7.0+ are Full database backup, differential database backup, transaction log backup, filegroup backup. Check out the BACKUP and RESTORE commands in SQL Server books online. Be prepared to write the commands in your interview. Books online also has information on detailed backup/restore architecture and when one should go for a particular kind of backup.

What is database replicaion? What are the different types of replication you can set up in SQL Server?

Replication is the process of copying/moving data between databases on the same or different servers. SQL Server supports the following types of replication scenarios:

Snapshot replication
Transactional replication (with immediate updating subscribers, with queued updating subscribers)
Merge replication

How to determine the service pack currently installed on SQL Server?

The global variable @@Version stores the build number of the sqlservr.exe, which is used to determine the service pack installed. To know more about this process visit SQL Server service packs and versions.

Database programming

What are cursors? Explain different types of cursors. What are the disadvantages of cursors? How can you avoid cursors?

Cursors allow row-by-row prcessing of the resultsets.

Types of cursors: Static, Dynamic, Forward-only, Keyset-driven. See books online for more information.

Disadvantages of cursors: Each time you fetch a row from the cursor, it results in a network roundtrip, where as a normal SELECT query makes only one rowundtrip, however large the resultset is. Cursors are also costly because they require more resources and temporary storage (results in more IO operations). Furthere, there are restrictions on the SELECT statements that can be used with some types of cursors.

Most of the times, set based operations can be used instead of cursors. Here is an example:

If you have to give a flat hike to your employees using the following criteria:

Salary between 30000 and 40000 -- 5000 hike
Salary between 40000 and 55000 -- 7000 hike
Salary between 55000 and 65000 -- 9000 hike

In this situation many developers tend to use a cursor, determine each employee's salary and update his salary according to the above formula. But the same can be achieved by multiple update statements or can be combined in a single UPDATE statement as shown below:

UPDATE tbl_emp SET salary =
CASE WHEN salary BETWEEN 30000 AND 40000 THEN salary + 5000
WHEN salary BETWEEN 40000 AND 55000 THEN salary + 7000
WHEN salary BETWEEN 55000 AND 65000 THEN salary + 10000
END

Another situation in which developers tend to use cursors: You need to call a stored procedure when a column in a particular row meets certain condition. You don't have to use cursors for this. This can be achieved using WHILE loop, as long as there is a unique key to identify each row. For examples of using WHILE loop for row by row processing, check out the 'My code library' section of my site or search for WHILE.

Write down the general syntax for a SELECT statements covering all the options.

Here's the basic syntax: (Also checkout SELECT in books online for advanced syntax).

SELECT select_list
[INTO new_table_]
FROM table_source
[WHERE search_condition]
[GROUP BY group_by_expression]
[HAVING search_condition]
[ORDER BY order_expression [ASC | DESC] ]

What is a join and explain different types of joins.

Joins are used in queries to explain how different tables are related. Joins also let you select data from a table depending upon data from another table.

Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs. OUTER JOINs are further classified as LEFT OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS.

For more information see pages from books online titled: "Join Fundamentals" and "Using Joins".

Can you have a nested transaction?

Yes, very much. Check out BEGIN TRAN, COMMIT, ROLLBACK, SAVE TRAN and @@TRANCOUNT

What is an extended stored procedure? Can you instantiate a COM object by using T-SQL?

An extended stored procedure is a function within a DLL (written in a programming language like C, C++ using Open Data Services (ODS) API) that can be called from T-SQL, just the way we call normal stored procedures using the EXEC statement. See books online to learn how to create extended stored procedures and how to add them to SQL Server.

Yes, you can instantiate a COM (written in languages like VB, VC++) object from T-SQL by using sp_OACreate stored procedure. Also see books online for sp_OAMethod, sp_OAGetProperty, sp_OASetProperty, sp_OADestroy. For an example of creating a COM object in VB and calling it from T-SQL, see 'My code library' section of this site.

What is the system function to get the current user's user id?

USER_ID(). Also check out other system functions like USER_NAME(), SYSTEM_USER, SESSION_USER, CURRENT_USER, USER, SUSER_SID(), HOST_NAME().

What are triggers? How many triggers you can have on a table? How to invoke a trigger on demand?

Triggers are special kind of stored procedures that get executed automatically when an INSERT, UPDATE or DELETE operation takes place on a table.

In SQL Server 6.5 you could define only 3 triggers per table, one for INSERT, one for UPDATE and one for DELETE. From SQL Server 7.0 onwards, this restriction is gone, and you could create multiple triggers per each action. But in 7.0 there's no way to control the order in which the triggers fire. In SQL Server 2000 you could specify which trigger fires first or fires last using sp_settriggerorder

Triggers can't be invoked on demand. They get triggered only when an associated action (INSERT, UPDATE, DELETE) happens on the table on which they are defined.

Triggers are generally used to implement business rules, auditing. Triggers can also be used to extend the referential integrity checks, but wherever possible, use constraints for this purpose, instead of triggers, as constraints are much faster.

Till SQL Server 7.0, triggers fire only after the data modification operation happens. So in a way, they are called post triggers. But in SQL Server 2000 you could create pre triggers also. Search SQL Server 2000 books online for INSTEAD OF triggers.

There is a trigger defined for INSERT operations on a table, in an OLTP system. The trigger is written to instantiate a COM object and pass the newly insterted rows to it for some custom processing. What do you think of this implementation? Can this be implemented better?

Instantiating COM objects is a time consuming process and since you are doing it from within a trigger, it slows down the data insertion process. Same is the case with sending emails from triggers. This scenario can be better implemented by logging all the necessary data into a separate table, and have a job which periodically checks this table and does the needful.

What is a self join? Explain it with an example.

Self join is just like any other join, except that two instances of the same table will be joined in the query. Here is an example: Employees table which contains rows for normal employees as well as managers. So, to find out the managers of all the employees, you need a self join.

CREATE TABLE emp
(
empid int,
mgrid int,
empname char(10)
)

INSERT emp SELECT 1,2,'Vyas'
INSERT emp SELECT 2,3,'Mohan'
INSERT emp SELECT 3,NULL,'Shobha'
INSERT emp SELECT 4,2,'Shridhar'
INSERT emp SELECT 5,2,'Sourabh'

SELECT t1.empname [Employee], t2.empname [Manager]
FROM emp t1, emp t2
WHERE t1.mgrid = t2.empid

Here's an advanced query using a LEFT OUTER JOIN that even returns the employees without managers (super bosses)

SELECT t1.empname [Employee], COALESCE(t2.empname, 'No manager') [Manager]
FROM emp t1
LEFT OUTER JOIN
emp t2
ON
t1.mgrid = t2.empid

What command do we use to rename a db?

- sp_renamedb ‘oldname’ , ‘newname’

Well sometimes sp_reanmedb may not work you know because if some one is using the db it will not accept this command so what do you think you can do in such cases?

- In such cases we can first bring to db to single user using sp_dboptions and then we can rename that db and then we can rerun the sp_dboptions command to remove the single user mode.

What is the difference between a HAVING CLAUSE and a WHERE CLAUSE?

- Having Clause is basically used only with the GROUP BY function in a query. WHERE Clause is applied to each row before they are part of the GROUP BY function in a query.

What do you mean by COLLATION?

- Collation is basically the sort order. There are three types of sort order Dictionary case sensitive, Dictonary - case insensitive and Binary.

What action do you have to perform before retrieving data from the next result set of a stored procedure?

What are the advantages and disadvantages of View?

Advantages of views:
1. View the data without storing the data into the object.

2. Restict the view of a table i.e. can hide some of columns in the tables.

3. Join two or more tables and show it as one object to user.

4. Restict the access of a table so that nobody can insert the rows into the table.

Disadvatages:
1. Can not use DML operations on this.

2. When table is dropped view becomes inactive.. it depends on the table objects.

3. It is an object, so it occupies space.

Pls. add , if I miss any of them.


How many max No. of triggers I can create in a table?

Only 12 triggers are created in one table

how to delete set of records at a time where all the records having same values , except the Rowid differ

delete from table_name where rowid not in(select max(rowid) from table_name group by field_name)

How to find errors of PROCEDURE at run time( not complie time) ?

'Show error' will show the error of procedure at runtime.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Interview Questions


Q1. Describe the role of inetinfo.exe, aspnet_isapi.dll andaspnet_wp.exe in the page loading process.

Q2. What’s the difference between Response.Write() andResponse.Output.Write()?

Sol : Response.Output.Write() allows you to write formatted output.

Q3. What methods are fired during the page load?

Sol : Init() - when the page is instantiatedLoad() - when the page is loaded into server memoryPreRender() - the brief moment before the page is displayed to the user as HTMLUnload() - when page finishes loading.

Q4. When during the page processing cycle is ViewState available?

Sol : After the Init() and before the Page_Load(), or OnLoad() for a control

Q5. Where do you store the information about the user’s locale?

Sol :System.Web.UI.Page.Culture

Q6. True or False: To test a Web service you must create a Windows application or Web application to consume this service?

Sol : False, the web service comes with a test page and it provides HTTP-GET method to test.

Q7. What does the "EnableViewState" property do? Why would I want it on or off?

Sol :It allows the page to save the users input on a form across postbacks. It saves the server-side values for a given control into ViewState, which is stored as a hidden value on the page before sending the page to the clients browser. When the page is posted back to the server the server control is recreated with the state stored in viewstate.

Q8. Difference B/W Web Farm and Web Garden

Sol : Technical Diffference

In a Web Garden...

1. You have to run aspnet_state.exe utility
2. Configure the Web application's stateConnection and mode sessionState attribute in the Web.Config file.

In a Web Farm...
1. Install the installSQLState.SQL utility
2. Set the sessionState element's mode in the application's web.config file
3. set the sqlConnectionString attribute in the application's web.config file.

Q9. How many types of trgers are there in Sql server
Sol. There are two types of Trigers in Sql server -
1. After Triggers
2. Insteadof Triggers

Q10. What is Application Domain ? Explain

Q11.What is Index in Sql Server?

Q12. Difference B/W Clustered and Non-Clustrered Indexes?

Q13. What are the different types of Session state management options available with ASP.NET?

Sol. ASP.NET provides In-Process and Out-of-Process state management. In-Process stores the session in memory on the web server. This requires the a "sticky-server" (or no load-balancing) so that the user is always reconnected to the same web server. Out-of-Process Session state management stores data in an external data source. The external data source may be either a SQL Server or a State Server service. Out-of-Process state management requires that all objects stored in session are serializable.

Q14. How to call a Javascript function on Server side Button Click?

Q15.What do you understand by Bubbled Event?

Sol. When you have a complex control, like DataGrid, writing an event processing routine for each object (cell, button, row, etc.) is quite tedious. The controls can bubble up their eventhandlers, allowing the main DataGrid event handler to take care of its constituents.

Q16. What is Caching?

Q17. How many Security mechanism available in .Net ?

Q18. Describe Page Life cycle in .Net?

Q19. What is Serialization? Types Of Serialization?

Q20. What is Web service and how it is different from Remoting?

Q21. What is Viewstate ?How can I encrypt Viewstate of a page?


Q22. What are Value types and Reference types ?

Sol . Value types directly contain their data are either allocated on the stack or allocated in-line in a structure.

Reference types store a reference to the value's memory address, and are allocated on the heap.Reference types can be self-describing types, pointer types, or interface types.
Variables that are value types each have their own copy of the data, and therefore operations on
one variable do not affect other variables. Variables that are reference types can refer to the same object; therefore, operations on one variable can affect the same object referred to by another variable.All types derive from the System.Object base type.

Q23. What is Pooling in Sql Server?

Q24. How can I imlement Security in IIS?

Q25. What is Url Re-Writing?

Q26. What do you understand by the term "Sql-Injections" ?

Sol. SQL injection is a technique used to take advantage of non-validated input vulnerabilities to pass SQL commands through a Web application for execution by a backend database.

Q27. Give us a query for third highest salaried employee in an organisation?

Q28. Which one is better Inline queries Or Stored procedure? How ?

Q29. Can I use multiple runat server Forms in a given Asp.Net Page?

Q30. What is Boxing and Unboxing?

Sol. Boxing permits any value type to be implicitly converted to type object or to any interface type implemented by value type.Boxing is process in which a object instances created and copying value types value in to that instance.

UnBoxing is vice versa of boxing operation where the value is copied from the instance in to
appropriate storage location.

Below is sample code of boxing and unboxing where integer data type is converted in to object
and then vice versa.

Dim x As Integer
Dim y As Object
x = 10
‘ boxing process
y = x
‘ unboxing process
x = y

Q31. Which one is better Server.Transfer () or Response.Redirect() ?

Sol.
Response.Redirect: This tells the browser that the requested page can be found at a new location. The browser then initiates another request to the new page loading its contents in the browser. This results in two requests by the browser.

Server.Transfer: It transfers execution from the first page to the second page on the server. As far as the browser client is concerned, it made one request and the initial page is the one responding with content. The benefit of this approach is one less round trip to the server from the client browser. Also, any posted form variables and query string parameters are available to the second page as well.

Q32. How can I validate the HTML input in my web form?





Q33.What is an interface and what is an abstract class?

Sol. In an interface, all methods must be abstract (must not be defined). In an abstract class, some methods can be defined. In an interface, no accessibility modifiers are allowed, whereas it is allowed in abstract classes.

Q34. Session state vs. View state?

Sol. In some cases, using view state is not feasible. The alternative for view state is session state. Session state is employed under the following situations:

Large amounts of data - View state tends to increase the size of both the HTML page sent to the browser and the size of form posted back. Hence session state is used.

Secure data - Though the view state data is encoded and may be encrypted, it is better and secure if no sensitive data is sent to the client. Thus, session state is a more secure option.

Problems in serializing of objects into view state - View state is efficient for a small set of data. Other types like DataSet are slower and can generate a very large view state.

Q35.Can two different programming languages be mixed in a single ASPX file?

Sol. ASP.NET’s built-in parsers are used to remove code from ASPX files and create temporary files. Each parser understands only one language. Therefore mixing of languages in a single ASPX file is not possible.

Q36.Can the view state be encrypted?

Sol. The view state can be encrypted by setting EnableViewStateMac to true and either modifying the element in Machine.config to or by adding the above statement to Web.config.

Q37. Why do uploads fail while using an ASP.NET file upload control to upload large files?

Sol. ASP.NET limits the size of file uploads for security purposes. The default size is 4 MB. This can be changed by modifying the maxRequestLength attribute of Machine.configs element.

Q38. What’s a proxy of the server object in .NET Remoting?

Sol. It’s a fake copy of the server object that resides on the client side and behaves as if it was the server. It handles the communication between real server object and the client object. This process is also known as marshaling.


Q39. What are remotable objects in .NET Remoting?

Sol. Remotable objects are the objects that can be marshaled across the application domains. You can marshal by value, where a deep copy of the object is created and then passed to the receiver. You can also marshal by reference, where just a reference to an existing object is passed.


Q40.What are channels in .NET Remoting?

Sol. Channels represent the objects that transfer the other serialized objects from one application domain to another and from one computer to another, as well as one process to another on the same box. A channel must exist before an object can be transferred.

Q41 What security measures exist for .NET Remoting in System.Runtime.Remoting?

Sol. None. Security should be taken care of at the application level. Cryptography and other security techniques can be applied at application or server level.

Q42. What is a formatter?

Sol. A formatter is an object that is responsible for encoding and serializing data into messages on one end, and deserializing and decoding messages into data on the other end.

Q43. Choosing between HTTP and TCP for protocols and Binary and SOAP for formatters, what are the trade-offs?

Sol. Binary over TCP is the most effiecient, SOAP over HTTP is the most interoperable.

Q44. What’s SingleCall activation mode used for?

Sol. If the server object is instantiated for responding to just one single request, the request should be made in SingleCall mode.

Q45 What’s Singleton activation mode?

Sol. A single object is instantiated regardless of the number of clients accessing it. Lifetime of this object is determined by lifetime lease.

Q46. What is marshalling and what are different kinds of marshalling ?

Sol. Marshaling is used when an object is converted so that it can be sent across the network  or across application domains.Unmarshaling creates an object from the marshaled  data.There are two ways to do marshalling :-

v Marshal-by-value (MBV) :- In this the object is serialized into the channel, and  a copy of the object is created on the other side of the network. The object to  marshal is stored into a stream, and the stream is used to build a copy of the  object on the other side with the unmarshalling sequence.

v Marshaling-by-reference (MBR):- Here it creates a proxy on the client that is  used to communicate with the remote object. The marshaling sequence of a
remote object creates an ObjRef instance that itself can be serialized across the network.

Q47. What is a IL? Twist :- What is MSIL or CIL , What is JIT?

Sol. (IL)Intermediate Language is also known as MSIL (Microsoft Intermediate Language) or CIL(Common Intermediate Language). All .NET source code is compiled to IL. This IL is then converted to machine code at the point where the software is installed, or at run-time by a Just-In-Time (JIT) compiler.

Q48. What is a CLR?

Sol. Full form of CLR is Common Language Runtime and it forms the heart of the .NET framework.All Languages have runtime and its the responsibility of the runtime to take care of  the code execution of the program.For example VC++ has MSCRT40.DLL,VB6 has MSVBVM60.DLL , Java has Java Virtual Machine etc. Similarly .NET has CLR.Following are the responsibilities of CLR

v Garbage Collection :- CLR automatically manages memory thus eliminating memory leakes. When objects are not referred GC automatically releases those
memory thus providing efficient memory management.

v Code Access Security :- CAS grants rights to program depending on the security configuration of the machine.Example the program has rights to edit or create a new file but the security configuration of machine does not allow the program to delete a file.CAS will take care that the code runs under the environment of machines security configuration.

v Code Verification :- This ensures proper code execution and type safety while the code runs.It prevents the source code to perform illegal operation such as
accessing invalid memory locations etc.

v IL( Intermediate language )-to-native translators and optimizer’s :- CLR uses JIT and compiles the IL code to machine code and then executes. CLR also
determines depending on platform what is optimized way of running the IL code.

Q49. What is a CTS?

Sol. In order that two language communicate smoothly CLR has CTS (Common Type System).Example in VB you have “Integer” and in C++ you have “long” these datatypes are not compatible so the interfacing between them is very complicated. In order that two different languages can communicate

Q50. What is a CLS(Common Language Specification)?

Sol. This is a subset of the CTS which all .NET languages are expected to support.It was always a dream of microsoft to unite all different languages in to one umbrella and CLS is one step towards that.Microsoft has defined CLS which are nothing but guidelines that language to follow so that it can communicate with other .NET languages in a seamless manner.

Q51. What is a Managed Code?

Sol. Managed code runs inside the environment of CLR i.e. .NET runtime.In short all IL are managed code.But if you are using some third party software example VB6 or VC++ component they are unmanaged code as .NET runtime (CLR) does not have control over the source code execution of the language.

Q52. What is Difference between NameSpace and Assembly?

Sol. Following are the differences between namespace and assembly :

v Assembly is physical grouping of logical units. Namespace logically groups classes.
v Namespace can span multiple assembly.

Q53. What is Manifest?

Sol. Assembly metadata is stored in Manifest.Manifest contains all the metadata needed to do the following things( See Figure Manifest View for more details) :

v Version of assembly
v Security identity
v Scope of the assembly
v resolve references to resources and classes.
v The assembly manifest can be stored in either a PE file (an .exe or .dll) with Microsoft intermediate language (MSIL) code or in a stand-alone PE file that contains only assembly manifest information.

Q54. What is GAC ?Twist :- What are situations when you register .NET assembly in GAC ?

Sol. GAC (Global Assembly Cache) is used where shared .NET assembly reside.GAC is used in the following situations :-

v If the application has to be shared among several application.
v If the assembly has some special security requirements like only administrators can remove the assembly.If the assembly is private then a simple delete of assembly the assembly file will remove the assembly.

Note :- Registering .NET assembly in GAC can lead to the old problem of DLL hell.
Where COM version was stored in central registry.So GAC should be used when
absolutely necessary.

Q55. What is concept of strong names ? Twist :- How do we generate strong names or what is the process of generating strong names , What is use of SN.EXE , How do we apply strong names to assembly ? , How do you sign an assembly ?

Sol. Strong name is similar to GUID(It is supposed to be unique in space and time) in COM components.Strong Name is only needed when we need to deploy assembly in GAC.Strong Names helps GAC to differentiate between two versions.Strong names use public key cryptography (PKC) to ensure that no one can spoof it.PKC use public key and private key concept.

Q56. What is garbage collection?

Sol. Garbage collection is a CLR feature which automatically manages memory. Programmers forget to release the objects while coding ..... laziness ( Remember in VB6 where one of the good practices is to set object to nothing).CLR automatically releases objects when they are no longer
referenced and in use.CLR runs on non-deterministic to see the unused objects and cleans them. One side effect of this non-deterministic feature is that we cannot assume an object is destroyed when it goes out of the scope of a function. Therefore, we should not put code into a class destructor to release resources.

Q57. Can we force garbage collector to run ?

Sol. System.GC.Collect() forces garbage collector to run.This is not recommended but can be used if situations arises.

Q58. What is reflection?

Sol. All .NET assemblies have metadata information stored about the types defined in modules.This metadata information can be accessed by mechanism called as “Reflection”.System.Reflection can be used to browse through the metadata information. Using reflection you can also dynamically invoke methods using System.Type.Invokemember.Below is sample source code if needed you can also get this code from CD provided , go to “Source code” folder in “Reflection Sample” folder.

Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim Pobjtype As Type
Dim PobjObject As Object
Dim PobjButtons As New Windows.Forms.Button()
Pobjtype = PobjButtons.GetType()
For Each PobjObject In Pobjtype.GetMembers
LstDisplay.Items.Add(PobjObject.ToString())
Next
End Sub
End Class

Q59. What are different types of caching using cache object of ASP.NET?

Sol. You can use two types of output caching to cache information that is to be transmitted to
and displayed in a Web browser:

v Page Output Caching
Page output caching adds the response of page to cache object.Later when page is requested page is displayed from cache rather than creating the
page object and displaying it.Page output caching is good if the site is fairly static.

v Page Fragment Caching If parts of the page are changing, you can wrap the static sections as user
controls and cache the user controls using pagefragment caching.

Q60. How can you cache different version of same page using ASP.NET cache object ?

Sol. Output cache functionality is achieved by using “OutputCache” attribute on ASP.NET page header.Below is the syntax


v VaryByParam :- Caches different version depending on input parameters send through HTTP POST/GET.

v VaryByHeader:- Caches different version depending on the contents of the page header.

v VaryByCustom:-Lets you customize the way the cache handles page variations by declaring the attribute and overriding the GetVaryByCustomString handler.

v VaryByControl:-Caches different versions of a user control based on the value of properties of ASP objects in the control.

Q61. How will implement Page Fragment Caching ?

Sol. Page fragment caching involves the caching of a fragment of the page, rather than the entire page. When portions of the page need to be dynamically created for each user request this is best method as compared to page caching.You can wrap Web Forms user control and cache the control so that these portions of the page don’t need to be recreated each time.

Q62. Is Session_End event supported in all session modes ?

Sol . Session_End event occurs only in “Inproc mode”.”State Server” and “SQL SERVER” do not have Session_End event.
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

What is .NET Framework and what are CLR, CTS and CLS?


. NET is a software platform. It's a language-neutral environment for developing .NET applications that can easily and securely operate within it.

The .NET Framework has two main components: the Common Language Runtime (CLR) and the .NET Framework class library.

The Runtime can be considered an agent that manages code at execution time. Thus providing core services such as memory management, thread management, and remoting. Also incorporating strict type safety, security and robustness.

The class library is a comprehensive collection of reusable types that you can use to develop traditional command-line, WinForm (graphical user interface) applications, Web Forms and XML Web services.

The .NET Framework provides a Runtime environment called the Common Language Runtime or (CLR) that handles the execution of the code and provides useful services for the implementation of the application. CLR takes care of code management upon program execution and provides various services such as memory management, thread management, security management and other system services. The managed code targets CLR benefits by using useful features such as cross-language integration, cross-language exception handling, versioning, enhanced security, deployment support, and debugging.

Common Type System (CTS) describes how types are declared, used and managed. CTS facilitates cross-language integration, type safety, and high performance code execution. The CLS is a specification that defines the rules to support language integration. This is done in such a way, that programs written in any language (.NET compliant) can interoperate with one another. This also can take full advantage of inheritance, polymorphism, exceptions, and other features.
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

HOW TO: Configure SQL Server Security for .NET Applications


This article describes how to configure the SQL Server for .NET applications. By default, the SQL Server denies access to user accounts that have not explicitly been granted access to a database, a table, or a view. By default, ASP.NET applications run in the context of the ASPNET user account. Unless you permit access to the ASPNET user account, an ASP.NET application cannot read and cannot update data in an SQL Server database. This article describes the process that you can use to permit an ASP.NET application to have permissions to an SQL Server 2000 database.Note You must give the ASPNET user account only minimal permissions to run. This limits the potential damage that may result to an ASP.NET application that is compromised by a malicious attacker.

Configure the SQL ServerTo permit an ASP.NET application that executes in the context of the ASPNET account to access an SQL Server database, follow these steps:
On the taskbar, click start.

Point to Programs and then point to Microsoft SQL Server.

Double-click Enterprise Manager.

Expand Microsoft SQL Servers and then expand the SQL Server group that contains your server.

Expand your server branch and then expand Security.

Right-click Logins and then select New Login to open the SQL Server Login Properties-New Login dialog box.

Click the General tab. In the name field, enter the name of the ASP.NET user. By default, this is a local account with the name ASPNET.


Click the Database Access tab.


Under Specify Which Databases Can Be Accessed By This Login, select the databases that are used by the ASP.NET application.You generally do not have to permit access to the Model database, the Master database, the Msdb database, or the Tempdb database.


For each database that the account requires access to, verify that the Public role in the Permit In Database Role list is selected.


Click OK to return to Enterprise Manager.


Expand the Databases branch, and then expand the branch for the database that your ASP.NET application requires access to. Click to select Users.


In the right pane, right-click the ASPNET user account and then click Properties. The Database User Properties dialog box appears.


Click Permissions. A new dialog box appears. This dialog box shows the permissions for the ASPNET user account for all objects in the database. Scroll through the list and then select the check boxes that are associated with the tables and the views that the application requires access to. For tables and views that the application must read, but not write to, select only the SELECT column. For tables and views that must be updated, select the SELECT, the UPDATE, the INSERT, and the DELETE check boxes as appropriate.


After you grant all the required permissions, click OK two times to return to Enterprise Manager.


Close Enterprise Manager.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

SQL Injection


SQL injection is a technique used to take advantage of non-validated
input vulnerabilities to pass SQL commands through a Web application for execution
by a backend database. Attackers take advantage of the fact that programmers often
chain together SQL commands with user-provided parameters, and can therefore embed
SQL commands inside these parameters. The result is that the attacker can execute
arbitrary SQL queries and/or commands on the backend database server through the
Web application.



Detailed description



Databases are fundamental components of Web applications. Databases enable Web applications
to store data, preferences and content elements. Using SQL, Web applications interact
with databases to dynamically build customized data views for each user. A common
example is a Web application that manages products. In one of the Web application's
dynamic pages (such as ASP), users are able to enter a product identifier and view
the product name and description. The request sent to the database to retrieve the
product's name and description is implemented by the following SQL statement.



SELECT ProductName, ProductDescription FROM Products WHERE ProductNumber = ProductNumber



Typically, Web applications use string queries, where the string contains both the
query itself and its parameters. The string is built using server-side script languages
such as ASP, JSP and CGI, and is then sent to the database server as a single SQL
statement. The following example demonstrates an ASP code that generates a SQL query.



sql_query= "SELECT ProductName, ProductDescription FROM Products WHERE ProductNumber
" & Request.QueryString("ProductID")



The call Request.QueryString("ProductID") extracts the value of the Web form variable
ProductID so that it can be appended as the SELECT condition.

When a user enters the following URL:



http://www.mydomain.com/products/products.asp?productid=123



The corresponding SQL query is executed:

SELECT ProductName, ProductDescription FROM Products WHERE ProductNumber = 123

An attacker may abuse the fact that the ProductID parameter is passed to the database
without sufficient validation. The attacker can manipulate the parameter's value
to build malicious SQL statements. For example, setting the value "123 OR 1=1" to
the ProductID variable results in the following URL:



http://www.mydomain.com/products/products.asp?productid=123 or 1=1



The corresponding SQL Statement is:

SELECT ProductName, Product Description From Products WHERE ProductNumber = 123
OR 1=1



This condition would always be true and all ProductName and ProductDescription pairs
are returned. The attacker can manipulate the application even further by inserting
malicious commands. For example, an attacker can request the following URL:



http://www.mydomain.com/products/products.asp?productid=123;DROP TABLE Products



In this example the semicolon is used to pass the database server multiple statements
in a single execution. The second statement is "DROP TABLE Products" which causes
SQL Server to delete the entire Products table.



An attacker may use SQL injection to retrieve data from other tables as well. This
can be done using the SQL UNION SELECT statement. The UNION SELECT statement allows
the chaining of two separate SQL SELECT queries that have nothing in common. For
example, consider the following SQL query:



SELECT ProductName, ProductDescription FROM Products WHERE ProductID = '123' UNION
SELECT Username, Password FROM Users;



The result of this query is a table with two columns, containing the results of
the first and second queries, respectively. An attacker may use this type of SQL
injection by requesting the following URL:


http://www.mydomain.com/products/products.asp?productid=123 UNION SELECT user-name, password FROM USERS

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Url Rewriting


<div class="post-body">
<p>
</p>
<div style="CLEAR: both">
</div>
<span style="color:#ff0000;"><strong>First Sample </strong>


</span>


string StrFilePath = Request.FilePath;

int intStart = StrFilePath.LastIndexOf("/") + 1 ;

int intEnd = StrFilePath.LastIndexOf(".aspx");

int intLength = intEnd - intStart; //CHECK THE URL STRING FOR USER SUB DIRECTORY

if(intEnd&gt;0 &amp;& intStart&gt;0)

{

StrFilePath = StrFilePath.Substring(intStart,intLength);//TRANSFER THE VISITOR TO
THE COMMON PAGE10:

string strselect ="select fieldname from tablemaster where fieldname='"+StrFilePath.Replace("'","''")+"'";

SqlDataReader Oreader=null;

Oreader=res.getReader(strselect);

if(Oreader.Read())

{

 

if(StrFilePath.IndexOf("StrFilePath")&lt;0) { Context.RewritePath("Listing.aspx?Id="+Oreader["ID"].ToString()+"");
} } Oreader.Close();

 

 

<span style="color:#ff0000;"></span><strong><span style="color:#ff0000;">Second Sample</span>
</strong>

 


string OriginalPath = HttpContext.Current.Request.Path;

Regex r = new Regex(@"(\d+)");

Match m = r.Match(OriginalPath);

try

{

int id = Convert.ToInt32(m.ToString());

HttpContext.Current.RewritePath("MyPage.aspx?id="+id);

}

catch {}

 

 

<span style="color:#ff0000;"><strong>Handling PostBack</strong>

</span>


RegisterStartupScript( "PostBackFix",

"&lt;script&gt; document.forms[0].action=''; &lt;/script&gt;

 

" );</div>

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Partial Classes in ASP.NET


Partial class is a new functionality that is included in Visual Studio .Net 2005 and is supported in ASP.Net 2.0. This new functionality helps you to split a single class into multiple partial classes. These partial classes can be in different individual files.

In the earlier versions of Visual Studio .Net 2005, while you create an ASP.Net application, you might have seen that a single class has to be in a single file. You will be beginning a class and ending that class in the same file. It was not possible to split a single class across multiple files. This new feature, partial class, allows you to allot different developers to develop the code for different functionalities that are available in a single class. These functionalities can be developed in partial classes and then compiled to form the required assembly.

In the previous versions of the Visual Studio .Net IDE, when you create a new ASP.Net webform, the name of the web form is used as a class in the code-behind file. Apart from that, you would have seen lots of code generated by Visual Studio .Net itself. In the latest version of the Visual Studio .Net IDE, the codes that are generated by Visual Studio .Net are in a separate file as a partial class. Hence a user who creates a new webform would see a partial class for that page, when the user uses the code-behind file. This way the code that is seen in the code-behind file is minimal for a particular webform.

The compilers for VB.Net or C# look for the partial classes and integrate them while compiling, to form the intermediate language. This intermediate language is the same when compared to the intermediate language that is generated, if all the partial classes are combined to form a single class in a single file. There is no modification done in the CLR for the implementation of partial classes.

The CLR finds no difference in the intermediate language, even if the IL is produced by having a single class in a single class file, where all the methods of the interface are implemented in a single class in a single class file. Since we are dealing with different files for a single class, even if you missed out implementing one method of an interface, the intellisense of Visual Studio .Net 2005 will point it out to you, thus enabling you to implement the missed out method of the interface. This is one among the advantage of using a Visual Studio .Net 2005 IDE for ASP.Net 2.0 applications.

This type of splitting the class file is particularly useful if a single class runs to thousands of lines of code with different functionalities across different methods. Productivity of the project team is increased since a single class file is split across the team members and implemented as partial classes.
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Access to the path containing 'hash.web' is getting denied.


After installing Visual Studio .NET and F5 a couple of times, I used to get this error frequently. The only resolution was to wait for upto 5 to10 mins or restart system, since a folder in Temporary ASP.NET files containing web.config gets locked up automatically.

After searching a while in KBs, Forums, I found one closest matching solution, which solved my problem. Just wanted to share with other readers who would also be experiencing this issue. The problem occurs significantly if you touch web.config and ASP.NET has significant memory consumption (as seen in Windows Task Manager)

There is a service called Indexing Service which runs in the system. During F5, ASP.NET tries to JIT compile the new dll (as my understanding goes) and when simultaneously ASP.NET and Indexing service goes to the specified set of cache files, the deadlock occurs and ASP.NET throws this exception.

Solutions:

1. Keep Indexing Service Manual or Stop It
2. In Indexing Service Preferences, Make C:/Winnt/Microsoft.NET to be excluded or placed in the exclusion catalog so that Indexing Service will not access this location.
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

What is the difference between const and static read-only


A const must be initialized at the time of its creation. A readonly field can be assigned to once in the class constructor allowing you to pass in the value at run-time. Declaring fields as const protects both you and other programmers from accidentally changing the value of the field. Also note that with const fields, the compiler performs some optimization by not declaring any stack space for the field. The readonly keyword is similar to const, with two exceptions. First, the storage of a readonly field is the same as a regular read-write field, and thus there is no performance benefit. Secondly, readonly fields can be initialized in the constructor of the containing class.
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Asp.Net Caching Basics


At a minimum a developer wants to be able to cache some (or possibly all) of the pages in her ASP.NET Application. The simplest way to achieve this is to add the @ OutputCache directive to the top of the .aspx file of each page:

OutputCache Duration="5" VaryByParam="none" %>


Now, that was easy, wasn't it? But - exactly what does it do? You are specifying how long the page is to be retained in the Cache with the Duration attribute, in
seconds. In the above example, this page will be rendered on the first request for it, and stored in Cache. For five seconds, all subsequent requests for this page
will be served from the Cache, which is hugely faster than having to go through the entire Page lifecycle, possibly combined with database access, re-render and finally serve the page HTML to the client. After five seconds, the page will again be rendered (and once again, stored in the Cache).

Do you want to perform a simple test that will convince you to become a "Cache Convert"? Fire up Application Center Test or Homer (Web Stress Tool) and throw 100 simultaneous threads at a sample page that gets a DataSet out of your favorite database and populates a DataGrid with a DataTable from it. Run this test for one minute, and note the total number of successful requests for the duration of the test. Now, modify the page by putting the above OutputCache irective at the top of the .aspx file. Then run the test again, and compare. It is as objective as gravity -- caching creates a huge scalability advantage.

The VaryByParam attribute is used to define parameters that determine which cached copy of a page should be sent to the browser. If your page doesn't change, you can set this to "none".

Caching Pages Based on QueryString items If the contents of one of your pages can vary based on the value of certain items on the querystring, which is a common technique in ASP.NET, you can populate the VaryByParam attribute with a semicolon-delimited list of the QueryString parameter names that control these changes. For each request, ASP.NET checks the value(s) of these items on the incoming QueryString, and if the parameter values match those
of a previously cached copy of the result page, it is served from the Cache. If the parameter(s) don't match, the custom page will be rendered, added to the Cache with the specified expiration time, and served to the client.

So, for example, if you have userid and companyid QueryString parameters, your VaryByParam attribute might look like this:
OutputCache Duration="5" VaryByParam="userid;companyid"

This technique works automatically with both QueryString ("GET") parameters as well as Form Field ("POST") data. You can also set the VaryByParam attribute to "*" to make ASP.NET cache a copy of every possible combination of querystring parameters. However, this can cause caching of a lot more pages that you want and can also cause performance problems. You should also be careful about defining a reasonable expiration time on your cached pages. If you set the Duration attribute to large values and a large number of unique page requests come in during this period, you could rack up a lot of server resources which would actually negatively affect performance or even cause process recycling based on IIS settings.

Caching pages based on Browser Information
If you need to render a page differently for different browsers, or you know that ASP.NET will automatically adjust the rendering of a page automatically based on the browser type and version of a request, you can use the "VaryByCustom" attribute:


At a minimum a developer wants to be able to cache some (or possibly all) of the pages in her ASP.NET Application. The simplest way to achieve this is to add the @ OutputCache directive to the top of the .aspx file of each page:

Now, that was easy, wasn't it? But - exactly what does it do? You are specifying how long the page is to be retained in the Cache with the Duration attribute, in
seconds. In the above example, this page will be rendered on the first request for it, and stored in Cache. For five seconds, all subsequent requests for this page
will be served from the Cache, which is hugely faster than having to go through the entire Page lifecycle, possibly combined with database access, re-render and finally serve the page HTML to the client. After five seconds, the page will again be rendered (and once again, stored in the Cache).

Do you want to perform a simple test that will convince you to become a "Cache Convert"? Fire up Application Center Test or Homer (Web Stress Tool) and throw 100 simultaneous threads at a sample page that gets a DataSet out of your favorite database and populates a DataGrid with a DataTable from it. Run this test for one minute, and note the total number of successful requests for the duration of the test. Now, modify the page by putting the above OutputCache directive at the top of the .aspx file. Then run the test again, and compare. It is as objective as gravity -- caching creates a huge scalability advantage.

The VaryByParam attribute is used to define parameters that determine which cached copy of a page should be sent to the browser. If your page doesn't change, you can set this to "none".

Caching Pages Based on QueryString items

If the contents of one of your pages can vary based on the value of certain items on the querystring, which is a common technique in ASP.NET, you can populate the VaryByParam attribute with a semicolon-delimited list of the QueryString parameter names that control these changes. For each request, ASP.NET checks the value(s) of these items on the incoming QueryString, and if the parameter values match those of a previously cached copy of the result page, it is served from the Cache. If the parameter(s) don't match, the custom page will be rendered, added to the Cache with the specified expiration time, and served to the client.

So, for example, if you have userid and companyid QueryString parameters, your VaryByParam attribute might look like this:

OutputCache Duration="5" VaryByParam="userid;companyid"%>

This technique works automatically with both QueryString ("GET") parameters as well as Form Field ("POST") data. You can also set the VaryByParam attribute to "*" to make ASP.NET cache a copy of every possible combination of querystring parameters. However, this can cause caching of a lot more pages that you want and can also cause performance problems. You should also be careful about defining a reasonable expiration time on your cached pages. If you set the Duration attribute to large values and a large number of unique page requests come in during this period, you could rack up a lot of server resources which would actually negatively affect performance or even cause process recycling based on IIS settings.

Caching pages based on Browser Information

If you need to render a page differently for different browsers, or you know that ASP.NET will automatically adjust the rendering of a page automatically based on the browser type and version of a request, you can use the "VaryByCustom" attribute:

OutputCache Duration="5" VaryByParam="none" VaryByCustom="browser"%>

Cache pages Based on Custom Strings
For situations where you want to cache pages where ASP.NET does not provide built-in support for caching, you can set the VaryByCustom attribute value to the name of a custom string of your own, and then override the GetVaryByCustomString method in global.asax and provide code that creates a unique custom string for the value that you assigned to the VaryByCustom attribute in your OutputCache directive.

Example code (global.asax):

public override string GetVaryByCustomString(System.Web.HttpContext context, string custom)

{

string value=null;

if(custom.Equals("urlReferrer")

{

value= context.Request.UrlReferrer; // cache based on where the request came from!

}

}

Additional Caching Features
Applications that want more control over the HTTP headers related to caching can use the functionality provided by the System.Web.HttpCachePolicy class. The following example shows the code equivalent to the page directives used in the previous samples.

Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));

Response.Cache.SetCacheability(HttpCacheability.Public);
To make this a sliding expiration policy, where the expiration time out resets each time the page is requested, set the SlidingExpiration property as shown in the following code.

Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));

Response.Cache.SetCacheability(HttpCacheability.Public);

Response.Cache.SetSlidingExpiration(true);

When sliding expiration is enabled (SetSlidingExpiration(true)), a request made to the origin server always generates a response. Sliding expiration is useful in
scenarios where there are downstream caches that can satisfy client requests, if the content has not expired yet, without requesting the content from the origin
server. Applications being ported from ASP may already be setting cache policy using the ASP properties; for example:


Response.CacheControl = "Public";

Response.Expires = 60;

Caching with Database Dependencies
In ASP.NET 1.1, caching based on database dependencies is not built in. You can still do it, but it requires wiring up some code. For details on how to do this,
here are links to a few articles that use several different techniques:
ASP.NET SqlCacheDependency with SQLte
ASP.NET SqlCacheDependency Redux
ASP.NET Database Cache Dependency


In ASP.NET 2.0 we have the ability to to cache pages with data dependencies based on SQL Server 7.0, 2000, 2005, MSDE, and SQL Express editions. The capabilites vary by application and version. In all cases, whether with ASP.NET 1.1 or ASP.NET 2.0, the key to database cache dependency is being able to know when data in the database changes.

For SQL Server 2005 and Express, these notifications can be enabled by simply adding the element to the web.config, which we'll cover shortly.

For SQL Server 7, 2000 and MSDE, notification events aren't supported, but what we can do is use polling by enabling the database with the command:

aspnet_regsql -S [SERVER] -E -d [database] -ed
To enable a specific table for notifications, we use:
aspnet_regsql -S [SERVER] -E -d [database] -et -t [table]
To see all the options for the ASPNET_REGSQL.EXE utility, use the -? argument.

The other way you can enable your database for dependency notifications is to use the methods in the SqlCacheDependencyAdmin class:

SqlCacheDependencyAdmin.EnableNotifications(connectionString);

If you want to see everything that the above do, simply perform the operation on a new database with one table in it, and view the results in Enterprise Manager.
The public methods of interest in the SqlCacheDependencyAdmin class are: DisableNotifications : Disables SqlCacheDependency change notifications
for the specified database.
DisableTableForNotifications: Overloaded. Disables SqlCacheDependency change notifications on a SQL Server database table or an array of database tables.
EnableNotifications: Enables SqlCacheDependency change notifications on the specified database.
EnableTableForNotifications: Overloaded. Connects to a SQL Server database and prepares a database table or tables for SqlCacheDependency change notifications.
GetTablesEnabledForNotifications: Retrieves a string array containing the name of every table that is enabled for change notifications in a SQL Server
database.

After your database is configured, you need to add the element:
<caching>

<sqlcachedependency enabled="true" polltime="30000">

<databases>

<add name="Pubs" connectionstringname="PubsConn">

</databases>

</sqlcachedependency>

</caching>


The "pollTime" attribute determines the rate at which the AspNet_SqlCacheTablesForChangeNotification table is queried to see if any table data has changed. Units are in milliseconds. The connectionStringName needs to be set to a connectionString in the <connectionstrings> node of the web.config.

Once the web.config is properly set up, you can cache pages using the SqlCacheDependency feature by adding this into the @ outputCache directive in the page:
<@ outputCache Duration="86400" VaryByParam="none" SqlDependency = "databasename:tablename" >

You can specify multiple databases and tables by providing a semicolon-delimited list of database:table pairs.

Caching specific Controls in a Page

You can apply the @ outputCache directive to individual user controls but not to the page itself. At the top of each .ascx user Control page, place an outputCache directive exactly as you would with a Page. Now if you have usercontrols whose data does not change frequently or with each page request, but the data on your page does need to be generated "fresh" on each request, you can have the best of both worlds. You can even specify the VaryByControl attribute to name specific controls on your UserControl that respond to properties such as "headerImage", or "backgroundColor".

Caching Application Data

Besides the advantages of caching pages, controls and using SqlCacheDependency, you can also directly interact with the Cache class by caching frequently used data. A typical pattern that I use looks like this:
public partial class _Default : System.Web.UI.Page



{



protected void Page_Load(object sender, EventArgs e)



{



DataTable dt =GetArticlesDt();



this.Repeater1.DataSource = dt;



Repeater1.DataBind();



}



private DataTable GetArticlesDt()



{



DataTable dt = null;



if (Cache["articlesDt"] == null)



{



DataSet ds = new DataSet();



string connectionString = System.Configuration.ConfigurationManager.AppSettings["connectionString"];



SqlCommand cmd = new SqlCommand("dbo.GetArticles");



cmd.CommandType = CommandType.StoredProcedure;



SqlConnection cn = new SqlConnection(connectionString);



cmd.Connection = cn;



SqlDataAdapter ad = new SqlDataAdapter(cmd);



ad.Fill(ds);



dt = ds.Tables[0];



Cache.Insert("articlesDt", dt, null, System.Web.Caching.Cache.NoAbsoluteExpiration,



TimeSpan.FromMinutes(30));



}



else



{



dt = (DataTable)Cache["articlesDt"];



}



return dt;



}





You see I have a method "GetArticlesDt" that automatically checks the Cache and ensures that we always can get our DataTable out of Cache in order to avoid repetitive Database calls. Then I just set the DataSource on the Repeater and DataBind.

In addition, you can cache application data based on database dependencies, if you have configured your database as above:



sqlDepcy = new SqlCacheDependency("ArticlesDB","tblArticles");

Context.Cache.Insert("articlesDt",ds.Tables[0],sqlDepcy);


Caching Data Sources


In ASP.NET 2.0, the XmlDataSource, ObjectDataSource and SqlDataSource controls all support caching "out of the box":
whateverDataSource.EnableCaching =true;

whateverDataSource.CacheDuration=5;




I hope this short discussion on Caching has sparked your interest and provided a convenient way to summarize these concepts for further study. I use Caching on almost all my work; at Tech-Ed 2004 Rob Howard gave a presentation on caching that totally blew me away and the lesson was learned very well. Caching data, pages or controls for as little as one second can have a dramatic effect on throughput of as much as 500 percent. This may not seem particularly important if you are just starting out, but I can tell you from personal experience that when you manage a successful web site with millions of hits per month, a thorough understanding of the uses and applications of Caching will serve you very well in your career as a professional .NET developer.

Cache pages Based on Custom Strings

For situations where you want to cache pages where ASP.NET does not provide built-in support for caching, you can set the VaryByCustom attribute
value to the name of a custom string of your own, and then override the GetVaryByCustomString method in global.asax and provide code that creates a unique custom string for the value that you assigned to the VaryByCustom attribute in your OutputCache directive.

Example code (global.asax):

public override string GetVaryByCustomString(System.Web.HttpContext
context, string custom)

{

string value=null;

if(custom.Equals("urlReferrer")

{

value= context.Request.UrlReferrer; // cache based on where the request came from!

}

}


Additional Caching Features

Applications that want more control over the HTTP headers related to caching can use the functionality provided by the System.Web.HttpCachePolicy class. The following example shows the code equivalent to the page directives used in the previous samples.

Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));

Response.Cache.SetCacheability(HttpCacheability.Public);

To make this a sliding expiration policy, where the expiration time out resets each time the page is requested, set the SlidingExpiration property as shown in the following code.

Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));

Response.Cache.SetCacheability(HttpCacheability.Public);

Response.Cache.SetSlidingExpiration(true);


When sliding expiration is enabled (SetSlidingExpiration(true)), a request made to the origin server always generates a response. Sliding expiration is useful in
scenarios where there are downstream caches that can satisfy client requests, if the content has not expired yet, without requesting the content from the origin
server.

Applications being ported from ASP may already be setting cache policy using the ASP properties; for example:

Response.CacheControl = "Public";

Response.Expires = 60;

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati
 

 

Copyright © Sharvan Dhaka