Sunday 29 September 2013

ASP.Net Page Life Cycle Events:



At each stage of the page life cycle, the page raises some events, which could be coded. An event handler is basically a function or subroutine, bound to the event, using declarative attributes like Onclick or handle.

Following are the page life cycle events:


PreInit . PreInit is the first event in page life cycle. It checks the IsPostBack property and determines whether the page is a postback. It sets the themes and master pages, creates dynamic controls and gets and sets profile property values. This event can be handled by overloading the OnPreInit method or creating a Page_PreInit handler.


Init . Init event initializes the control property and the control tree is built. This event can be handled by overloading the OnInit method or creating a Page_Init handler.


InitComplete . InitComplete event allows tracking of view state. All the controls turn on view-state tracking.


LoadViewState . LoadViewState event allows loading view state information into the controls.


LoadPostData . during this phase, the contents of all the input fields defined with the <form> tag are processed.


PreLoad . PreLoad occurs before the post back data is loaded in the controls. This event can be handled by overloading the OnPreLoad method or creating a Page_PreLoad handler.


Load . the Load event is raised for the page first and then recursively for all child controls. The controls in the control tree are created. This event can be handled by overloading the OnLoad method or creating a Page_Load handler.


LoadComplete . the loading process is completed, control event handlers are run and page validation takes place. This event can be handled by overloading the OnLoadComplete method or creating a Page_LoadComplete handler.


PreRender . the PreRender event occurs just before the output is rendered. By handling this event, pages and controls can perform any updates before the output is rendered.


PreRenderComplete . as the PreRender event is recursively fired for all child controls, this event ensures the completion of the pre-rendering phase.


SaveStateComplete . state of control on the page is saved. Personalization, control state and view state information is saved. The HTML markup is generated. This stage can be handled by overriding the Render method or creating a Page_Render handler.


UnLoad . the UnLoad phase is the last phase of the page life cycle. It raises the UnLoad event for all controls recursively and lastly for the page itself. Final cleanup is done and all resources and references, such as database connections, are freed. This event can be handled by modifying the OnUnLoad method or creating a Page_UnLoad handler.

ASP.Net Page Life Cycle



When a page is requested, it is loaded into the server memory, processed and sent to the browser. Then it is unloaded from the memory. At each of this steps, methods and events are available, which could be overridden according to the need of the application. In other words, you can write your own code to override the default code.

The Page class creates a hierarchical tree of all the controls on the page. All the components on the page, except the directives are part of this control tree. You can see the control tree by adding trace= "true" to the Page directive. We will cover page directives and tracing under 'directives' and 'error handling'.

The page life cycle phases are:


Initialization


Instantiation of the controls on the page


Restoration and maintenance of the state


Execution of the event handler codes


Page rendering


Understanding the page cycle helps in writing codes for making some specific thing happen at any stage of the page life cycle. It also helps in writing custom controls and initializing them at right time, populate their properties with view-state data and run control behavior code.

Following are the different stages of an ASP.Net page:


Page request . when ASP.Net gets a page request, it decides whether to parse and compile the page or there would be a cached version of the page; accordingly the response is sent


Starting of page life cycle . at this stage, the Request and Response objects are set. If the request is an old request or post back, the IsPostBack property of the page is set to true. The UICulture property of the page is also set.


Page initialization . at this stage, the controls on the page are assigned unique ID by setting the UniqueID property and themes are applied. For a new request postback data is loaded and the control properties are restored to the view-state values.


Page load . at this stage, control properties are set using the view state and control state values.


Validation . Validate method of the validation control is called and if it runs successfully, the IsValid property of the page is set to true.


Postback event handling . if the request is a postback (old request), the related event handler is called.


Page rendering . at this stage, view state for the page and all controls are saved. The page calls the Render method for each control and the output of rendering is written to the OutputStream class of the Page's Response property.


Unload . the rendered page is sent to the client and page properties, such as Response and Request are unloaded and all cleanup done.

Saturday 28 September 2013

Differance between Web Application and Web site creation in Asp.Net

