Authentication in ASP.Net


Authentication is a mechanism which detects if a user trying to access the site or resource is a valid user or not. There are lot of misinterpretations about terms Authentication and Authorization.

Authorization on the other hand is a process followed by successful authentication, which checks if the current user is having rights to access the resource.

Different modes of Authentication in ASP.Net
- None
- Windows
- Forms
- Passport

Where to set Authentication mode ?
The authentication mode can be set in a web.config file of your web application. In web.config file, under System.Web section,
we can specify Authentication mode as,

<System.Web>
    <authentication mode="Windows" />
</System.Web>

Authentications Modes in details

None - This is the most flexible mode provided for Authentication. You can use this setting if you don't want
to authenticate any user at all or you want to implement your own authentication mechanism. Custom authentication can be implemented using an ISAPI filters from IIS.

Passport - It is a central mechanism provided by Microsoft which allows single sign on with multiple sites mechanism. All member sites using passport mechanism are provided with a key which is used in single sign on mechanism across multiple domains.

Windows - It relies upon IIS for authenticating a user. With this settings, windows accounts are checked for authentication against user trying to log into the system. When IIS authenticates a user, it creates a security token and passes it to ASP.Net. ASP.Net then creates an WindowsPrincipal object and attaches it to the application context.

Forms - This mechanism allows your application to collect user credentials right from HTML forms. When a user submits the login credentials,
application code checks for user authentication. If it succeeds, it issues a cookie for the respective client. This cookies is then used for
subsequent requests from the respective client. If the cookie is not found, user is redirected to a log on page.

What is Responsive Web Design


Responsive web design, an USP that companies are using nowadays.
What is Responsive web design ?
Responsive Web Design also known as RWD is a concpet used to develop websites
which provides easy navigation, smooth and optimal viewing experience to the users.
The development involves lot of terminologies from CSS3 especially media library. Media library allows to use different types CSS depending upon the device. It can be run on desktops, laptops, tablets, mobile phones.

Referrence : http://en.wikipedia.org/wiki/Responsive_web_design

Performing self join uisng LINQ

Self join is used when one wants to refer data from the same table. Consider a scenario where we have an Employee table. Each record consist of ManagerID which is again an Employee. Now if we want to get the record of employee-manager relationship.

Consider a class Employee as,

1
2
3
4
5
6
7
public class Employee
    {
        public int EmpID { get; set; }
        public string EmpName { get; set; }
        public string City { get; set; }
        public int ManagerID { get; set; }
    }
 
We will create a list of Employee( I am using class, you can fetch records from database table)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
List<Employee> emp = new List<Employee>();
emp.Add(new Employee()
{
    EmpID = 1,
    EmpName = "a",
    City = "Pune",
    ManagerID = 11
});

emp.Add(new Employee()
{
    EmpID = 2,
    EmpName = "b",
    City = "mumbai",
    ManagerID = 12
});

emp.Add(new Employee()
{
    EmpID = 3,
    EmpName = "c",
    City = "Pune",
    ManagerID = 2
});

emp.Add(new Employee()
{
    EmpID = 4,
    EmpName = "d",
    City = "Delhi",
    ManagerID = 14
});

         
Now to query data, self join is written as,
1
2
3
var q = (from employee in emp
        join employee2 in emp on employee.EmpID equals employee2.ManagerID
        select employee).FirstOrDefault();
     
Using this query you can select child employee as well as parent employee i.e. employee as well as Manager.

Call JavaScript function from code behind in c#

Many times we come across situations where we need to call JavaScript functions from code-behind.
This can be achieved by registering ClientScript block.
Let's take a look by an example.

JavaScript function :
1
2
3
4
5
<script type="text/javascript">
        function WelcomeUser(username) {
            alert("Welcome::" + username);
        }
    </script>
Code behind :

1
2
3
4
5
protected void Page_Load(object sender, EventArgs e)
{
     ClientScript.RegisterStartupScript(GetType(), 
     "hwa", "WelcomeUser('VJ');", true);
}



This will call Welcomeuser method from code behind.

Fault Exceptions in WCF


Exceptions thrown by WCF service are treated as Fault exceptions. As a developer we should gracefully handle these kind of exceptions. Let's take a look at this by an example/

