Adsence750x90

Wednesday, April 28, 2010

Dynamic DataTable ASP.Net

This Article for How to Create a DataTable Dynamically.

DataTable is Derived from System.Data namespace


//Create a object of Datatable
        DataTable dynamicTable = new DataTable();

        //DataRow
        DataRow dynamicRow;
        //DataColumn for Name and Time
        DataColumn NameColumn = new DataColumn("Name", typeof(string));
        DataColumn TimeColumn = new DataColumn("Time", typeof(string));

        //add Column to Datatable
        dynamicTable.Columns.Add(NameColumn);
        dynamicTable.Columns.Add(TimeColumn);
        //loop for 10 item in DataTable
        for (int i = 0; i < 10; i++)
        {
            dynamicRow = dynamicTable.NewRow();
            //Add Rows to dymanicTable
            dynamicTable.Rows.Add(dynamicRow);
            //Assign Column value
            dynamicTable.Rows[i][NameColumn] = Guid.NewGuid().ToString();
            dynamicTable.Rows[i][TimeColumn] = DateTime.Now.ToString();
        }

        //Bind DynamicTable into a GridView
        GridView1.DataSource = dynamicTable;
        GridView1.DataBind();

Monday, April 26, 2010

Read E Mails from ASP.NET

Read Mails from ASP.NET

This article Illustrate How to read mails from ASP.Net. Using POP commands you can access you email inbox from ASP.Net. Basic POP commands are USER, PASS, LIST, QUIT, RETR.
More details POP command help you can check these links


http://www.nthelp.com/pop_commands.htm
http://www.faqs.org/rfcs/rfc1939


         //Creating Object for POPHelper
        //Parameters are Gmail,Yahoo or MSN Pop Server,
        //Port number
        //bool isSSL
        POPHelper objPopHelper = new POPHelper("pop.gmail.com", 995, true);
        objPopHelper.UserName = "Your Gmail Username eg:youremail@gmail.com";
        objPopHelper.Password = "GmailPassword";
        objPopHelper.Connect();
        GridView1.DataSource = p.DataSource;
        GridView1.DataBind();


Code Of Connect Method 

public void Connect()
        {
            string response = string.Empty;
            ArrayList arrList = new ArrayList();
            try
            {
                //Connect to Host server
                #region Connect Host
                TcpClient _tcpClient = new TcpClient();
                try
                {
                    _tcpClient.Connect(_hostname, _port);
                    //if login is ssl
                    if (_isSsl)
                    {
                        _stream = new SslStream(_tcpClient.GetStream());
                        ((SslStream)_stream).AuthenticateAsClient(_hostname);
                    }
                    else
                    {
                        _stream = _tcpClient.GetStream();
                    }
                }
                catch (Exception ex)
                {
                    throw new POPCommandException("Connection to " + _hostname + " Port: " + _port + " failed. Error Details"+ex.Message);
                }
                #endregion
                // Send POP Commands (USER, PASS, LIST) to Host
                #region POP Commands
                _streamWriter = new StreamWriter(_stream, Encoding.ASCII);
                _streamReader = new StreamReader(_stream, Encoding.ASCII);

                //POP command for send Username
                _streamWriter.WriteLine(POPCommands.USER.ToString()+" "+ UserName);
                //send to server
                _streamWriter.Flush();

                //POP command for send  Password
                _streamWriter.WriteLine(POPCommands.PASS.ToString() + " " + Password);
                //send to server
                _streamWriter.Flush();

                //POP command for List mails
                _streamWriter.WriteLine(POPCommands.LIST.ToString());
                //send to server
                _streamWriter.Flush();
                #endregion
                //Read Response Stream from Host
                #region Read Response Srteam
                //Read Response Stream
                response = null;
                string resText = string.Empty;
                while ((resText = _streamReader.ReadLine()) != null)
                {
                    if (resText == ".")
                    { break; }
                    if (resText.IndexOf("-ERR") != -1)
                    { break; }
                    response += resText;
                    arrList.Add(resText);
                }
                #endregion
                //Binding Properties
                #region Bindings
                //Bind Message count
                BindMailCount(arrList);
                //mails returns List
                _mail = ReadMail(messagecount);
                //get  mails Subjects returns List
                _mailsub = FilterContent(_mail,FiltersOption.Subject);
                _from = FilterContent(_mail, FiltersOption.From);
                _to = FilterContent(_mail, FiltersOption.To);
                SetDataSource(_mailsub, _from);
                #endregion
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
            }
        }


