Friday 4 December 2015

Server.MapPath

Server.MapPath(".") returns the current physical directory of the page that you are running
Server.MapPath("..") returns the parent physical directory of the page that you are running
Server.MapPath("~") returns the physical path of the root directory of the application 

Binding an asp.net dropdownlist with an XML file

First add an XML file, to the web application project. To do this 
1. Right click on the web application project, and select Add => New Item.
2. In the Add New Item dialog box, select XML File.
3. Give the XML file a meaningful name. In our case let's name it Countries.xml and click Add.
4. In the Countries.xml file, copy and paste the following
<?xml version="1.0" encoding="utf-8" ?>
<Countries>
  <Country>
    <CountryId>101</CountryId>
    <CountryName>India</CountryName>
  </Country>
  <Country>
    <CountryId>102</CountryId>
    <CountryName>USA</CountryName>
  </Country>
  <Country>
    <CountryId>103</CountryId>
    <CountryName>Australia</CountryName>
  </Country>
  <Country>
    <CountryId>104</CountryId>
    <CountryName>Africa</CountryName>
  </Country>
</Countries> 


Drag and drop a DropDownList on the webform. Copy and paste the following code in the code behind page.
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        //Create a new DataSet
        DataSet DS = new DataSet();
        //Read the xml data from the XML file using ReadXml() method
        DS.ReadXml(Server.MapPath("Countries.xml"));
        DropDownList1.DataTextField = "CountryName";
        DropDownList1.DataValueField = "CountryId";
        DropDownList1.DataSource = DS;
        DropDownList1.DataBind();
        ListItem li = new ListItem("Select""0");
        DropDownList1.Items.Insert(0, li);
    }
}

The important thing to notice here is that, we are using ReadXml() method of the DataSet object, to read the data from the Countries.xml file into a DataSet.Server.MapPath() method returns the physical path of the file from the provided virtual path. We will discuss about this method in a later video session.

To insert a ListItem at a specific location use the Insert() method specifying the index of the location where you want to insert, and the listitem object.

IsPostBack in asp.net

IsPostBack is a Page level property, that can be used to determine whether the page is being loaded in response to a client postback, or if it is being loaded and accessed for the first time. 

In real time there are many situations where IsPostBack property is used. For example, consider the webform used to register employee details. A sample form that we will use for this example is shown below. The form has First Name, Last Name and City fields.  

If you want to follow along with me, copy and paste the following HTML in a web form.
<table style="font-family: Arial">
    <tr>
        <td colspan = "2"><b>Employee Details Form</b></td>
    </tr>
    <tr>
        <td>First Name: </td>
        <td> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> </td>
    </tr>
    <tr>
        <td>Last Name: </td>
        <td> <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> </td>
    </tr>
    <tr>
        <td>City:</td>
        <td>
            <asp:DropDownList ID="ddlCity" runat="server">
            </asp:DropDownList>
        </td>
    </tr>
    <tr>
        <td></td>
        <td>
            <asp:Button ID="Button1" runat="server" onclick="Button1_Click" 
                Text="Register Employee" />
        </td>
    </tr>
</table>

Copy and Paste the following code in the code behind file of the web form.
protected void Page_Load(object sender, EventArgs e)
{
    LoadCityDropDownList();
}
public void LoadCityDropDownList()
{
    ListItem li1 = new ListItem("London");
    ddlCity.Items.Add(li1);

    ListItem li2 = new ListItem("Sydney");
    ddlCity.Items.Add(li2);

    ListItem li3 = new ListItem("Mumbai");
    ddlCity.Items.Add(li3);
}
protected void Button1_Click(object sender, EventArgs e)
{
} 

Now run the application. Look at the City DropDownList. The cities, (London, Sydney and Mumbai) are correctly shown as expected. Just click the button once. Notice, that the city names in the DropDownList are duplicated. So, every time you click the button, the city names are again added to the DropDownList.

Let's now understand the cause for this duplication.
We know that all ASP.NET server controls retain their state across postback. These controls make use of ViewState. So, the first time, when the webform load. the cities get correctly added to the DropDownList and sent back to the client.

Now, when the client clicks the button control, and the 
webform is posted back to the server for processing. During the Page initialization, ViewState restoration happens. During this stage, the city names are retrieved from the viewstate and added to the DropDownList. PageLoad event happens later in the life cycle of the webform. During page load we are again adding another set of cities. Hence, the duplication.

How to solve the DropDownList items duplication
There are several ways to solve this. One of the best ways to do this, is to use IsPostBack property. So, in the Page_Load, call LoadCityDropDownList() method, if the request, is not a postback request. That is, only if the webform is being loaded and accessed for the first time.
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        LoadCityDropDownList();
    }
}

Another way to solve, this problem is to simply disable the ViewState of the DropDownlist control. To disable the viewstate, right click the DropDownList control, and set EnableViewState property to false. Now run the project, and the cities duplication issue is gone.

But the problem, with 
this approach is that, the DropDownList list, does not remember your selecttion across postback. That is, Select "Mumabi" as the city, and submit the form. When the page rerenders, observer that selection is set back to "London". Another problem with, disabling the viewstate is that, the DropDownList events may not work correctly as expected.

Another way to solve this, is to clear all the DropDownList items, before calling LoadCityDropDownList() method. But this not efficient from a performance perspective. The modified code is shown below.
protected void Page_Load(object sender, EventArgs e)
{
    ddlCity.Items.Clear();
    LoadCityDropDownList();
} 