Service Contract -
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
[ServiceContract]
    public interface IService2
    {
        [OperationContract]
        [FaultContract(typeof(MyException))]
        [DebuggerStepThrough]
        MyException GetData(int value);
    }

    [DataContract]
    public class MyException 
    {
        [DataMember]
        public bool Result { get; set; }

        [DataMember]
        public string ErrorMessage { get; set; }

        [DataMember]
        public Exception MyInnerException { get; set; }

        [DataMember]
        public string ClientMessage { get; set; }
    }


Service Implementation -
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class Service1 : IService2
    {
       
        public MyException GetData(int value)
        {
            MyException mx = new MyException();
            try
            {
                double a = 44;
                if (value == 0)
                {
                    throw new DivideByZeroException();
                }
                double res = a / value;
                mx.ClientMessage = "Everything is well";
                mx.Result = true;
                return mx;
            }
            catch (DivideByZeroException dvex)
            {
                mx.Result = true;
                mx.ClientMessage = "Divide by zero";
                mx.MyInnerException = dvex;
                mx.ErrorMessage = dvex.StackTrace;
                throw new FaultException<MyException>(mx, dvex.ToString());
            }                    

        }
    }


Client (aspx.cs page) -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
try
            {
                FaultContractsDemo.ServiceReference1.Service2Client o = new ServiceReference1.Service2Client();
                MyException data = o.GetData(0);
                if (data.Result)
                    lblMessage.Text = "All is well";
            }
            catch (FaultException<MyException> ex)
            {
                lblMessage.Text = ex.Detail.ClientMessage;
            }


The service layer throws an exception, but client never recieves any. I am getting unhandled exception like,
The underlying connection was closed: The connection was closed unexpectedly.
 WCF does not like serializing the DivideByZeroException or any root exception caused at service layer, which is necessary to get it across the wire. Commenting out this would work as expected.

SaaS - Software As A Service, Kick off


What is SaaS ?
It is a software delivery model in which software and data are centrally hosted and shared amongst multiple users.
The softwares can be consumed by thin clients, with the help browsers.

Benefits of SaaS over traditional web models
No setup cost
Easy deployment
Full time support availability
Pay as you use model
Flexible maintainability
Short time ROI ( Return on Investments)

How domestic market can be targeted with SaaS
Opportunities in local market for SaaS applications
Pricing and Support benefits
Growing IT infrastructure

How subscription based licensing is attracting more customers. ROI of SaaS
Subscription based business model is saving cost by pay-per-use model. Customers get flexibility to add/remove feature at run time by just changing the subscription. It is minimizing the downtime increasing ROI

SaaS = Consumers + Technology + Business
This is basically how SaaS evolved.
The days in 1970’s and now.
Training needs

Closomo (Cloud Social Media Mobility) 
How Social Media and mobile devices can be used in cloud environment.
How organizations are making use of Social Media platform for various purposes like Business pages, recruitment etc.
Case study of usage of Twitter for technical support
App stores offered by mobile companies

SaaS development factors
Factors to be considered while moving to SaaS platform - Understanding what to do and what not do
Data Migration
Data Security
Licensing
Single Sign On
Different options for Identity management

HostingEnvironmentException while running application from IIS


I was trying to run a simple ASP.Net application on my machine. Surprisingly it failed and below exception occured.