Class Diagram of POPHelper

Reading Mails Using POP Command RETR from ASP.NET

private List ReadMail(int Count)
        {
            List lst = new List();
            try
            {
                for (int i = 1; i <= Count; i++)
                {
                    _streamWriter.WriteLine(POPCommands.RETR+" " + i.ToString());
                    _streamWriter.Flush();
                    string resText = string.Empty;
                    while ((resText = _streamReader.ReadLine()) != null)
                    {
                        if (resText == ".")
                        { break; }
                        if (resText.IndexOf("-ERR") != -1)
                        { break; }
                        lst.Add(resText);
                    }
                }
               
            }
            catch(Exception ex)
            {
                errors.Add(ex.Message);
            }
            return lst;
        }



Enumerates for Filer message subject and From Address and ToAddress 

Method for Filer Content


private List FilterContent(List Mails,FiltersOption filter)
        {
            List filterItems = new List();
            try
            {
                for (int i = 0; i < Mails.Count; i++)
                {
                    if (Mails[i].StartsWith(filter.ToString() + ":"))
                    {
                        string sub = Mails[i].Replace(filter.ToString() + ":", "");
                        filterItems.Add(sub);
                    }
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
            }
            return filterItems;
        }

Creating DataSource for GridView

private DataTable SetDataSource(Listsubject,Listsender)
        {
            int messageCount = messagecount;
            dataTab = new DataTable();
            DataRow drow;
            DataColumn Sender = new DataColumn("Sender", typeof(string));
            DataColumn Subject = new DataColumn("Subject", typeof(string));
            dataTab.Columns.Add(Sender);
            dataTab.Columns.Add(Subject);
            for (int i = 0; i < subject.Count; i++)
            {
                drow = dataTab.NewRow();
                dataTab.Rows.Add(drow);
                dataTab.Rows[i][Sender] = sender[i].ToString();
                dataTab.Rows[i][Subject] = subject[i].ToString();
            }
            return dataTab;
        }


Download SOURCE

Monday, April 19, 2010

Tracing ASP.NET

Tracing

ASP.NET tracing enable diagnostic information about requested asp.net page.
Tracing Help to follow

•    Page's execution path,
•    Display diagnostic information at run time
•    debug your application

Tracing appends diagnostic information and custom tracing messages to the output of the page and sends this information to the requesting browser. Optionally, you can view this information from a separate trace viewer (Trace.axd) that displays trace information for every page in an ASP.NET Web application. Tracing information can help you investigate errors or unwanted results while ASP.NET processes a page request.

Trace information can enable for single page and hole pages/ application level by configure the application's Web.config. Trace statements are processed and displayed only when tracing is enabled.

Code for Application Level tracing
in web.config file   

<configuration>
  <system.web>
<trace enabled="true" requestLimit="40" pageOutput="true"             localOnly="false" />
  </system.web>
</configuration>

Page level tracing

Add Trace="true" in @page Directives

Eg : <%@ Page Trace="true" %>

Trace Configuration Attributes

PageOutput -  true to display trace both in pages and in the trace viewer (Trace.axd); otherwise, false. The default is false.

requestLimit - The number of trace requests to store on the server. The default is 10.

localOnly - true to make the trace viewer (Trace.axd) available only on the host Web server; otherwise, false. The default is true.

When tracing is enabled for a page, trace information is displayed in any browser requests that page. Tracing displays sensitive information, such as the values of server variables, and can therefore represent a security threat. Be sure to disable page tracing before porting your application to a production server. You can do this by setting the Trace attribute to false or by removing it. You can also configure tracing in the Web.config file by setting the enabled, localOnly, and pageOutput attributes of the trace Element

Source  from MSDN

Friday, April 16, 2010

Control State - ASP.NET State Management

State management is the process by which you maintain state and page information over multiple requests for the same or different pages.
Control state is an object comprised of critical view state data that Web server controls need to function, and is contained in a separate object from normal view state information. Control state data is not affected when view state is disabled at the Page level, but requires extra implementation steps to use.

More Reference for ASP.NET State Management Check this  

Monday, April 12, 2010

Encrypt and Decrypt String ASP.NET

You can Encrypt and Decrypt string  variable like QueryString etc by FormsAuthentication class. This class is Derived from System.Web.Security. This is a simple method to encryption and decryption. I think the code will definitely explain how it works. if anyone want detailed description just drop a comment i will reply ASAP.

First Initializes a new instance of  FormsAuthenticationTicket class, this ticket is used to encrypt via FormsAuthentication.Encrypt(FormsAuthenticationTicket tk) method. FormsAuthentication.Encrypt method return encrypted string.


FormsAuthenticationTicket has three parameters.parameters are  string name, bool isPersistent, and int timeout.The time, in minutes, for which the authentication ticket is valid. if isPersistent is true if the ticket will be stored in a persistent cookie (saved across browser sessions); otherwise, false. If the ticket is stored in the URL, this value is ignored.

Encrypt Method 

    private string Encrypt(string stringToEncrypt)
    {
        FormsAuthenticationTicket tk = new FormsAuthenticationTicket(stringToEncrypt, false, 600);
        // returns encrypted string
        return FormsAuthentication.Encrypt(tk);
    }

Decrypt Method

    private string Decrypt(string encryptedString)
    {
        FormsAuthenticationTicket tk= FormsAuthentication.Decrypt(encryptedString);
        return tk.Name;
    }

Friday, April 9, 2010

QueryString - Passing variable Between Pages ASP.Net

QueryString is user for passing variable in between pages. for example you need to pass ones first name and last name from one page to another page, you can use QueryString. you can collect first name from page one and send that information via query string.

Example of a QueryString is search.aspx?fname=john&lname=thomas

 "?" starts the QueryString and "&" is used to add more variables
Advantages of QueryString is its very easy to use but it have limitations you cant sent large information via QueryString, QueryString have max length. you cant send [&] and [space]  via QueryString. do not send secure information like username and password via QueryString.

Example for Send QueryString

// taking First Name and Last Name in two Variables
string firstName=txtFirstName.Text;
string lastName=txtLastName.Text;

// format QueryString using string format
string qStringVaribales = string.Format("fname={0}&lname={1}", firstName, lastName);

// alternate method
string qStringVaribales="?fname="+firstName+"&lname="+lastName;

// Redirect QueryString to second page
Response.Redirect("search.aspx" + qStringVaribales);

Receive QueryString 

// Checking QstringString is null or empty
 // assigning QueryString in Variables

        if (Request.QueryString["fname"] != null && Request.QueryString["fname"] != "")
        {
            string firstName = Request.QueryString["fname"];
        }
        if (Request.QueryString["lname"] != null && Request.QueryString["lname"] != "")
        {
            string lastName = Request.QueryString["lname"];
        }

Get Client IP Address ASP.NET

How to get IP Host Address of remote Client

 // To get IP of the client meachine
        // There is two methods to obtain IP address
       
        // Method 1
        //     Gets the IP host address of the remote client.
        // Returns:
        //     The IP address of the remote client.
        string ipMethod1 = Request.UserHostAddress; // HttpContext.Current.Request.UserHostAddress;

        //Methord 2
        //Request.ServerVariables is a Name Value Collection
        //     Gets a collection of Web server variables.
        // Returns:
        //     A System.Collections.Specialized.NameValueCollection of server variables.
        string ipMethod2 = Request.ServerVariables["REMOTE_ADDR"]; //HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
        Response.Write(ipAdddress);