Thursday, April 30, 2009

Create row at run time in ASP.NET GridView

Here I have created an ASP.NET GridView example where you can add, delete and update the row in the GridView at run time.

Steps:

1. Create a asp.net web application

2. Create a global DataTable globalDataTable

3. To create a DataTable first time I have created the following function


private DataTable CreateDataTable()
{
  DataTable dtSample = new DataTable();

  DataColumn myDataColumn;

  myDataColumn = new DataColumn();
  myDataColumn.DataType = Type.GetType("System.String");
  myDataColumn.ColumnName = "Id";
  dtSample.Columns.Add(myDataColumn);


  myDataColumn = new DataColumn();
  myDataColumn.DataType = Type.GetType("System.String");
  myDataColumn.ColumnName = "FirstName";
  dtSample.Columns.Add(myDataColumn);

  myDataColumn = new DataColumn();
  myDataColumn.DataType = Type.GetType("System.String");
  myDataColumn.ColumnName = "LastName";
  dtSample.Columns.Add(myDataColumn);

  return dtSample;
}

First time when the page is loaded it call this function to create the gridview and then store the gridview into the Session["dtSample"]. You can also use viewstate here instead of session.

4. To create a new row in the gridview the following function has been created :


private void AddNewRow(string firstname, string lastname, DataTable myTable)
{
  DataRow row;

  row = myTable.NewRow();

  row["Id"] = myTable.Rows.Count + 1;

  row["FirstName"] = firstname;

  row["LastName"] = lastname;

  myTable.Rows.Add(row);

  rowCount = myTable.Rows.Count;
}


6. To Edit and Delete from the gridview the following event has been added to the gridview


protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
  DataTable userDataTable = (DataTable)Session["dtSample"];

  userDataTable.Rows[e.RowIndex].Delete();

  Session["dtSample"] = userDataTable;

  this.GridView1.DataSource = ((DataTable)Session["dtSample"]).DefaultView;

  this.GridView1.DataBind();

}

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{

  DataTable userDataTable = (DataTable)Session["dtSample"];

  if (userDataTable != null)
  {
    lblMsg.Text = Convert.ToString(userDataTable.Rows[e.NewEditIndex]["Id"]);

    txtFirstName.Text = Convert.ToString(userDataTable.Rows[e.NewEditIndex]["FirstName"]);

    txtLastName.Text = Convert.ToString(userDataTable.Rows[e.NewEditIndex]["LastName"]);
  }
}


7. We have saved the data on the Submit button click. 



protected void btnSubmit_Click(object sender, EventArgs e)
{
   if (txtFirstName.Text.Trim() == "")
   {
     this.lblMsg.Text = "You must fill a name.";
     return;
   }
  else
  {
   if (lblMsg.Text != "")
    {
      DataTable dtSample = (DataTable)Session["dtSample"];

     for (int iCount = 0; iCount < dtSample.Rows.Count; iCount++)
     {
      if (Convert.ToString(dtSample.Rows[iCount]["Id"]) == lblMsg.Text)
       {
         dtSample.Rows[iCount]["FirstName"] = txtFirstName.Text;
         dtSample.Rows[iCount]["LastName"] = txtLastName.Text;
        }
     }
 }
else
 {
  AddNewRow(this.txtFirstName.Text.Trim(), this.txtLastName.Text.Trim(), (DataTable)Session["dtSample"]);
}

 this.GridView1.DataSource = ((DataTable)Session["dtSample"]).DefaultView;      this.GridView1.DataBind();
this.txtFirstName.Text = "";
this.txtLastName.Text = "";
this.lblMsg.Text = "";
 }
}




Download:

Wednesday, April 29, 2009

Use email template and send email with ASP.NET

Sometimes you need to send the email with the formatted manner. Here I have created a sample application by which you can send mail with the html template.


Steps:


1. Created an Email Class library, where a SendMail has been created which contins the properties and functions to send the mail.


2. Created a Web Application “EmailApplication” and added the reference of Email Class library.


3. Create the Test.html page to send the formatted mail. With the $ sign you can set the values at the run time. For example if I need to set the title of the email then I used $Title in html page.


4. Set the following things in the web.config file