Exception Details: System.Web.Hosting.HostingEnvironmentException: Failed to access IIS metabase.
The process account used to run ASP.NET must have read access to the IIS metabase (e.g. IIS://servername/W3SVC).
For information on modifying metabase permissions, please see http://support.microsoft.com/?kbid=267904.
Source Error:
An unhandled exception was generated during the execution of the current web request.
Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[HostingEnvironmentException: Failed to access IIS metabase.]

The framework versions installed on my machine were 1.1, 2.0, 4.0. And my application was configured for 4.0 version.
To resolve this issue we just need to open visual studio command prompt and type the following command.

aspnet_regiis.exe /r

This will install the respective version of ASP.Net.

How to call default contstructor from another one


One of my team mate asked me this question today. I was not aware of this before that.
Here is a code for the same,

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public class A
    {
        public A()
        {
            Console.WriteLine("Default");
        }

        public A(string msg) : this()
        {
            Console.WriteLine("this is param : " + msg);
        }
    }
    
Now when you create instance of class A as,

1
A objA = new A("Hello");

It will print statements as;
Default
this is param : Hello

How to decide database connection instance dynamically ?


This was a question asked by one interviewer in my early interviews. The scenario was that,
an application makes use of several database providers. How one can decide which connection instance to be used at run time.
The answer lies in the question itslef. I couldn't figure it out at that time.

This can be achieved by ProviderName attribute available in ConnectionString format. Let's do it by an example.

Consider a connection string as,

1
2
3
4
5
6
7
8
<connectionStrings>
    <add name="LocalSqlServer"
    connectionString="data source=.\SQLEXPRESS;
    Integrated Security=SSPI;
    AttachDBFilename=|DataDirectory|aspnetdb.mdf;
    User Instance=true"
    providerName="System.Data.SqlClient" />
</connectionStrings>


Here we have ProviderName as 'System.Data.SqlClient'. The configuration can have multiple connectionStrings with different providerName values. We can retrive providerName value and can create an instance based upon it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
ConnectionStringSettings connection =  ConfigurationManager.ConnectionStrings["LocalSqlServer"];
DbConnection db = null;
switch (connection.ProviderName)
{
    case "System.Data.SqlClient":
      db = new SqlConnection(connection.ConnectionString);
      break;
    case "System.Data.OleDb":
      db = new OleDbConnection(connection.ConnectionString);
      break;
    case "System.Data.Odbc":
      db = new OdbcConnection(connection.ConnectionString );
      break;
    case "System.Data.OracleClient":
      db = new OracleConnection(connection.ConnectionString);
      break;
}


Read CDATA section based on where clause using LINQ

Consider an XML as below;
<Book>
  <BookItem ISBN="SKS84747"><![CDATA[20]]> </BookItem>
  <BookItem ISBN="LHKGOI84747"><![CDATA[50]]> </BookItem>
  <BookItem ISBN="PUOT84747"><![CDATA[20]]> </BookItem>
</Book>

This code gives me all the CDATA sections,

var value = from v in x.Descendants("BookItem").OfType<XCData>()
                                select (string)v.Value;

In order to get CDATA of any particular node based on where clause we need to execute below query as,

var value = x.DescendantNodes().OfType<XCData>()
                .Where(m => m.Parent.Name == "BookItem" && m.Parent.Attribute("ISBN").Value == "PUOT84747")
                .ToList();

This statement will return all the CDATA sections matching in where clause.
To get the single item just replace .ToList() with .Select(cdata => cdata.Value.ToString());

var value = x.DescendantNodes().OfType<XCData>()
                .Where(m => m.Parent.Name == "BookItem" && m.Parent.Attribute("ISBN").Value == "PUOT84747")
                .Select(cdata => cdata.Value.ToString());

ToolStrip control extended


Today one of my clients asked me to show a button in ToolStrip control. He provided that this button should look like a regular button. The one which we use on WinForms. The default button available in ToolStrip control provided limited set of properties than the regular button control. It does not support border, flaststyle etc. properties.

Then from MSDN I found out the ToolStripControlHost class which allows developer to extend any standard .net control and add it to the ToolStrip.
You have to just extend this class so as to add any control. Here is a sample code,
I have used 2 controls A Button and A LinkLabel.
    public class ToolStripControlButton : ToolStripControlHost
    {
        public ToolStripControlButton()
            : base(new Button())
        {
        }

        public Button ButtonControl
        {
            get
            {
                return Control as Button;
            }
        }
    }


    public class ToolStripControlLinkLabel : ToolStripControlHost
    {
        public ToolStripControlLinkLabel()
            : base(new LinkLabel())
        {
        }

        public LinkLabel LinkLabelControl
        {
            get
            {
                return Control as LinkLabel;
            }
        }
    }
Then in the loading event of a form you can add these controls to the ToolStrip as,

ToolStripControlButton tsBtn = new ToolStripControlButton();
tsBtn.Text = "test";

ToolStripControlLinkLabel tsCal = new ToolStripControlLinkLabel();
tsCal.Text = "Visit us";
tsCal.Alignment = ToolStripItemAlignment.Left;
            
toolStrip1.Items.Add(tsCal);
toolStrip1.Items.Add(tsBtn);

When you run your program and when form is loaded it will show you these statndard controls as a part of ToolStrip.

DBML designer over SQLMetal


Today I got an assignment from client that the update query is running too slow. I started debugging it and found that the update is using all the fields. I came to know that LINQ to SQL by default assume that all columns participate in opt concurrency and generates a full WHERE clause.
So the query looks like,

UPDATE [dbo].[TableName]
SET [Column1] = @p1, [Column2] = @p2, [Column2] = @p3, [Column3] = @p4, [Column4] = @p5
WHERE [PRIMARYKEY] = @p0 AND
[Column2] = @p2 AND
[Column2] = @p3 AND
[Column3] = @p4 AND
[Column4] = @p5

From this link http://stackoverflow.com/questions/10136450/submitchanges-internally-adds-all-the-fields-as-where-clause-how-to-get-rid-of I came to know about a property UpdateCheck. This has to be set to NEVER in order to remove it from concurrency controlling. But this is not possible with SQLMetal tool because it generates the class structure straight away through command line.

Then I tried DBML designer. In DBML designer you can set the properties for every column from visual studio. So I dropped my table into the designer and it's respective code generated. Both the tools generate the same code, but designer facilitates you with properties window to change them at any point of time.
With UpdateCheck set to never the query gets generated like this,

UPDATE [dbo].[TableName]
SET [Column1] = @p1, [Column2] = @p2, [Column2] = @p3, [Column3] = @p4, [Column4] = @p5
WHERE [PRIMARYKEY] = @p0

To mention the disadvatages of setting UpdateCheck to never is the application looses concurrency control. The where clause gets cut down and allows multiple users to update the table at the same time.

Performing pre-termination activities using ProcessExit event

In many cases we use resources such as files, storage, connections etc. in our application. Being a programmer it is our responsibility to free up all the used resources before terminating our program. We have try {} finally{} which does the same thing. This can be achieved by AppDomains ProcessExit event.

    class Myclass
    {
        // will print 1st also sets up Event Handler
        static Myclass()
        {
            Console.WriteLine("I am inside Myclass");
            
        }

        static void Main(string[] args)
        {
            Console.WriteLine("I am inside Main()"); // it will print 2nd
            AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);
        }

        static void CurrentDomain_ProcessExit(object sender, EventArgs e)
        {
            Console.WriteLine("I am the last one to run");
        }
    }