Area
Web application projects
Web site projects
Project file structure
A Visual Studio project file (.csproj or .vbproj) stores information about the project, such as the list of files that are included in the project, and any project-to-project references.
There is no project file (.csproj or .vbproj). All the files in a folder structure are automatically included in the site.
Compilation
·    You explicitly compile the source code on the computer that is used for development or source control.
·    By default, compilation of code files (excluding .aspx and .ascx files) produces a single assembly.
·    The source code is typically compiled dynamically (automatically) by ASP.NET on the server the first time a request is received after the site has been installed or updated.
You can precompile the site (compile in advance on a development computer or on the server).
·    By default, compilation produces multiple assemblies.
Namespaces
Explicit namespaces are added to pages, controls, and classes by default.
Explicit namespaces are not added to pages, controls, and classes by default, but you can add them manually.
Deployment
·    You copy the assembly to a server. The assembly is produced by compiling the application.
·    Visual Studio provides tools that integrate with Web Deploy (the IIS web deployment tool) to automate many deployment tasks.
·    You copy the application source files to a computer that has IIS installed on it.
·    If you precompile the site on a development computer, you copy the assemblies produced by compilation to the IIS server.
·    Visual Studio provides tools that integrate with Web Deploy (the IIS web deployment tool) to automate many deployment tasks.

Refine Hours and Min from user give value

Hi All,

Today I am going to give a method by the help of which you can get hours and mins as integer if user willl give in different formate like, (1 hr 10 min or 1hr or 1:10 hour...)



public void getEventHourAndMinuteValues(string eventDuration, out int hour, out int minutes)
        {
            hour = 0;
            minutes = 0;

            try
            {
                if (eventDuration != string.Empty)
                {
                label1:
                    string[] duration = eventDuration.Split(new char[] { ':','.' });
                    if (IsValidTime(eventDuration))
                    {
                        if (duration.Length > 1)
                        {
                            hour = Convert.ToInt32(duration[0]);
                            minutes = Convert.ToInt32(duration[1]);
                        }
                        else
                        {
                            hour = Convert.ToInt32(duration[0]);
                        }
                    }
                    else
                    {
                        string pattern = @"(hour|HRs|hr|hrs|hr's|HOUR|HR)";
                        string minPattern = @"(minutes|mins|min's|Minutes|MINUTES)";
                        if (duration.Length > 1)
                        {
                            duration[0] = Regex.Replace(duration[0], @"\s+", string.Empty); //removing whitespace
                            duration[1] = Regex.Replace(duration[1], @"\s+", string.Empty);
                            hour = Convert.ToInt32(Regex.Replace(duration[0], pattern, string.Empty));
                            minutes = Convert.ToInt32(Regex.Replace(duration[1], minPattern, string.Empty));
                        }
                        else
                        {
                            //duration[0] = Regex.Replace(duration[0], @"\s+", string.Empty); //removing whitespace
                            try
                            {
                                hour = Convert.ToInt32(Regex.Replace(duration[0], pattern, string.Empty));
                            }
                            catch
                            {
                                hour = 1;
                                //eventDuration = Regex.Replace(duration[0], pattern, ":");
                                //eventDuration = Regex.Replace(eventDuration, minPattern, string.Empty);
                                //eventDuration = Regex.Replace(eventDuration, @"\s+", string.Empty); //removing whitespace
                                ////goto label1;
                            }
                        }

                    }
                }
                else
                {
                    hour = 1;
                }

            }
            catch (Exception ex)
            {
                hour = 1;
            }

        } 

Friday 27 September 2013

Check Valid Time Method

public bool IsValidTime(string thetime)
        {
            Regex checktime = new Regex(@"^(20|21|22|23|[01]d|d)(([:][0-5]d){1,2})$");
            return checktime.IsMatch(thetime);
        }

Creating DataTable for C# Code :


public static DataTable getAllProduct()
        {          
            DataTable table = new DataTable();
            DataColumn col1 = new DataColumn("Id");
            DataColumn col2 = new DataColumn("Title");
            DataColumn col3 = new DataColumn("Entitlement");
            DataColumn col4 = new DataColumn("CreatedDate");
            DataColumn col5 = new DataColumn("PublishedDate");
            DataColumn col6 = new DataColumn("ProductType");

            col1.DataType = System.Type.GetType("System.String");
            col2.DataType = System.Type.GetType("System.String");
            col3.DataType = System.Type.GetType("System.String");
            col4.DataType = System.Type.GetType("System.DateTime");
            col5.DataType = System.Type.GetType("System.DateTime");
            col6.DataType = System.Type.GetType("System.String");

            table.Columns.Add(col1);
            table.Columns.Add(col2);
            table.Columns.Add(col3);
            table.Columns.Add(col4);
            table.Columns.Add(col5);
            table.Columns.Add(col6);

            //For Each Subscription Product Purchased
            for (int x = 0; x < listOrders.Rows.Count; x++)
            {
                DataTable gt = getProductsBySubscription(CustomerID);
                //For Each Subscription Product
                for (int y = 0; y < gt.Rows.Count; y++)
                {
                    DataRow row = table.NewRow();
                    row[col1] = gt.Rows[y]["Id"].ToString();
                    row[col2] = gt.Rows[y]["Title"].ToString();
                    row[col3] =  gt.Rows[y]["Entitlement"].ToString();
                    row[col4] = gt.Rows[y]["CreatedDate"];
                    row[col5] = gt.Rows[y]["PublishedDate"];
                    row[col6] = gt.Rows[y]["ProductType"];
                    table.Rows.Add(row);
                }
            }
            DataTable distinctTable = table.DefaultView.ToTable( /*distinct*/ true);
            return distinctTable;
        }