< key="SmtpServer" value="mail.mailserver.com">
< key="SiteUrl" value="www.mysite.com/default.aspx" />
< key="IsSend" value="Yes">
< key="SendMailBackground" value="Yes">
<system.net>
<mailSettings>
<smtp>
< host="mail.mailserver.com" port="25" username="" password="">
< / smtp >
< / mailSettings >
< / system.net >


Here SmptServer represent the SMTP Server name, SiteUrl represent the your site url , SendMailBackground specify whether the mail should be send by background or not and IsSend represent whether you want to send the mail or not. If you want to stop the mail send facility then you don’t need to change the code you just need to change the web.config file to set the value of IsSend to “No”.



5. To send the mail through the site I have created a UI as Default.aspx, where you have to specify the sender email address, subject, message and attached file.



Download:

Monday, April 27, 2009

Get user Permission from file or folder in asp.net

Here I have upload the sample example to get the specific user permission on a specified file or folder. To get the permission I have created a function
public string GetDirectoryAccessControlInformation(string objectPath, string userName)
{
---------------------
}

Where we have to pass the file/folder path and the username.

Download:

Sunday, April 26, 2009

implement impersonation in an ASP.NET application

Impersonation in .Net allows you to run an application in a particular user account which is determined by you. Usually the account in which the application runs is ASPNET or NETWORK SERVICE depending on the version of IIS you are running in your machine. With IIS 5.0 the ASPNET account is used and it is not possible to override this account in the web.config file. In the IIS 6.0 you can configure this in the web.config file so that you can run the application on a different user account. With the help of impersonation, application can be run by a different user with different permission levels.
We can implement Impersonation in three ways:

1. Impersonate the Microsoft IIS Authenticated Account or User:

To impersonate the IIS authenticating user on every request for every page in an ASP.NET application, we must include an tag in the Web.config file of this application and set the impersonate attribute to true. By default impersonation is disabled and the anonymous user account is used by IIS.
< impersonate="'">
2. Impersonate a Specific User:
To impersonate a specific user for all the requests on all pages of an ASP.NET application, you can specify the userName and password attributes in the tag of the Web.config file for that application.
< impersonate="'" username="AccountName" password="password">


3. Impersonate through the code:
I have a machine A (Server) from where I have to use its resources. That machine is very secure and does not allow accessing its resources to everyone (Client). To accessing its resources I have to implement the Impersonation. Since there are numbers of users who will access those resources, that’s why I have to implement the Impersonation through the code.



Figure-1


As you can see in the Figrue-1, there is a Machine A and I have to read and write a Myfile.xml file, which is located in the file system of the Machine A. Since no any client can read/write that file, so that I have created a Web Service in ASP.NET and apply the impersonation into that web service, and all the clients can access that web service and easily read/write into that file. You can also implement the same scenario to create/delete the file or folders in the server.


Steps:

1. Create a new web service.

2. Change into the web.config file. Add the following tag in the tag.

< key="FilePath" value="D:\Projects\Impersonation\Myfile.xml">
< key="UserName" value="Pankaj">
< key="Pwd" value="password">
< key="DomainName" value="DomainName">

Change the appropriate values according to the authenticated user of that machine.

3. Include the AuthenticateUser class in the web service. This class is used to impersonate your code.
4. Add the following function to the Service.cs class