Executing this program will print
I am inside Myclass
I am inside Main()


Obviously the last statement will not be visible, as the application is still running. But, you can try writting in an event log to see how it works.

LINQ update on table having no primary key


I was trying to update a record in a table last night, using LINQ. Everything was fine and running without any errors.
Surpisingly the record was not getting updated. I then attached the modified object to the context. It started giving an exception as,

Can't perform Create, Update or Delete operations on Table because it has no primary key.

Then I realised that there is no primary key assigned to the table. The possible solution was to change the database schema and add primary key 
to that table. But this change was not acceptable.
Further debugging into the code I got the workaround for this. 

When we generate a class file using a tool such as sqlmetal or anything else, certain attributes are associated with the columns of that table.
We can open that class file and manually add IsPrimary= true attribute to any one of the columns.

This will fool the LINQ engine and treat the respective column as a primary key.

Here is an example for the same.
I have generated a class with table as TableWithNoPK. It has 3 columns as Field1, Field2, Field3.
I assigned IsPrimary attribute to field1 as,

[global::System.Data.Linq.Mapping.ColumnAttribute(Name="field1", Storage="_Field1", DbType="VarChar(50)", IsPrimaryKey= true)]
        public string Field1
        {
            get
            {
                return this._Field1;
            }
            set
            {
                if ((this._Field1 != value))
                {
                    this._Field1 = value;
                }
            }
        }


The c# code goes normal as,

var qry = from NoPK in instance.TableWithNoPK
                      select NoPK;

       TableWithNoPK test = qry.FirstOrDefault();
       test.Field3 = "Gud 1";
       instance.SubmitChanges();


ABC of WCF




Address

This is a url which specifies where the service is hosted. Example is like,
http://localhost:2190/MyFirstService/MyService.svc

Binding

Binding decribes how the client will communicate with the service. WCF makes use of various protocols to communicate with client.
You can read more details about types of bindings here.

Contract

This specified what operation(s) to be carried out. It is simple request/response, duplex exchange of information between client and service.
Examining end-points, client come to know what all operations are exposed by a service.

Detect session expiry using JavaScript

I was working on a web application using ASP.Net. I was making use session in my application. 
There was one scenario where I was trying to access session variable through JavaScript. It works fine, when session is accessed in normal state ( i.e. session is not expired). But after session expiry, if click on any button, it was throwing an exception and start abnormal behavior, resulting in page not found. 
To tackle with this, I used session handling from JavaScript as;


