Friday, November 13, 2009

Using Form Authentication In ASP.NET

This article is focused on using forms authentication. It uses cookies to allow applications to track users throughout their visit. First of all, to enable form authentication edit your Web.Config file

Edit your <authentication> part in Web.Config as following:

        <authentication mode="Forms">
            <forms cookieless="UseCookies" loginUrl="Login.aspx" defaultUrl="Home.aspx">
            </forms>
        </authentication>



Login Page : Login.aspx

       <asp:TextBox ID="UserId" runat="server"></asp:TextBox>
       <br/>
       <asp:TextBox ID="Password" runat="server" TextMode="Password"></asp:TextBox>
       <br/>
       <asp:CheckBox ID="Persist" runat="server" Text="Remember Me" />
       <br/>         
       <asp:Button ID="Login" runat="server" onclick="Login_Click" Text="Login" />



In Login.aspx.cs, after successful verification of login credential use the following code to redirect from login page

         using System.Web.Security;

         FormsAuthentication.RedirectFromLoginPage(Login_TextBox_UsedId.Text, Persist.Checked);

Here Persist.Checked is used in regards to Remember Me textbox.



To restrict users from accessing any page without login, use the following code in Page_Load event:

            using System.Web.Security;

            if (User.Identity.IsAuthenticated == false)
                FormsAuthentication.RedirectToLoginPage();



For Signing out, use the follwing code in your logout page:

        using System.Web.Security;

        protected void Page_Load(object sender, EventArgs e)
        {
            FormsAuthentication.SignOut();
            Response.Redirect("Home.aspx");
        }



If you want that your previous page to expire after successfull SignOut then use the following code with FormsAuthentication.SignOut(); in logout page

        using System.Web.Security;

        protected void Page_Load(object sender, EventArgs e)
        {
            FormsAuthentication.SignOut();
            Response.Cache.SetCacheability(HttpCacheability.Public);
            Response.Redirect("Home.aspx");
        }

Friday, November 6, 2009

Encryption & Decryption Using Rijndael Algorithm.

Below, I have written all the necessary code to encrypt and decrypt text using Rijndael algorithm. Comments are also placed in between to better understand this code. In the end of this article I have also shown an example explaining the use of this algorithm.

using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace Security
{
    public sealed class CryptoCore : IDisposable
    {
        private static readonly byte[] Key = {
                                                0xda, 0x3c, 0x35, 0x6f, 0xbd, 0xd, 0x87, 0xf0,
                                                0x9a, 0x7, 0x6d, 0xab, 0x7e, 0x82, 0x36, 0xa,
                                                0x1a, 0x5a, 0x77, 0xfe, 0x74, 0xf3, 0x7f, 0xa8,
                                                0xaa, 0x4, 0x11, 0x46, 0x6b, 0x2d, 0x48, 0xa1
                                            };

        private static readonly byte[] IV =  {
                                                0x6d, 0x2d, 0xf5, 0x34, 0xc7, 0x60, 0xc5, 0x33,
                                                0xe2, 0xa3, 0xd7, 0xc3, 0xf3, 0x39, 0xf2, 0x16
                                            };
        /// <summary>
        /// Abstract object
        /// </summary>
        protected SymmetricAlgorithm algorithm;

        /// <summary>
        /// Default constructor
        /// </summary>
        public CryptoCore()
        {
            this.algorithm = new RijndaelManaged();
            this.algorithm.Mode = CipherMode.CBC;
            this.algorithm.Key = Key;
            this.algorithm.IV = IV;          
        }

        /// <summary>
        /// Release all resources used by the SymmetricAlgorithm class
        /// </summary>
        public void Dispose()
        {
            this.algorithm.Clear();
        }

        /// <summary>
        /// Set Binary Keys
        /// </summary>
        public void SetBinaryKeys(byte[] Key, byte[] IV)
        {
            this.algorithm.Key = Key;
            this.algorithm.IV = IV;
        }

        /// <summary>
        /// Extract Binary Keys
        /// </summary>
        public void ExtractBinaryKeys(out byte[] Key, out byte[] IV)
        {
            Key = this.algorithm.Key;
            IV = this.algorithm.IV;
        }

        /// <summary>
        /// Process the data with CryptoStream
        /// </summary>
        protected byte[] Process(byte[] data, int startIndex, int count, ICryptoTransform cryptor)
        {
            //
            // the memory stream granularity must match the block size
            // of the current cryptographic operation
            //
            int capacity = count;
            int mod = count % algorithm.BlockSize;
            if (mod > 0)
            {
                capacity += (algorithm.BlockSize - mod);
            }

            MemoryStream memoryStream = new MemoryStream(capacity);

            CryptoStream cryptoStream = new CryptoStream(
                memoryStream,
                cryptor,
                CryptoStreamMode.Write);

            cryptoStream.Write(data, startIndex, count);
            cryptoStream.FlushFinalBlock();

            cryptoStream.Close();
            cryptoStream = null;

            cryptor.Dispose();
            cryptor = null;

            return memoryStream.ToArray();
        }

        /// <summary>
        ///  Byte array encryption function
        /// </summary>
        /// <param name="cleanBuffer">input byte array</param>
        /// <returns>output encrypted byte array</returns>
        public byte[] EncryptBuffer(byte[] cleanBuffer)
        {
            byte[] output;

            // Encryptor object
            ICryptoTransform cryptoTransform = this.algorithm.CreateEncryptor();

            // Get the result
            output = this.Process(cleanBuffer, 0, cleanBuffer.Length, cryptoTransform);

            //clean
            cryptoTransform.Dispose();

            return output;
        }

        /// <summary>
        ///  Byte array decryption function
        /// </summary>
        /// <param name="cryptoBuffer">input chiper byte array</param>
        /// <returns>output decrypted byte array</returns>
        public byte[] DecryptBuffer(byte[] cryptoBuffer)
        {
            byte[] output;

            // Decryptor object
            ICryptoTransform cryptoTransform = this.algorithm.CreateDecryptor();

            // Get the result   
            output = this.Process(cryptoBuffer, 0, cryptoBuffer.Length, cryptoTransform);

            //clean
            cryptoTransform.Dispose();

            return output;
        }

        /// <summary>
        /// String encryption function
        /// </summary>
        /// <param name="plainText">clean text</param>
        /// <returns>base64 encrypted string</returns>
        public string EncryptString(string plainText)
        {
            return Convert.ToBase64String(EncryptBuffer(Encoding.UTF8.GetBytes(plainText)));
        }

        /// <summary>
        /// String decryption function
        /// </summary>
        /// <param name="encyptedText">base64 encrypted string</param>
        /// <returns>decrypted text</returns>
        public string DecryptString(string encyptedText)
        {
            return Encoding.UTF8.GetString(DecryptBuffer(Convert.FromBase64String(encyptedText)));
        }
    }
}