Remove particular HTML Tag for a string

Hi Guy's,

Suppose we have a string like this :

<p>
<span>Learn to use Excel to identify what happened in the past,</span> so you can better prepare for the future. <bold>By using Excel as a trend analysis tool</bold>, CFOs, controllers and financial analysts will be able to use the data from budgets and financial statements to work through the planning and forecasting process.
</p>.

And we want to remove <bold> Tag from the above string then what to Do ?

We can use Below method to archive this :

     public static string removeSingleTagFromText(string text, string tagName)
        {
            string x = "<" + tagName + @"\b[^>]*>(.*?)</" + tagName + ">";
            Regex m = new Regex(@"<p\b[^>]*>(.*?)</p>", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            return m.Replace(text, "");
        }

Remove all un-necessary HTML Tag

Hi All,

This Function will remove all un- necessary HTML Tag from the string which you will pass as a parameter to this function :

  public static string removeAllHTMLTags(string text)
        {
            Regex m = new Regex(@"<(.|\\n)*?>", RegexOptions.IgnoreCase); 
            string newString = m.Replace(text, "");
            return newString;
        }

Method for Encryption and Decryption.

Hello All,

By the help of below method you can encrypt and  decrypt URL or any value.


public static Byte[] m_Key = new Byte[8];
 public static Byte[] m_IV = new Byte[8];

  //Function to encrypt data

        public static string EncryptData(String strKey, String strData)
        {
            string strResult; //Return Result

            //1. String Length cannot exceed 90Kb. Otherwise, buffer will overflow. See point 3 for reasons
            if (strData.Length > 92160)
            {
                strResult = "Error. Data String too large. Keep within 90Kb.";
                return strResult;
            }

            //2. Generate the Keys
            if (!InitKey(strKey))
            {
                strResult = "Error. Fail to generate key for encryption";
                return strResult;
            }

            //3. Prepare the String
            // The first 5 character of the string is formatted to store the actual length of the data.
            // This is the simplest way to remember to original length of the data, without resorting to complicated computations.
            // If anyone figure a good way to 'remember' the original length to facilite the decryption without having to use additional function parameters, pls let me know.
            strData = String.Format("{0,5:00000}" + strData, strData.Length);


            //4. Encrypt the Data
            byte[] rbData = new byte[strData.Length];
            ASCIIEncoding aEnc = new ASCIIEncoding();
            aEnc.GetBytes(strData, 0, strData.Length, rbData, 0);

            DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();

            ICryptoTransform desEncrypt = descsp.CreateEncryptor(m_Key, m_IV);


            //5. Perpare the streams:
            // mOut is the output stream.
            // mStream is the input stream.
            // cs is the transformation stream.
            MemoryStream mStream = new MemoryStream(rbData);
            CryptoStream cs = new CryptoStream(mStream, desEncrypt, CryptoStreamMode.Read);
            MemoryStream mOut = new MemoryStream();

            //6. Start performing the encryption
            int bytesRead;
            byte[] output = new byte[1024];
            do
            {
                bytesRead = cs.Read(output, 0, 1024);
                if (bytesRead != 0)
                    mOut.Write(output, 0, bytesRead);
            } while (bytesRead > 0);

            //7. Returns the encrypted result after it is base64 encoded
            // In this case, the actual result is converted to base64 so that it can be transported over the HTTP protocol without deformation.
            if (mOut.Length == 0)
                strResult = "";
            else
                strResult = Convert.ToBase64String(mOut.GetBuffer(), 0, (int)mOut.Length);

            return strResult;
        }

------------------------------------------------------------------------------------------------------------
 //Function to decrypt data
        public static string DecryptData(String strKey, String strData)
        {
            string strResult;

            //1. Generate the Key used for decrypting
            if (!InitKey(strKey))
            {
                strResult = "Error. Fail to generate key for decryption";
                return strResult;
            }

            //2. Initialize the service provider
            int nReturn = 0;
            DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();
            ICryptoTransform desDecrypt = descsp.CreateDecryptor(m_Key, m_IV);

            //3. Prepare the streams:
            // mOut is the output stream.
            // cs is the transformation stream.
            MemoryStream mOut = new MemoryStream();
            CryptoStream cs = new CryptoStream(mOut, desDecrypt, CryptoStreamMode.Write);

            //4. Remember to revert the base64 encoding into a byte array to restore the original encrypted data stream
            byte[] bPlain = new byte[strData.Length];
            try
            {
                bPlain = Convert.FromBase64CharArray(strData.ToCharArray(), 0, strData.Length);
            }
            catch (Exception ex)
            {
                strResult = "Error. Input Data is not base64 encoded.";
                return strResult;
            }

            long lRead = 0;
            long lTotal = strData.Length;

            try
            {
                //5. Perform the actual decryption
                while (lTotal >= lRead)
                {
                    cs.Write(bPlain, 0, (int)bPlain.Length);
                    //descsp.BlockSize=64
                    lRead = mOut.Length + Convert.ToUInt32(((bPlain.Length / descsp.BlockSize) * descsp.BlockSize));
                };

                ASCIIEncoding aEnc = new ASCIIEncoding();
                strResult = aEnc.GetString(mOut.GetBuffer(), 0, (int)mOut.Length);

                //6. Trim the string to return only the meaningful data
                // Remember that in the encrypt function, the first 5 character holds the length of the actual data
                // This is the simplest way to remember to original length of the data, without resorting to complicated computations.
                String strLen = strResult.Substring(0, 5);
                strResult = strResult.Replace(strLen, "");
                //int nLen = Convert.ToInt32(strLen);
                //strResult = strResult.Substring(5, nLen);
                //nReturn = (int)mOut.Length;

                return strResult;
            }
            catch (Exception ex)
            {
                strResult = "Error. Decryption Failed. Possibly due to incorrect Key or corrputed data";
                return strResult;
            }
        }

------------------------------------------------------------------------------------------------------------

//Private function to generate the keys into member variables
        static private bool InitKey(String strKey)
        {
            try
            {
                // Convert Key to byte array
                byte[] bp = new byte[strKey.Length];
                ASCIIEncoding aEnc = new ASCIIEncoding();
                aEnc.GetBytes(strKey, 0, strKey.Length, bp, 0);
             

                //Hash the key using SHA1
                SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider();
                byte[] bpHash = sha.ComputeHash(bp);

                int i;
                // use the low 64-bits for the key value
                for (i = 0; i < 8; i++)
                    m_Key[i] = bpHash[i];

                for (i = 8; i < 16; i++)
                    m_IV[i - 8] = bpHash[i];

                return true;
            }
            catch (Exception ex)
            {
                //Error Performing Operations
                return false;
            }
        }

Wednesday 25 September 2013

Asp.Net Page Life Cycle Events



      Following are the page life cycle events:
  1. PreInit . PreInit is the first event in page life cycle. It checks the IsPostBack property and determines whether the page is a postback. It sets the themes and master pages, creates dynamic controls and gets and sets profile property values. This event can be handled by overloading the OnPreInit method or creating a Page_PreInit handler.

  2. Init . Init event initializes the control property and the control tree is built. This event can be handled by overloading the OnInit method or creating a Page_Init handler.

  3. InitComplete . InitComplete event allows tracking of view state. All the controls turn on view-state tracking.

  4. LoadViewState . LoadViewState event allows loading view state information into the controls.

  5. LoadPostData . during this phase, the contents of all the input fields defined with the <form> tag are processed.

  6. PreLoad . PreLoad occurs before the post back data is loaded in the controls. This event can be handled by overloading the OnPreLoad method or creating a Page_PreLoad handler.

  7. Load . the Load event is raised for the page first and then recursively for all child controls. The controls in the control tree are created. This event can be handled by overloading the OnLoad method or creating a Page_Load handler.

  8. LoadComplete . the loading process is completed, control event handlers are run and page validation takes place. This event can be handled by overloading the OnLoadComplete method or creating a Page_LoadComplete handler.

  9. PreRender . the PreRender event occurs just before the output is rendered. By handling this event, pages and controls can perform any updates before the output is rendered.

  10. PreRenderComplete . as the PreRender event is recursively fired for all child controls, this event ensures the completion of the pre-rendering phase.

  11. SaveStateComplete . state of control on the page is saved. Personalization, control state and view state information is saved. The HTML markup is generated. This stage can be handled by overriding the Render method or creating a Page_Render handler.

  12. UnLoad . the UnLoad phase is the last phase of the page life cycle. It raises the UnLoad event for all controls recursively and lastly for the page itself. Final cleanup is done and all resources and references, such as database connections, are freed. This event can be handled by modifying the OnUnLoad method or creating a Page_UnLoad handler.