private void AuthenticateUser()
{
AuthenticateUser obAuthenticateUser = new AuthenticateUser();
try
{
obAuthenticateUser.Authenticate();
}
catch
{
throw;
}
finally
{
obAuthenticateUser = null;
}

4. Call the AuthenticateUser(); method into the every method of the web service. This method should be the called first in the each method, because this method will authenticate your code to run in the context. For example I have to get the Folder Path from the MyFile.xml, then I have created a function GetFolderPath in the service.asmx.cs file and write the code in the following manner

[WebMethod]
public string GetFolderPath()
{
//authenticate the user
AuthenticateUser();
string folderPath = string.Empty;
FileOperation.FileOperation obFileOperation = new FileOperation.FileOperation();
try
{
folderPath = obFileOperation.FolderPath;
}
catch
{
throw;
}
return folderPath;
}
5. Create a Web Application and add the reference of the web service. Now your web application can read and write the xml file which is located to another machine.
Why I have used Web Service: When we have a two or more then two machines (hosting server), and we need to read/write the file from a specified machine (hosting server) and each machine have different authentication, then web service is the best solution. I will create a web service and integrate each web service in each machine with their specified user authentication. Now each machine have same web service with their authentication to read/write file of that machine. Now any user to read/write that file of any machine then it does not need to be authenticated, since web service is already authenticated, it just need to call the web service of that specified machine. To call the specified web service of a machine, we can call by the setting of url of the web service object at run time. For example, suppose I am userA and I need to access the Machine-A web service to read/write the file of Machine-A. There is also another machine Machine-AA where my web application is hosted. Now I need to access the Machine-A file though the hosted web application of Machine-AA. Then I will pass the IP address of the Machine-A and set the url property of the Machine-A's web service object. i.e.
obMachine-AWebService.Url = "http://" + IPAddressOfmachine-A + "WebserviceName" ;
Now we can access the any machine's file/web service only just passing the IP address of that machine with the same web application.

Download:

Tuesday, April 21, 2009

Sorting in a Asp.net Gridview with custom data object


This article explains about how to sort the gridview with the custom object. Here I have used viewstate and no need to any server call for the sorting.
Here I have filled the gridview with all the files or folder within a directory. To get the properties of the file/folder I have created a class FileObject class


public class FileObject
{
private string name;
private string path;
private int size;
private string type;
private string modified;

public string Modified
{
get { return modified; }
set { modified = value; }
}
public string Type
{
get { return type; }
set { type = value; }
}
public int Size
{
get { return size; }
set { size = value; }
}
public string Path
{
get { return path; }
set { path = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
}

To store all the object to a collection I have created a custom collection class.
public class DataCollection : IEnumerable
{
private List listData = new List();

public T GetData(int index)
{
return listData[index];
}
public void AddData(T c)
{
listData.Add(c);
}
public void ClearData()
{
listData.Clear();
}
public int Count
{
get { return listData.Count; }
}
// IEnumerable extends IEnumerable, therefore
// we need to implement both versions of GetEnumerator().
IEnumerator IEnumerable.GetEnumerator()
{
return listData.GetEnumerator();
}

System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return listData.GetEnumerator();
}
public void Add(T c)
{
listData.Add(c);
}

}


To sort the data in the collection I have created a GenericComparer class which is inherited from the IComparer.
public sealed class GenericComparer : IComparer
{

public enum SortOrder { Ascending, Descending };

#region member variables

private string sortColumn;

private SortOrder sortingOrder;

#endregion

#region constructor

public GenericComparer(string sortColumn, SortOrder sortingOrder)
{

this.sortColumn = sortColumn;

this.sortingOrder = sortingOrder;

}

#endregion

#region public property

///
/// Column Name(public property of the class) to be sorted.
///

public string SortColumn
{
get { return sortColumn; }
}

///
/// Sorting order.
///

public SortOrder SortingOrder
{
get { return sortingOrder; }
}

#endregion
#region public methods

///
/// Compare interface implementation
///

/// First Object
/// Second Object
/// Result of comparison
public int Compare(T x, T y)
{
PropertyInfo propertyInfo = typeof(T).GetProperty(sortColumn);
IComparable obj1 = (IComparable)propertyInfo.GetValue(x, null);
IComparable obj2 = (IComparable)propertyInfo.GetValue(y, null);
if (sortingOrder == SortOrder.Ascending)
{
return (obj1.CompareTo(obj2));
}
else
{
return (obj2.CompareTo(obj1));
}
}
#endregion
}

To Sort the gridview I have used the following gridview command

protected void dgrid_Sorting(object sender, GridViewSortEventArgs e)
{
if (ViewState["SortBy"] == null)
{
ViewState["SortBy"] = "DESC";
}

else if (ViewState["SortBy"].ToString().Equals("ASC"))
{
ViewState["SortBy"] = "DESC";
}
else
{
ViewState["SortBy"] = "ASC";
}

BindData(e.SortExpression);
}


Thanks for my colleague Poonam to help me for this.




Download:

Monday, April 20, 2009

Validation of XML with XSD in C#

This article explains about how to validate an XML document with XSD schema. The validation is performed by checking whether the XML document is a well-formed one by programmatically using .NET classes in C#.

Xml Document

xml version="1.0" encoding="utf-8" ?>

<Employees>

<Employee>

<FirstName>PankajFirstName>

<LastName>SahaLastName>

<Age>26Age>

<Address>

<City>BarodaCity>

<Country>IndiaCountry>

Address>

Employee>

<Employee>

<FirstName>AnimeshFirstName>

<LastName>SingLastName>

<Age>27Age>

<Address>

<City>BarodaCity>

<Country>IndiaCountry>

Address>

Employee>

Employees >


Here I have created two xsd file, one is valid or another is invalid.

You can create the xsd file from a xml file with the visual studio.

  1. Open the xml file in the visual studio.
  2. Go to the xml menu
  3. click on Create Schema



Figure-1



Figure-2



To created invalid xsd I have removed one tag LastName after the FirstName tag in the valid xsd.

Valid XSD schema

xml version="1.0" encoding="utf-8"?>

<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:element name="Employees" >

<xs:complexType>

<xs:sequence maxOccurs ="unbounded" >

<xs:element maxOccurs="unbounded" name="Employee" >

<xs:complexType>

<xs:sequence>

<xs:element name="FirstName" type="xs:string" />

<xs:element name="LastName" type="xs:string" />

<xs:element name="Age" type="xs:unsignedByte" />

<xs:element name="Address">

<xs:complexType>

<xs:sequence>

<xs:element name="City" type="xs:string" />

<xs:element name="Country" type="xs:string" />

xs:sequence>

xs:complexType>

xs:element>

xs:sequence>

xs:complexType>

xs:element>

xs:sequence>

xs:complexType>

xs:element>

xs:schema>

Invalid XSD schema

xml version="1.0" encoding="utf-8"?>

<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:element name="Employees">

<xs:complexType>

<xs:sequence>

<xs:element maxOccurs="unbounded" name="Employee">

<xs:complexType>

<xs:sequence>

<xs:element name="FirstName" type="xs:string" />

<xs:element name="Age" type="xs:unsignedByte" />

<xs:element name="Address">

<xs:complexType>

<xs:sequence>

<xs:element name="City" type="xs:string" />

<xs:element name="Country" type="xs:string" />

xs:sequence>

xs:complexType>

xs:element>

xs:sequence>

xs:complexType>

xs:element>

xs:sequence>

xs:complexType>

xs:element>

xs:schema>

To check whether the xml is valid or not I have done the following steps:

1. Created class XmlValidator

2. The ValidationCallBack event is used to define an event handler for receiving the notification about XSD schema validation errors. If any validation error occurs, an exception is thrown, and the XmlValidatingReader cannot be restarted

Conclusion

This article explained about the XML document, XSD schema, and how to validate XML document against XSD schema using Microsoft .NET framework classes.


Download:




Sunday, April 19, 2009

Custom paging in asp.net with Jquery

Here I have created a custom grid with Jquery in Asp.net. When we use web control (datagrid, GridView etc.) in asp.net to show the information then it takes time as the number of users increased. As well as if we have to go for the next page in the Gridview a postback happened and it increase the load on the server. I have used here a Jquery Ajax method to fetch and save the data without postback.



Steps:
  1. Here I have used Link To SQL for the datalayer. I have created the procedures to insertUser (to insert the new user) , GetTotalUserCount (get the total number of users) and GetAllUsers (to fetch all the users).
  2. Created a class user in the datalayer to fetch the users by pageSize, pageNo and SortColumn.
  3. Created a BusinessLayer.
  4. Created JSONHelper.JSON and added the reference to the BusinessLayer. JSONHelper.JSON is used to convert the object to the Json string.
  5. Included the jquery-1.3.2.min.js in the default.aspx page. No need to write any server site code. You can also use any .html page instead of .aspx page.
  6. Include CustomeUserGrid.js and Employee.js files where I fetch the data from the database and also save the new user information
  7. To save/fetch the data from the database with Jquery Ajax method I have created a DataPage.aspx.
  8. Restore the database EmployeeManagement.bak.
  9. Set the default.aspx page Set as start page.
Technolgoes: asp.net 3.5, Linq to SQL, Jquery

Written By: Pankaj Saha

Download:




Thanks my friend Animesh Singh to help me out for this blog.