public string TransactionID
{
   get { 
        var data = ((Hashtable)(Session["SessionData"])); 
        if (data != null)
           return data["TransactionID "];
        else
           return null;
   }
}

Creating Singleton class in C#


In many of the cases, we come accross situations where we want to create only one instance of a class. And use it throughout the application. As a programmer we have to take care of that from the code itself. Let's take a look at this step by step.

We will create a class MySingletonClass in such a way that it can be instantiated only once.

    public class MySingletonClass
    {
        //This will create a static instance of the class MySingletonClass
        private static MySingletonClass instance;

        //Private constructor
        private MySingletonClass() { }

        public static MySingletonClass Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new MySingletonClass();
                }
                return instance;
            }
        }

        public void DoWork()
        {
            Console.WriteLine("I am going for lunch");
        }
    }

So we are done with the class definition. Now let's start creating it's instances.

    class Program
    {
        static void Main(string[] args)
        {
            MySingletonClass objMySingleton = MySingletonClass.Instance;
            MySingletonClass objMySingleton2 = MySingletonClass.Instance;

            objMySingleton.DoWork();

            Console.ReadLine();
        }
    }

If you debug this code and put a break-point at get of Instance, you will notice that the object creation statement will get executed only once for the first object. For later requests the program will serve the existing one.

Now, if by mistake or intentionally, someone else tries to create an instance of MySingletonClass in traditional way as;

MySingletonClass objMySingleton = new MySingletonClass();

Our private constructor will not allow this to be compiled due to protection level.
So our class can be instantiated only once from anywhere in the application and the instance can be shared.


Use of ConfigurationProviders to protect connection string


In a web application, an ideal way to store the connection string is using web.config file.
web.config consist of several section one of them is connectionStrings. Storing connection string in
a plain text can be risky to some extent. .Net framework has provided a mechanism using which you can protect
your connection string. So that if accidentally anyone breach into your system and get an access to web.config file,
the connectionString is not reachable to that person.

Let's take a look at this with an example;
1. Create a web site project using Visual Studio.

2. To have a connection string, we will use GridView control. Open default.aspx in design mode.
3. Go to toolbox and drag a gridview control onto the form and set it's datasource as per your database object.
4. The code behind will now look like this.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            DataKeyNames="DeptID" DataSourceID="SqlDataSource1" 
            EnableModelValidation="True">
            <Columns>
                <asp:BoundField DataField="DeptID" HeaderText="DeptID" InsertVisible="False" 
                    ReadOnly="True" SortExpression="DeptID" />
                <asp:BoundField DataField="DeptName" HeaderText="DeptName" 
                    SortExpression="DeptName" />
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:MySampleDBConnectionString %>" 
            SelectCommand="SELECT [DeptID], [DeptName] FROM [Department]">
        </asp:SqlDataSource>

5. web.config file will then be reflected with the <connectionStrings/> section which is in readable format.
6. Now to protect the connectionString, open default.aspx.cs file and add these 2 functions.
private void EncryptConnString(string protectionMode)
    {
        Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
        ConfigurationSection section = config.GetSection("connectionStrings");
        section.SectionInformation.ProtectSection(protectionMode);
        config.Save();
    }

    private void DecryptConnString()
    {
        Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
        ConfigurationSection section = config.GetSection("connectionStrings");
        section.SectionInformation.UnprotectSection();
        config.Save();
    }

7. In page_load function give call as,
Either
EncryptConnString("RSAProtectedConfigurationProvider");
OR
EncryptConnString("DataProtectionConfigurationProvider");

8. For DataProtectionConfigurationProvider, the connectionString section will be then modified as,