--------------------------- end of algorithm --------------------------


You can save the above code in a class file and then import the newly created class file wherever you want to use it. For example I have saved this code in a class file in a new project named 'Security'

Say I have to use encryption in my existing project 'abc', then I will add existing project 'Security' in project 'abc'. Then in References of project 'abc' I will add Security.dll file. Now we can use this algorithm in anywhere in project 'abc'. Following example shows encryption of a string in 'abc' project using Security.

using Security;


CryptoCore sec = new CryptoCore();
string password;
password = sec.EncryptString(TextBox1.Text);

// Here value stored in password variable will be a encrypted version of value in TextBox1.

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

I hope this article will help you in using Encryption and Decryption in your project. Please do not forget to post your comments...

State Management In ASP.NET

This post is for Beginner or Intermediate learner and is focused on various ways by which State Management is possible in ASP.NET . So lets begin with this concept...

The connection between the client and the server will be closed once the response is returned to the client. This is called as stateless nature of the web. As HTTP is a state less protocol, which cannot hold the values of the variables in between the request.
And when the web server maintains the information about the client, then it is called as state management concept.

Different methods used to maintain the state:
1.    Submission of data using post method.
2.    Cookies.
3.    Session Memory.
4.    Application Memory.
5.    Cache Data.


  • Submission of data
Http context is the memory area in which the instances of the classes will be executed. By getting the reference to this memory area. We can access the handler class instance.


  • Cookies
Cookie can be defined as small amount of memory used by the web server within client machine.
Basically cookies are used to maintain personal information of the client
The cookies can be classified in two types.
1.    Inmemory cookie
2.    Persistent cookie

When the cookie is stored within the process memory of the browser then it is called as Inmemory cookie.
Inmemory cookie is a temporary cookie because when the browser will be closed the data will be lost.
When the browser is storing cookie on to the hard disk memory, then it is called as persistent cookie.
It is provided with particular lifetime.

Creating a cookie:
Dim obj as new httpCookie ("name", value)
Obj.expires=#mm/dd/yyyy/hh:mm:ss#(requires incase of Persistent cookie)
Response.appendcookie (obj)this will write cookie information to the client machine

Reading the cookie:
Dim obj as httpcookie
Obj=request. Cookies ("name")it returns an object of httpcookie class, if the obj is nothing then cookie is not available.

Each request from the client will carry all the cookies information to web server.

The cookies will be stored into the hard disk memory of the client machine, with respect to network login folder.
(C:\document and settings\administrator (login folder)\cookies\administrator@localhost.txt)

The cookie information is maintained in the client machine, so it is called as client side state management.
It does not provide any security because it is available in the client machine. So the client can modify the value of the cookie as well as delete the text file.
A cookie can represent maximum of 4KB data.
A website can be used with maximum of 20 cookies because a browser can accommodate only 20 cookies towards single website.
A browser can accommodate maximum of 400 cookies with respect to different websites.


  • Session Memory
When the first request from the client goes to the web server, the web server will create a unique memory to the client on the server machine.
This session memory provides server side state management.
A cookie can represent only ordinary text, where as a session can represent ordinary text, arrays, objects etc.
The session will be maintained on the web server with the time out of 20 minutes (by default), but this can be changed as per the requirements.
Using session object we can access the session memory.
Session properties are,
1.    Session id
2.    Time out (To close session implicitly)
Session methods are,
1.    Add (varname, value)
2.    Remove (varname)
3.    Abandon (to close session explicitly)