Monday 23 November 2015

How is the DLL HELL problem solved in .NET

In short, the dll hell problem is solved in .NET by signing the shared assemblies with strong name

In dot net all the shared assemblies are usually in the GAC. GAC stands for Global Assembly Cache. The path for GAC is
 C:\[OperatingSystemDirectory]\assembly. For example on my computer the path is C:\WINDOWS\assembly. The image below shows the shared assemblies in the GAC.



Only strong named assemblies can be copied into GAC. Strong named assemblies in .NET has 4 pieces in its name as listed below.
1. Simple Textual Name
2. Version Number
3. Culture
4. Public Key Token


All these four pieces put together, is called as the fully qualified name of the assembly. In the GAC image above Accessibility assembly has a version of 2.0.0.0.
 

Now consider the example below:
1. I have 2 applications, Application - A1 and Application - A2 which relies on the shared assembly Accessibility.dll (Version 2.0.0.0) as shown in the image below.
2. Now, I have a latest version of Application - A2 available on the internet.
3. I download the latest version of A2 and install it on my machine. 
4. This new installation copies a newer version of Accessibility.dll into the GAC with version 3.0.0.0.
5. So, in the GAC we now have 2 versions of Accessibility.dll. 
6. Application - A1 continues to use Accessibility.dll (version 2.0.0.0) and Application - A2 uses Accessibility.dll (version 3.0.0.0) 
7. So, now the assemblies are able to reside side by side in the GAC. For this reason dot net assemblies are also said to be supporting side by side execution.

What is DLL HELL in .NET

Let us try and understand DLL HELL problem with an example.
1. I have 2 applications, A1 and A2 installed on my computer. 

2. Both of these applications use shared assembly shared.dll

3. Now, I have a latest version of Application - A2 available on the internet.

4. I download the latest version of A2 and install it on my machine.

5. This new installation has over written Shared.dll, which is also used by Application - A1.

6. Application - A2 works fine, but A1 fails to work, because the newly installed Shared.dll is not backward compatible.

So, DLL HELL is a problem where one application will install a new version of the shared component that is not backward compatible with the version already on the machine, causing all the other existing applications that rely on the shared component to break. With .NET versioning we don’t have DLL HELL problem anymore.


Wednesday 14 October 2015

How to handle 403 error in ASP.Net

How to handle 403 error in ASP.Net

Using the following code you can not resolve 403 error.

<customErrors mode="On">
      <error statusCode="400" redirect="error/error_page.aspx?ID=400" />
      <error statusCode="403" redirect="error/error_page.aspx?ID=403" />
      <error statusCode="404" redirect="error/error_page.aspx?ID=404" />
      <error statusCode="500" redirect="error/error_page.aspx?ID=500" />
</customErrors>

To resolve 403 error use the following code.

 <httpErrors errorMode="Custom">
      <error statusCode="403" subStatusCode="14" path="http://mywebsite.com/error/error_page.aspx?id=403" responseMode="Redirect" />
  </httpErrors>

Tuesday 6 October 2015

What is the differnce between var and dynamic keyword?

What is the differnce between var and dynamic keyword?

Suppose we have code like below.

var i= 123;
i="ABC";
print(i);
Above code will give compilation error "Cannot implicitly convert type 'string' to 'int'",
because when we initialize the var variable first time it will decide the datatype according
to value which we assign,
here first we assign i=123, so on the basis of value i is integer, intetger datatype is got
assigned and therefore later we cannot assign string value to it.

And suppose with dynamic keyword we have code like below

dynamic i= 123;
i="ABC";
print(i);
Above code gives the output as "ABC" because as name suggest the dynamic variable can deal
with any kind data type, no matter which first value is assign to this variable.

Can we overload methods in following way?

Can we overload methods in following way?

public void MySampleMethod(int i) { }
public void MySampleMethod(ref int i) { }
The signature of a method consists of the name of the method,
the number of type parameters and the type and kind (value, reference, or output)
of each of its formal parameters, considered in the order left to right.

So with above code as there is use of "ref" keyword which makes it unique signature
comapre to other one i.e. we can overload method in above way.

Can we overload methods in following way?

public void MyTestMethod(ref int x){}
public void MyTestMethod(out int x){}

though kind of parameter is a part of signature as
like previous case but here you have used ref and out toghether which is providing
same meaning to the methods therefor you cannot overload methods in same class or
interface solely by ref and out so above code will throw following error.

"Cannot define overloaded method 'MyTestMethod' because it differs from another method only on ref and out"

The differences between LEN and DATALENGTH in SQL Server

The differences between LEN and DATALENGTH in SQL Server

LEN
Returns the number of characters, rather than the number of bytes,
of the given string expression, excluding trailing blanks.

DATALENGTH
Returns the number of bytes used to represent any expression.

So what does that mean? It means that the LEN function will first right
trim the value and then give you a count of the charaters, the DATALENGTH
function on the other hand does not right trim the value and gives you the
storage space required for the characters.

Take a look at this example
declare @v nchar(5)
select @v ='ABC  '


select len(@v),datalength(@v)
The output for len is 3 while the output for datalength =10. The reason that
datalength returns the value 10 is because nvarchar uses 2 bytes to store 1
character by using unicode while varchar is using ascii which requires 1 byte
per charaters