<connectionStrings configProtectionProvider="DataProtectionConfigurationProvider">
    <EncryptedData>
      <CipherData>        <CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAPZoPJPL7WU2bSGOa18BMVwQAAAACAAAAAAADZgAAqAAAABAAAAAfUh8QAdOcGZJJNc+9QTbJAAAAAASAAACgAAAAEAAAAPlnxynAFzHQ+uS2csFRjO+4AQAAtmWRrXO0QUf9a4haoioMng7gQuAyIBI2q0XJS3j4PwwVLRU+jLwg0CbvFjsrAg6uQG48ooiJO/IaRC9KGnPp2bAFSJZBDsE7UKGN9aa8tC1XqzEn4pzDKsybx1rlJUPE5pX+dfY/oa7PEbrNsqS0OcIiEFWJtvGlKFLmNAXN0CEiSz0AiMMIrqYtFZFNkJyCcqY7InuwqvburYnMTUX5NPco/zeJw+in3CcBaymsMc/9MPe5IwcKJBDOaH2ay8Rt+O3RXdvrCC0TalJlt/l2N4Hd3HPX/6YIUS2vWxIXlwiDT442sjLHUKFiXW2waDUHQx91vfDF9AxX4G4N3O0grr4CyG3OVz4KVHXskDqdStzCeKQQNeQp4et6ldrJjk50aHpmOlVYpV/ilhdanKDRYmwRSiHtv/F6VWyYBpa9MBbfKhS3fAX/pYohjesiUmUKz0J9h4T2Vkyd+WD6eiIMs/giPimaYtiwJFrh8fb1/9BbsPXfFU7dbh22P3s0BZI5cilQxcto/4aNgMhMmMAGRN23jEMK6kzTiLD75WSxnlMZryyr4UqUlaGdI0tLF+GB6Kqro7BmkQ8UAAAA64RcPSpRfxsAIuu5N+rLu92Dd7c=</CipherValue>
      </CipherData>
    </EncryptedData>
  </connectionStrings>

9. If you make use of RSAProtectedConfigurationProvider the section will look like,

<connectionStrings configProtectionProvider="RsaProtectedConfigurationProvider">
    <EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element"
      xmlns="http://www.w3.org/2001/04/xmlenc#">
      <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
      <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
        <EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">
          <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
          <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
            <KeyName>Rsa Key</KeyName>
          </KeyInfo>
          <CipherData>
            <CipherValue>dAlnD1WJk7imw0yfupREP4ifSHMaJm1cKHVwHQXPRoThnIVtTT3j+svOrELJeIV6gs+KuEdglhhQQo7VBlmQwfcOXxcqyd4/YjAE+Q45YSAI23gQ5Y5WOQU5pvyNyqZJR4XJN2eWzZ6ZBVyTVqiZ9fVEsamPF0R1oesh9CNMD+8=</CipherValue>
          </CipherData>
        </EncryptedKey>
      </KeyInfo>
      <CipherData>
        <CipherValue>cEPk5EBd58MjInYNrh1oGHp5KH4S4vocyUrPnK5Z/aCaehRxio/XE+IK6GnrvpltQRlZv6fzy/RlrDDpI4uHF0U87kbIYCa9/RbBwlmg4Z14IMuCFpWuBjA+fBqkRiWTn5+6bXxHyS+3WC30kNumxKxSuk5unfvLdD5G7Ei4w1wITwR27zG9MIxJm3UYAYQ8FuDCLloXZEuULRyvB0F9z56eWxcpPU/8koYu7l6siZ5tKO674zZEOp1pzhDEElBcN1o0onFJ0rjJse3lOIAveRFQ5bg35MkjmEYYrSCKLQC1hJ6E4hvfvw==</CipherValue>
      </CipherData>
    </EncryptedData>
  </connectionStrings>




Can multiple catch blocks be executed ?

One of my acquaintance asked this question. Initially I got confused that is it really possible.
The answer to this question is "NO". Here is a program in support with this answer.

    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                int numerator = 20;
                int denominator = 0;
                int result = numerator / denominator;
            }
            catch (DivideByZeroException de)
            {
                Console.WriteLine("You are trying to divide by number 0");
            }
            catch (Exception ex)
            {
                Console.WriteLine("This is a general exception.");
            }
            finally
            {
                Console.WriteLine("You are in finally block.");
            }
        }
    }

The output of this program is;
You are trying to divide by number 0
You are in finally block.

This means that when an exception occurs, and is handled with the specific type it executes the statements in the catch block and leaves the control to finally block, if exists.

It is not possible to execute multiple catch blocks.

What is the difference between Web Application project and Web site project?

Web Application project was launched with Visual studio 2005. Both the models has their own characteristics.

Web Application Project -
1. Run on IIS as well as ASP.net internal server.
2. The compiled output is a single assembly.
3. Change in one perticular file requires recompilation of entire application.
4. Consist of its own project file, so the application is structured based on the project file.


How to create a Web Application?





Web Site Project -
1. Run on IIS as well as ASP.net internal server.
2. Each page gets compiled into its own assembly.
3. Changes can be applied without compilation of entire site.
4. Do not consist of project file. Structure is based on the file system.

How to create Web Site Project?