When it comes to ASP 3.0, session variable can't be removed, i.e. erased until session is closed. When it comes to ASP.NET, session variable can be removed by using remove method.

Session Tracking
It is a concept of identifying the session by the web server belonging to a particular user.
When user sends the 2nd request to the server, the session ID will be carried with the request, so the server can trap the session memory assigned for the particular user.
The session id will be 120-bit number. (i.e. 15 bytes) in the hexadecimal format.


  • Application Memory
When the first client's first request comes to the web server towards a particular application, then web server will allocate memory for the application. This memory is called as application memory.
This memory will be common to all the users.
The application memory does not have timeout, this will be maintained till the web server is active. (i.e. executing)
E.g. At the time of chatting we require a common field i.e. application memory not the session memory.

By using application object, we can access the application memory from the web page.
Like session, application objects are having some methods.
1.    Add (var, value)
2.    Remove (var)
3.    Lock ()
4.    Unlock ()

Each client request to the web server will start a new thread, when one thread is processing the data in the application memory before the processing is finished, if the time slice is completed the processor will go to next client request, if this thread is processing data in the application memory, then the result will not be proper. To avoid this it is advisable to allow only one thread at a time to work with application memory. This can be achieved through lock () and Unlock () methods.
This process is called as synchronization of threads.

SESSION EVENTS AND APPLICATION EVENTS
1.    Session OnStart ()
2.    Session OnEnd ()

When a session memory is created OnStart () event will be executed.
Before releasing the session memory OnEnd () event will be executed.

Application Events are,
1.    Application OnStart ()
2.    Application OnEnd ()
3.    Application BeginRequest ()
4.    Application EndRequest ()
   (Newly provided in ASP.NET)

When a request comes for a particular web page then begin request will be executed, then the particular requested page will be processed and then the end request will be executed.

GLOBAL.ASAX

Session and application events have to be placed within a special file called as global.asax.
a.    Global.asax file has to be stored within the root directory of the application.
b.    An application can have only one Global.asax file.


When the first client's first request comes to the asp.net runtime, i.e. web server towards a particular application, then it will create application memory and an instance of global class within global.asax file. This instance will be maintained through out the application for making calls to the session events and application events.

Tuesday, November 3, 2009

The "SendUsing" configuration value is invalid.



The "SendUsing" configuration value is invalid.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Runtime. InteropServices.COMException: The "SendUsing" configuration value is invalid.

 
This error is generally a SMTP configuration error. Many web hosts now have their servers "locked down" and require a username and password to send email from their servers so that no unauthenticated emails are sent to users e.g. spam mails. If you have code that uses "localhost" (the SMTP service running on the local machine) then this shouldn't be an issue... 

You need this three parameters for sending email via SMTP Authenticatin.
host:- mail.your_domain_name
Username:- XXX@your_domain_name
Password:- corresponding password


Following Codes demonstrates how to send an email with SMTP Authentication using ASP.NET 3.5

using System.Net.Mail


        MailMessage msgMail = new MailMessage();
        MailMessage myMessage = new MailMessage();
        myMessage.From = new MailAddress("sender's email");
        myMessage.To.Add("recipient's email");
        myMessage.Subject = "Subject";
        myMessage.IsBodyHtml = true;

        myMessage.Body = "Message Body";

        SmtpClient mySmtpClient = new SmtpClient();
        System.Net.NetworkCredential myCredential = new System.Net.NetworkCredential("
email", "password");
        mySmtpClient.Host = "your smtp host address";
        mySmtpClient.
UseDefaultCredentials = false;
        mySmtpClient.Credentials = myCredential;
        mySmtpClient.ServicePoint.
MaxIdleTime = 1;
        mySmtpClient.Send(myMessage);
        myMessage.Dispose();



Note : You can avoid mySmtpClient.ServicePoint.MaxIdleTime, as it is to force the SmtpClient to send mail immediately with the .Send method.
I hope that this post helped you in troubleshooting your error. Do not forget to post your response...

Sunday, November 1, 2009

A generic error occurred in GDI+

Today, while working with my project I encountered the following error in uploading files...


A generic error occurred in GDI+.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+




After analyzing the whole trace, I came to know that apparently it is just a regular permissions issue. I don't have the write permission on the server in which this web is running.
Then I simply asked my asked hosting provider(as I am working on remote server,i.e. on my hosting account) to give write permissions to me and then all worked absolutely fine.


How to enable write permission in localhost


If you are working on your localhost and you encountering the same problem then you can enable write permission by following the steps mentioned below.

As an administrator,
  • right click on virtual directory
  • click on properties 
  • navigate to security tab 
  • click on advance or edit
  • give appropriate permissions (modify, read, write)
  • click on Apply and exit (by clicking ok)
I hope this piece of information helped you in resolving your error. Don't forget to post your response...


 

.NET Recipes Copyright © 2009 Designed by SAER