Tuesday 30 October 2012

Sending GridView Data in Mail


Sending GridView Data in Mail

Today I will show to Send Gridview Data in mail... Its very simple.. Lets give it a try..

Prerequisites:

A Populated Gridview in your design part with code for populating it already present in the codebehind..

A Button named Send Mail which will send the gridview data using email..


Getting Started:

Include these namespaces in your code-behind:


using System.Net.Mail;

using System.Text;

using System.IO;


Then On Button Click Event:


    protected void SendMail_Click(object sender, ImageClickEventArgs e)

    {

        //Specify the Email Address of the Recepient

        string to = "abc@xyz.com";

        //Specify the Email Address of the Sender

        string From = "xyz@abc.com";

        //Insert the subject of the mail

        string subject = "GridView Data";

     

        //Specifies the content of the body

        string Body = "Dear sir ,<br> Plz Check d Attachment <br><br>";

        Body += GridViewToHtml(Gridview1);

        Body += "<br><br>Regards,<br>Vishal";

        bool send = send_mail(to, From, subject, Body);

        if (send == true)

        {

            string CloseWindow = "alert('Mail Sent Successfully!');";

            ClientScript.RegisterStartupScript(this.GetType(), "CloseWindow", CloseWindow, true);

        }

        else

        {

            string CloseWindow = "alert('Problem in Sending mail...try later!');";

            ClientScript.RegisterStartupScript(this.GetType(), "CloseWindow", CloseWindow, true);

        }

    }


I have used a couple of methods in above event handler.. You have to specify those methods in the codebehind:

Boolean Send Mail Method:


    public bool send_mail(string to, string from, string subject, string body)

    {

            MailMessage msg = new MailMessage(from, to);

            msg.Subject = subject;

            AlternateView view;

            SmtpClient client;

            StringBuilder msgText = new StringBuilder();

            msgText.Append(" <html><body><br></body></html> <br><br><br>  " + body);

            view = AlternateView.CreateAlternateViewFromString(msgText.ToString(), null, "text/html");

            msg.AlternateViews.Add(view);

            client = new SmtpClient();

            client.Host = "smtp.gmail.com";

            client.Port = 587;

            client.Credentials = new System.Net.NetworkCredential("xyz@abc.com", "Your_password");

            client.EnableSsl = true; //Gmail works on Server Secured Layer

            client.Send(msg);

            bool k = true;

            return k;

    }


Gridview To Html Method:


    private string GridViewToHtml(GridView gv)

    {

        StringBuilder sb = new StringBuilder();

        StringWriter sw = new StringWriter(sb);

        HtmlTextWriter hw = new HtmlTextWriter(sw);

        gv.RenderControl(hw);

        return sb.ToString();

    }

    public override void VerifyRenderingInServerForm(Control control)

    {

         //Confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time.

    }


Note(Important):

1> You have to preconfigure your gmail settings(POP and IMAP) in order to send and receive mail..

2>You have to preconfigure you web.config file for sending mail.. If you dont know google that..

3> Important

Sometime one can  encountered by this error  -:
RegisterForEventValidation can only be called during Render();

This means that either you have forgot to override VerifyRenderingInServerForm in code behind or EventValidation is true.
So the solution is set EventValidation to false and must override VerifyRenderingInServerForm method.

4> If Everything worked fyn you would be able to Send your Gridview via Mail...

:-)

Get Particular Value from a Dataset


Get Particular Value from a Dataset


We came across situations when we have to access a particular value from the Dataset.. There must be scenarios when we have to assign those values to a variable.. Here is a method to achieve this..

Working:

string title = ds.Tables[0].Rows[0]["Title"].ToString();

The above code actually assigns the value from the Dataset to variable..

Description:

DataSet dsUserDetails = FillUserDetails();
string username ="";
if (dsUserDetails != null && dsUserDetails.Tables[0].Rows.Count > 0)
{
         username = dsUserDetails.Tables[0].Rows[0]["username"].ToString();
       }

where the first square braket after the "Rows"  contains the integer value of the row from which the field must be retrieved and the second square bracket contains the Column Name of the Datatable.Thus the value is retrived from the datatable of a Dataset.
Dataset will have n-number of tables.
The value in the square Bracket after the Tables(eg dsUserDetails.Tables[0].Rows.Count) denote the table location of the dataset.We are checking if the dataset is not empty i.e null and if the first table records is greater than zero then fetch the cell value from the datatable of the dataset.


References:

http://stackoverflow.com/questions/7284575/getting-value-from-a-dataset-into-a-variable



 

Handling Browser Navigation Event


Handling Browser Navigation Event

This trick will help you to capture the browser navigation event.. You could then include your code snippets which will execute whenever this event is triggered..

Here is the code for that:


public delegate void WebBrowserNavigatingEventHandler(Object sender, WebBrowserNavigatingEventArgs e);

browser.Navigating += new System.Windows.Forms.WebBrowserNavigatingEventHandler(Browser_Navigating);

private void Browser_Navigating(Object sender, WebBrowserNavigatingEventArgs e)

{

    /** the broswer control is doing some navagatin! **/

}

Get the Description of File Types from Registry programmatically


Get the Description of File Types from Registry programmatically

 

The following Code Snippet will help you to get the information about a particular file extension directly from the registry. It can be used to provide the user about the nature of the file type..

Here is the code snippet for that:


/// <summary>

/// Goes through registry to get the file type description for each extension

/// </summary>

/// <param name="theExtension"></param>

/// <returns></returns>

private string GetFileTypeString(String theExtension)
{
    // HKEY_CLASSES_ROOT //

    RegistryKey root = Registry.ClassesRoot;
    // something like '.csproj'

    RegistryKey openValue = root.OpenSubKey(theExtension);
    try
    {
        if (openValue != null)
        {
            // This will get the name of a key - something like 'VisualStudio.csproj.8.0'

            String val = openValue.GetValue("").ToString();
            // So we go there to get the value //

            RegistryKey typeVal = root.OpenSubKey(val);
            // something like 'Visual C# Project file'

            return typeVal.GetValue("").ToString();

        }
        else
        {
            // Sometimes its unrecognized //

            return theExtension;
        }
    }
    //Sometimes the default key value is Null...no big deal

    catch (Exception)
    {
        return theExtension;
    }

} 

Find out the stored procedure which were created/modified in last N Days:


Find out the stored procedure which were created/modified in last N Days

 

Here are some Queries to find out the list of stored procedure that were created in last N days..

Stored Procedure that were created in last N days :

SELECT name
FROM sys.objects
WHERE type = 'P'
AND DATEDIFF(D,create_date, GETDATE()) < 7
order by create_date desc

SELECT name,create_date,modify_date
FROM sys.objects
WHERE type = 'P'
AND DATEDIFF(D,create_date, GETDATE()) < 7
order by create_date desc

Stored Procedure that were modified in last N days :

SELECT name
FROM sys.objects
WHERE type = 'P'
AND DATEDIFF(D,modify_date, GETDATE()) < 30
order by modify_date desc


SELECT name,create_date,modify_date
FROM sys.objects
WHERE type = 'P'
AND DATEDIFF(D,modify_date, GETDATE()) < 7
order by modify_date desc

Copy Directory and Sub Directory



Copy Directory and Sub Directory

Today I will discuss this a method to copy the entire directory along with associated sub directories if required..

Here is the code snippet to achieve this:


    /// <summary>

        /// Copys directory, including sub directories, if desired

        /// </summary>

        /// <param name="theSourcePath"></param>

        /// <param name="theDestPath"></param>

        /// <param name="copySubDirs"></param>

        private static void CopyDirectory(String theSourcePath, string theDestPath, bool copySubDirs)

        {

            var dir = new DirectoryInfo(theSourcePath);

            DirectoryInfo[] dirs = dir.GetDirectories();

            // If the source directory does not exist, throw an exception.

            if (!dir.Exists)

            {

                throw new DirectoryNotFoundException(

                    "Source directory does not exist or could not be found: "

                    + theSourcePath);

            }

            // If the destination directory does not exist, create it.

            if (!Directory.Exists(theDestPath))

            {

                Directory.CreateDirectory(theDestPath);

            }

            // Get the file contents of the directory to copy.

            FileInfo[] files = dir.GetFiles();

            foreach (FileInfo file in files)

            {

                // Create the path to the new copy of the file.

                string temppath = Path.Combine(theDestPath, file.Name);

                // Copy the file.

                file.CopyTo(temppath, false);

            }

            // If copySubDirs is true, copy the subdirectories.

            if (copySubDirs)

            {

                foreach (DirectoryInfo subdir in dirs)

                {

                    // Create the subdirectory.

                    string temppath = Path.Combine(theDestPath, subdir.Name);

                    // Copy the subdirectories.

                    CopyDirectory(subdir.FullName, temppath, true);

                }

            }

        } 

Remove Special Characters and Space From String Using Regex


Remove Special Characters and Space From String Using Regex

Hi I will be discussing now how to remove special characters and space from a given string.. In this project i will be using two multiline textboxes and a button to demonstrate the functionality:

Design Part:


    <div>
    <br />
    <br />
        <asp:TextBox ID="TextBox1" TextMode="MultiLine" runat="server" Height="200px" Width="300px"></asp:TextBox>
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" Text="Trim String" OnClick="Button1_Click" />
        <br />
        <br />
        <asp:TextBox ID="TextBox2" TextMode="MultiLine" runat="server" Height="200px" Width="300px"></asp:TextBox>
    </div>


Code Behind:

Include the Namespace-

using System.Text.RegularExpressions;

Then use the following codes:

    public static string RemoveSpecialCharacters(string str)
    {
        // Strips all special characters and spaces from a string.
        return Regex.Replace(str, "[^a-zA-Z0-9_.]+", "", RegexOptions.Compiled);
    }


    protected void Button1_Click(object sender, EventArgs e)
    {
        string str=TextBox1.Text;
        TextBox2.Text=RemoveSpecialCharacters(str);
    }


On Button Click you will get the trimmed string in the second textbox..

Hope It helps.. Vishal   

Checking If the Connection can be made to the Server or Not

Checking If the Connection can be made to the Server or Not

Hi all, Today I will give you a code snippet to find out if a connection can be made to server or not provided that if you know the Server Name and Port Number..

This can be useful in scenarios when you can switch to other server based upon the fact the connection to a particular server failed and still u want to keep ur website alive..

Here is the Code Snippet to achieve this:


public bool ConnectionExist(string Server, int Port)

        {

            {

                try

                {

                    TcpClient clnt = new TcpClient(Server, Port);

                    clnt.Close();

                    return true;

               }

                catch (System.Exception ex)

                {

                    return false;

                }

            }

        }

Monday 29 October 2012

Get Operating System Name, Service Pack and Architecture



Get Operating System Name, Service Pack and Architecture


Here is a method to get the operating system name, Service Pack and Architecture using WMI:


using System;
using System.Management;
using System.Text.RegularExpressions;
/// <summary>
/// Gets Operating System Name, Service Pack, and Architecture using WMI 

with the legacy methods as a fallback
/// </summary>
/// <returns>String containing the name of the operating system followed by

 its service pack (if any) and architecture</returns>
private string getOSInfo()
{
 ManagementObjectSearcher objMOS = new ManagementObjectSearcher 

("SELECT * FROM  Win32_OperatingSystem");

 //Variables to hold our return value
 string os = "";
 int OSArch = 0;

 try
 {
  foreach (ManagementObject objManagement in objMOS.Get())
  {
   // Get OS version from WMI - This also gives us the edition
   object osCaption = objManagement.GetPropertyValue("Caption");
   if (osCaption != null)
   {
    // Remove all non-alphanumeric characters so that only letters, 

numbers, and spaces are left.
    string osC = Regex.Replace(osCaption.ToString(),"[^A-Za-z0-9 ]","");
    //string osC = osCaption.ToString();
    // If the OS starts with "Microsoft," remove it.  We know that already
    if (osC.StartsWith("Microsoft"))
    {
     osC = osC.Substring(9);
    }
    // If the OS now starts with "Windows," again... useless.  Remove it.
    if (osC.Trim().StartsWith("Windows"))
    {
     osC = osC.Trim().Substring(7);
    }
    // Remove any remaining beginning or ending spaces.
    os = osC.Trim();
    // Only proceed if we actually have an OS version - service pack is 

useless without the OS version.
    if(!String.IsNullOrEmpty(os))
    {
     object osSP = null;
     try
     {
      // Get OS service pack from WMI
      osSP = objManagement.GetPropertyValue("ServicePackMajorVersion");
      if (osSP != null && osSP.ToString() != "0")
      {
       os += " Service Pack " + osSP.ToString();
      }
      else
      {
       // Service Pack not found.  Try built-in Environment class.
       os += getOSServicePackLegacy();
      }
     }
     catch (Exception)
     {
      // There was a problem getting the service pack from WMI.  

Try built-in Environment class.
      os += getOSServicePackLegacy();
     }
    }
    object osA = null;
    try
    {
     // Get OS architecture from WMI
     osA = objManagement.GetPropertyValue("OSArchitecture");
     if (osA != null)
     {
      string osAString = osA.ToString();
      // If "64" is anywhere in there, it's a 64-bit architectore.
      OSArch = (osAString.Contains("64") ? 64 : 32);
     }
    }
    catch (Exception)
    {
    }
   }
  }
 }
 catch (Exception)
 {
 }
 // If WMI couldn't tell us the OS, use our legacy method.
 // We won't get the exact OS edition, but something is better than nothing.
 if (os == "")
 {
  os = getOSLegacy();
 }
 // If WMI couldn't tell us the architecture, use our legacy method.
 if (OSArch == 0)
 {
  OSArch = getOSArchitectureLegacy();
 }
 return os + " " + OSArch.ToString() + "-bit";
}
/// <summary>
/// Gets Operating System Name using .Net's Environment class.
/// </summary>
/// <returns>String containing the name of the operating system followed

 by its service pack (if any)</returns>
private string getOSLegacy()
{
 //Get Operating system information.
 OperatingSystem os = Environment.OSVersion;
 //Get version information about the os.
 Version vs = os.Version;

 //Variable to hold our return value
 string operatingSystem = "";

 if (os.Platform == PlatformID.Win32Windows)
 {
  //This is a pre-NT version of Windows
  switch (vs.Minor)
  {
   case 0:
    operatingSystem = "95";
    break;
   case 10:
    if (vs.Revision.ToString() == "2222A")
     operatingSystem = "98SE";
    else
     operatingSystem = "98";
    break;
   case 90:
    operatingSystem = "Me";
    break;
   default:
    break;
  }
 }
 else if(os.Platform == PlatformID.Win32NT)
 {
  switch (vs.Major)
  {
   case 3:
    operatingSystem = "NT 3.51";
    break;
   case 4:
    operatingSystem = "NT 4.0";
    break;
   case 5:
    if (vs.Minor == 0)
    {
     operatingSystem = "2000";
    }
    else
    {
     operatingSystem = "XP";
    }
    break;
   case 6:
    if (vs.Minor == 0)
    {
     operatingSystem = "Vista";
    }
    else
    {
     operatingSystem = "7";
    }
    break;
   default:
    break;
  }
 }
 //Make sure we actually got something in our OS check
 //We don't want to just return " Service Pack 2"
 //That information is useless without the OS version.
 if(operatingSystem != "")
 {
  //Got something.  Let's see if there's a service pack installed.
  operatingSystem += getOSServicePackLegacy();
 }
 //Return the information we've gathered.
 return operatingSystem;
}
/// <summary>
/// Gets the installed Operating System Service Pack using .Net's Environment class.
/// </summary>
/// <returns>String containing the operating system's installed service pack (if any)</returns>
private string getOSServicePackLegacy()
{
 // Get service pack from Environment Class
 string sp = Environment.OSVersion.ServicePack;
 if (sp != null && sp.ToString() != "" && sp.ToString() != " ")
 {
  // If there's a service pack, return it with a space in front (for formatting)
  return " " + sp.ToString();
 }
 // No service pack.  Return an empty string
 return "";
}
/// <summary>
/// Gets Operating System Architecture.  This does not tell you if the program 
/// in running in 32- or 64-bit mode or if the CPU is 64-bit capable.  
/// It tells you whether the actual Operating System is 32- or 64-bit.
/// </summary>
/// <returns>Int containing 32 or 64 representing the number of bits 

///in the OS Architecture</returns>
private int getOSArchitectureLegacy()
{
 string pa = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");
 return ((String.IsNullOrEmpty(pa) || String.Compare(pa,0,"x86",0,3,true) 

 == 0) ? 32 : 64);
}


Reference:



Detecting Mobile Device in ASP.Net


Detecting Mobile Device in ASP.Net

Today I will be sharing a couple of method to detect the access of your Website by a Mobile Device..

Method 1:


In ASP.NET, you can easily detect the mobile device request using Request.Browser.IsMobileDevice property and Request.UserAgent.

The following code checks the IsMobileDevice property and redirects to the mobile specific page:


protected void Page_Load(object sender, EventArgs e)
{
    if (Request.Browser.IsMobileDevice)
    {
       Response.Redirect("~/default_mobile.aspx");          
    }
} 


If you request "default.aspx" from mobile browser, 
it will redirect to default_mobile.aspx page.
 
 

Method 2:

 
Use this isMobileBrowser() Method:
 

public static bool isMobileBrowser()
{
    //GETS THE CURRENT USER CONTEXT
    HttpContext context = HttpContext.Current;

    //FIRST TRY BUILT IN ASP.NT CHECK
    if (context.Request.Browser.IsMobileDevice)
    {
        return true;
    }
    //THEN TRY CHECKING FOR THE HTTP_X_WAP_PROFILE HEADER
    if (context.Request.ServerVariables["HTTP_X_WAP_PROFILE"] != null)
    {
        return true;
    }
    //THEN TRY CHECKING THAT HTTP_ACCEPT EXISTS AND CONTAINS WAP
    if (context.Request.ServerVariables["HTTP_ACCEPT"] != null && 
        context.Request.ServerVariables["HTTP_ACCEPT"].ToLower().Contains("wap"))
    {
        return true;
    }
    //AND FINALLY CHECK THE HTTP_USER_AGENT 
    //HEADER VARIABLE FOR ANY ONE OF THE FOLLOWING
    if (context.Request.ServerVariables["HTTP_USER_AGENT"] != null)
    {
        //Create a list of all mobile types
        string[] mobiles =
            new[]
                {
                    "midp", "j2me", "avant", "docomo", 
                    "novarra", "palmos", "palmsource", 
                    "240x320", "opwv", "chtml",
                    "pda", "windows ce", "mmp/", 
                    "blackberry", "mib/", "symbian", 
                    "wireless", "nokia", "hand", "mobi",
                    "phone", "cdm", "up.b", "audio", 
                    "SIE-", "SEC-", "samsung", "HTC", 
                    "mot-", "mitsu", "sagem", "sony"
                    , "alcatel", "lg", "eric", "vx", 
                    "NEC", "philips", "mmm", "xx", 
                    "panasonic", "sharp", "wap", "sch",
                    "rover", "pocket", "benq", "java", 
                    "pt", "pg", "vox", "amoi", 
                    "bird", "compal", "kg", "voda",
                    "sany", "kdd", "dbt", "sendo", 
                    "sgh", "gradi", "jb", "dddi", 
                    "moto", "iphone"
                };

        //Loop through each item in the list created above 
        //and check if the header contains that text
        foreach (string s in mobiles)
        {
            if (context.Request.ServerVariables["HTTP_USER_AGENT"].
                                                ToLower().Contains(s.ToLower()))
            {
                return true;
            }
        }
    }

    return false;
} 


Here are some Useful Links:

http://www.hand-interactive.com/resources/detect-mobile-aspnet.htm

http://our.umbraco.org/forum/templating/templates-and-document-types/18111-How-to-determine-Mobile-and-Tablet-and-sending-them-to-different-alt-templates-This-is-how-to

http://www.codeproject.com/Articles/213825/ASP-net-Mobile-device-detection

http://www.codeproject.com/Articles/34422/Detecting-a-mobile-browser-in-ASP-NET

How to Include Breakpoint programmatically in Try Catch Block in Codes

How to Include Breakpoint programmatically in Try Catch Block in Codes

This snippet shows how to force the running application to stops automatically when occurs an exception -exclusively when in debug mode.


            try
            {
               // your code to try
            }
            catch (Exception ex)
            {
               MessageBox.Show("Erro ao iniciar aplicativo: \n" + ex.Message + "\n" + ex.StackTrace);
                Console.WriteLine(DateTime.Now + " - Erro : " + ex.Message + "\nStackTrace:" +   ex.StackTrace);
               #if DEBUG
                System.Diagnostics.Debugger.Break();
               #endif
            } 

Get External Valid IP Address


Get External Valid IP Address

 

Here is a method to find out the external Valid IP address of your network/Connection:

In Design Part Include a label and Button:

    <div>
        <asp:Label ID="Label1" runat="server"></asp:Label>
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
    </div> 


Include these namespaces first:

using System.IO;
using System.Net;
using System.Text;  


Then include this method in your codebehind:

        public static string GetExternalIP(string Provider)

        {

            try

            {

                if ((Provider == null) || (Provider == ""))

                    Provider = "http://automation.whatismyip.com/n09230945.asp";

                HttpWebRequest WebReq = (HttpWebRequest)HttpWebRequest.Create(Provider);

                HttpWebResponse WebRes = (HttpWebResponse)WebReq.GetResponse();

                System.IO.Stream ResStream = WebRes.GetResponseStream();

                StreamReader ResStreamReader = new StreamReader(ResStream, Encoding.UTF8);

                string IP = ResStreamReader.ReadToEnd();

                ResStream.Close();

                WebRes.Close();

               return IP;

            }

            catch (Exception ex)

            {

                return "127.0.0.1";

                //throw;

            }

        }

Then On the button click Event:


    protected void Button1_Click(object sender, EventArgs e)

    {

        string IPinternet = GetExternalIP(null);

        Label1.Text=IPinternet;

    }


Saturday 27 October 2012

Remove Duplicate Records in a DataTable


Remove Duplicate Records in a DataTable 

The Merge method of DataTable class is convenient for combining two tables into one. However, the result table may contain duplicate data after the operation. We could write our own function to remove the duplicates, or, we could take advantage of a built-in method of DataView class.

There is this DataView method called ToTable with two parameters: (and a three-parameter overloaded version)
a boolean param distinct
If true, the returned System.Data.DataTable contains rows that have distinct values for all its columns. The default value is false.
a string array param columnNames
A string array that contains a list of the column names to be included in the returned System.Data.DataTable. The System.Data.DataTable contains the specified columns in the order they appear within this array.

We could first create a DataView object dv using the source table dt, then we turn dv into the destination "slim" DataTable dt through that ToTable method introduced above. The redundant data will be removed automatically.

Let's assume dt is the source DataTable object with duplicate records.

// create a dv from the source dt
DataView dv = new DataView(dt);
// set the output columns array of the destination dt
string[] strColumns = {"NodeID", "Title", "Url"};
// true = yes, i need distinct values.
dt = dv.ToTable(true, strColumns);

That's it, the easy way to get redundant data removed from a DataTable object.

Avoid Duplicate record insertion on page refresh in ASP.NET



Avoid Duplicate record insertion on page refresh in ASP.NET

One of most common issue which many of the web developers face in their web applications, is that the duplicate records are inserted to the Database on page refresh. If the web page contains some text box and a button to submit the textbox data to the database. In that case when the user insert some data to the textbox and click on the submit button, it will save the record to the Database and then if the user refresh the web page immediately then the same record is again saved to the database as there is no unique keys that can be used to verify the existence of the data, so as to prevent the multiple insertion.


From this behavior we can definitely know that, on the page fresh the  button click event is fired.

To avoid this problem we can try this method as discuss below.

On page load event save the date/time stamp in a session variable, when the page is first loaded, a Session variable is populated with the current date/time as follows:


void Page_Load(Object sender, EventArgs e)
{
   if(!IsPostBack)
     {
        Session["update"] =  Server.UrlEncode(System.DateTime.Now.ToString());
       }
  }


On the page's PreRender event, a ViewState variable is set to the value of the Session variable as follows:

  
  void Page_PreRender(object obj,EventArgs e)
    {
        ViewState["update"] = Session["update"];
    }
 


Then these two values are compared to each other immediately before the database INSERT command is run.  If they are equal, then the command is permitted to execute and the Session variable is updated with the current date/time, otherwise the command is bypassed as given below:  


    void btnSubmit_Click(object obj, EventArgs e)
    {
        string name = "";
        string qualification = "";


        if (Session["update"].ToString() == ViewState["update"].ToString())
        {
            if (txtName.Text != "" || txtName.Text != null)
            {
                name = txtName.Text.ToString();
            }

            if (txtQualification.Text != "" || txtQualification.Text != null)
            {
                qualification = txtQualification.Text.ToString();
            }

           //--- Insert data function should be execute here

           string strSql = "INSERT INTO Testdata (Name,Qualification) VALUES ('" + name + "','" + qualification + "')";
           
            SqlConnection ANConnection = new SqlConnection(ConnectionString);

            ANConnection.Open();
            SqlCommand ANCommand = new SqlCommand(strSql, ANConnection);
            ANCommand.ExecuteNonQuery();

            ANConnection.Close();
            ANConnection.Dispose();
                                   
            //--End of save data
           
           lblMessage.Text = "Inserted Record Sucessfully
           Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());
        }
        else
        {
            lblMessage.Text = "Failure – Due to Page Refresh";
            txtName.Text = "";
            txtQualification.Text = "";
        }
    }

 
 


Note: that ViewState needs to be enabled on the page for this to work; if ViewState is not enabled then a hidden form field may be used instead. 

Generate Machine Keys from IIS Manager


Generate Machine Keys from IIS Manager

 

 

The machineKey element of the ASP.NET web.config specifies the algorithm and keys that ASP.NET will use for encryption.

By default the validationKey and the decryptionKey keys are set to AutoGenerate which means the runtime will generate a random key for use. This works fine for applications that are deployed on a single server. When you use webfarms a client request can land on any one of the servers in the webfarm. Hence you will have to hardcode the validationKey and the decryptionKey on all your servers in the farm with a manually generated key.

There are a lot of articles that describe how to use RNGCryptoServiceProvider to generate a random key. There are also a lot of online tools that generate random keys for you. But I would suggest writing your own script because any one who has access to these keys can do evil things like tamper your forms authentication cookie or viewstate.

With IIS 7 you no longer have to do this manually. The IIS 7.0 manager has a built in feature that you can use to generate these keys.

It uses RNGCryptoServiceProvider internally to create a random key. The value is stored locally in the web.config of that application something like :


<?xml version="1.0" encoding="UTF-8"?>
<configuration> 

<system.web> 

<machineKey decryptionKey="F6722806843145965513817CEBDECBB1F94808E4A6C0B2F2,IsolateApps" validationKey="C551753B0325187D1759B4FB055B44F7C5077B016C02AF674E8DE69351B69

FEFD045A267308AA2DAB81B69919402D7886A6E986473EEEC9556A9003357F5ED45,

IsolateApps"/> </system.web>
</configuration>  

You can copy it and paste it in the web.config file of all the servers in the webfarm.

Show Gridview Header and Footer without any Data


Show Gridview Header and Footer without any Data

Today I will show how to show gridview header and footer when no data is returned from the dataset or datatable..

The trick here is to add a new blank row to the DataTable that you used as your DataSource if there was no data returned in your query.
Here’s the method for showing the Header and Footer of GridView when no data returned in the query.

    private void ShowNoResultFound(DataTable source, GridView gv)
    {
        // create a new blank row to the DataTable
        source.Rows.Add(source.NewRow()); 
 
       // Bind the DataTable which contain a blank row to the GridView
        gv.DataSource = source;
 
        gv.DataBind();
 
       // Get the total number of columns in the GridView to know 
           what the Column Span should be
        int columnsCount = gv.Columns.Count;
 
        gv.Rows[0].Cells.Clear();// clear all the cells in the row
        gv.Rows[0].Cells.Add(new TableCell()); //add a new blank cell 
        //set the column span to the new added cell
        gv.Rows[0].Cells[0].ColumnSpan = columnsCount; 

        //You can set the styles here
        gv.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
        gv.Rows[0].Cells[0].ForeColor = System.Drawing.Color.Red;
        gv.Rows[0].Cells[0].Font.Bold = true;
        //set No Results found to the new added cell
        gv.Rows[0].Cells[0].Text = "NO RESULT FOUND!";
    }
 
 
As you can see, the method above takes two paramaters, first is the DataTable that you used as the DataSource, second is the ID of your GridView.
All you need to do is Call the method ShowNoResultFound() when your DataSource ( the DataTable) returns nothing. See this example below:

private void BindGridView()
{ 
        DataTable dt = new DataTable(string user);
        SqlConnection connection = new SqlConnection(GetConnectionString()); 
        try
        {
            connection.Open();
            string sqlStatement = "SELECT* FROM Orders WHERE UserID = @User";
            SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);
            sqlCmd.Parameters.AddWithValue("@User", user);
            SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);

            sqlDa.Fill(dt);
            if (dt.Rows.Count > 0) //Check if DataTable returns data
            {
                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
            Else //else if no data returned from the DataTable then 
            {    //call the method ShowNoResultFound()
                ShowNoResultFound(dt,GridView1);
            }
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
                string msg = "Fetch Error:";
                msg += ex.Message;
                throw new Exception(msg);
        }
        finally
        {
            connection.Close();
        }
}
 
 
 
 
The Output is like this:
 
Header 1    Header 2    Header 3    Header  4
 
No Result Found
 
Footer 1    Footer 2    Footer 3    Footer 4 

 

Sunday 21 October 2012

Installing MVC3 after Installing MVC4


Installing MVC3 after Installing MVC4

 

I came across this situation when i recently installed VWD 2010.. When i installed MVC4 template;I found out that MVC3 template disappeared after this installation..
Here is this trick I found out in order to resolve this problem..
There is this Nuget Template that gets installed by default when u install MVC4.
If you have this problem, go to Add Remove Programs in the control panel and remove NuGet and the reinstall Mvc3 and the templates will be available.   
For More Details, Here are few links for you to refer:
Happy Coding :-)       

List of Common Error Codes with their Meanings


List of Common Error Codes with their Meanings

100 Continue

This means that the server has received the request headers, and that the client should proceed to send the request body (in the case of a request for which a body needs to be sent; for example, a POST request).
If the request body is large, sending it to a server when a request has already been rejected based upon inappropriate headers is inefficient.
To have a server check if the request could be accepted based on the request's headers alone, a client must send Expect: 100-continue as a header in its initial request
and check if a 100 Continue status code is received in response before continuing (or receive 417 Expectation Failed and not continue)


101 Switching Protocols

This means the requester has asked the server to switch protocols and the server is acknowledging that it will do so


102 Processing

As a WebDAV request may contain many sub-requests involving file operations, it may take a long time to complete the request.
This code indicates that the server has received and is processing the request, but no response is available yet.
This prevents the client from timing out and assuming the request was lost.

200 OK

Standard response for successful HTTP requests. The actual response will depend on the request method used. In a GET request,
the response will contain an entity corresponding to the requested resource.
In a POST request the response will contain an entity describing or containing the result of the action.


201 Created

The request has been fulfilled and resulted in a new resource being created.


202 Accepted

The request has been accepted for processing, but the processing has not been completed.
The request might or might not eventually be acted upon, as it might be disallowed when processing actually takes place.


203 Non-Authoritative Information (since HTTP/1.1)

The server successfully processed the request, but is returning information that may be from another source.


204 No Content

The server successfully processed the request, but is not returning any content.


205 Reset Content

The server successfully processed the request, but is not returning any content.
Unlike a 204 response, this response requires that the requester reset the document view.


206 Partial Content

The server is delivering only part of the resource due to a range header sent by the client.
The range header is used by tools like wget to enable resuming of interrupted downloads, or split a download into multiple simultaneous streams.

207 Multi-Status (WebDAV; RFC 4918)

The message body that follows is an XML message and can contain a number of separate response codes, depending on how many sub-requests were made.


208 Already Reported (WebDAV; RFC 5842)

The members of a DAV binding have already been enumerated in a previous reply to this request, and are not being included again.


226 IM Used (RFC 3229)

The server has fulfilled a GET request for the resource, and the response is a representation of the result of one or more instance-manipulations
applied to the current instance.


300 Multiple Choices

Indicates multiple options for the resource that the client may follow.
It, for instance, could be used to present different format options for video, list files with different extensions, or word sense disambiguation.


301 Moved Permanently

This and all future requests should be directed to the given URI.
302 Found

This is an example of industry practice contradicting the standard.
The HTTP/1.0 specification (RFC 1945) required the client to perform a temporary redirect (the original describing phrase was "Moved Temporarily"),
but popular browsers implemented 302 with the functionality of a 303 See Other.
Therefore, HTTP/1.1 added status codes 303 and 307 to distinguish between the two behaviours.
However, some Web applications and frameworks use the 302 status code as if it were the 303.

303 See Other (since HTTP/1.1)

The response to the request can be found under another URI using a GET method. When received in response to a POST (or PUT/DELETE),
it should be assumed that the server has received the data and the redirect should be issued with a separate GET message.

304 Not Modified

Indicates the resource has not been modified since last requested.
Typically, the HTTP client provides a header like the If-Modified-Since header to provide a time against which to compare.
Using this saves bandwidth and reprocessing on both the server and client, as only the header data must be sent and received
in comparison to the entirety of the page being re-processed by the server,
then sent again using more bandwidth of the server and client.

305 Use Proxy (since HTTP/1.1)

Many HTTP clients (such as Mozilla[8] and Internet Explorer) do not correctly handle responses with this status code, primarily for security reasons.

306 Switch Proxy

No longer used.Originally meant "Subsequent requests should use the specified proxy."

307 Temporary Redirect (since HTTP/1.1)

In this case, the request should be repeated with another URI; however, future requests can still use the original URI.
In contrast to 302, the request method should not be changed when reissuing the original request.
For instance, a POST request must be repeated using another POST request.

308 Permanent Redirect (experimental Internet-Draft)

The request, and all future requests should be repeated using another URI.
307 and 308 (as proposed) parallel the behaviours of 302 and 301, but do not require the HTTP method to change.
So, for example, submitting a form to a permanently redirected resource may continue smoothly.

400 Bad Request

The request cannot be fulfilled due to bad syntax.

401 Unauthorized

Similar to 403 Forbidden, but specifically for use when authentication is possible but has failed or not yet been provided.
The response must include a WWW-Authenticate header field containing a challenge applicable to the requested resource.
See Basic access authentication and Digest access authentication.

402 Payment Required

Reserved for future use. The original intention was that this code might be used as part of some form of digital cash or micropayment scheme,
but that has not happened, and this code is not usually used. As an example of its use, however, Apple's MobileMe service generates a 402 error
("httpStatusCode:402" in the Mac OS X Console log) if the MobileMe account is delinquent.

403 Forbidden

The request was a legal request, but the server is refusing to respond to it. Unlike a 401 Unauthorized response, authenticating will make no difference.

404 Not Found

The requested resource could not be found but may be available again in the future.Subsequent requests by the client are permissible.

405 Method Not Allowed

A request was made of a resource using a request method not supported by that resource;
for example, using GET on a form which requires data to be presented via POST, or using PUT on a read-only resource.

406 Not Acceptable

The requested resource is only capable of generating content not acceptable according to the Accept headers sent in the request.

407 Proxy Authentication Required

The client must first authenticate itself with the proxy.

408 Request Timeout

The server timed out waiting for the request. According to W3 HTTP specifications: "The client did not
produce a request within the time that the server was prepared to wait.
The client MAY repeat the request without modifications at any later time."

409 Conflict

Indicates that the request could not be processed because of conflict in the request, such as an edit conflict.

410 Gone

Indicates that the resource requested is no longer available and will not be available again.
This should be used when a resource has been intentionally removed and the resource should be purged.
Upon receiving a 410 status code, the client should not request the resource again in the future.
Clients such as search engines should remove the resource from their indices.
Most use cases do not require clients and search engines to purge the resource, and a "404 Not Found" may be used instead.

411 Length Required

The request did not specify the length of its content, which is required by the requested resource.

412 Precondition Failed

The server does not meet one of the preconditions that the requester put on the request.

413 Request Entity Too Large

The request is larger than the server is willing or able to process.

414 Request-URI Too Long

The URI provided was too long for the server to process.

415 Unsupported Media Type

The request entity has a media type which the server or resource does not support.
For example, the client uploads an image as image/svg+xml, but the server requires that images use a different format.

416 Requested Range Not Satisfiable

The client has asked for a portion of the file, but the server cannot supply that portion.
For example, if the client asked for a part of the file that lies beyond the end of the file.

417 Expectation Failed

The server cannot meet the requirements of the Expect request-header field.

418 I'm a teapot (RFC 2324)

This code was defined in 1998 as one of the traditional IETF April Fools' jokes, in RFC 2324, Hyper Text Coffee Pot Control Protocol,
and is not expected to be implemented by actual HTTP servers. However, known implementations do exist.

420 Enhance Your Calm (Twitter)

Returned by the Twitter Search and Trends API when the client is being rate limited.
Likely a reference to this number's association with marijuana.
Other services may wish to implement the 429 Too Many Requests response code instead.
The phrase "Enhance Your Calm" is a reference to Demolition Man (film).
In the film, Sylvester Stallone's character John Spartan is a hot-head in a generally more subdued future,
and is regularly told to "Enhance your calm" rather than a more common phrase like "calm down".

422 Unprocessable Entity (WebDAV; RFC 4918)

The request was well-formed but was unable to be followed due to semantic errors.

423 Locked (WebDAV; RFC 4918

The resource that is being accessed is locked.

424 Failed Dependency (WebDAV; RFC 4918)

The request failed due to failure of a previous request (e.g. a PROPPATCH).

424 Method Failure (WebDAV)

Indicates the method was not executed on a particular resource within its scope because some part of the method's execution
failed causing the entire method to be aborted.

425 Unordered Collection (Internet draft)

Defined in drafts of "WebDAV Advanced Collections Protocol",but not present in "Web Distributed Authoring and Versioning (WebDAV) Ordered Collections Protocol".

426 Upgrade Required (RFC 2817)

The client should switch to a different protocol such as TLS/1.0.

428 Precondition Required (RFC 6585)

The origin server requires the request to be conditional.
Intended to prevent "the 'lost update' problem, where a client GETs a resource's state, modifies it,
and PUTs it back to the server, when meanwhile a third party has modified the state on the server, leading to a conflict."

429 Too Many Requests (RFC 6585)

The user has sent too many requests in a given amount of time. Intended for use with rate limiting schemes

431 Request Header Fields Too Large (RFC 6585)
   
The server is unwilling to process the request because either an individual header field, or all the header fields collectively, are too large.

444 No Response (Nginx)

An Nginx HTTP server extension. The server returns no information to the client and closes the connection (useful as a deterrent for malware).

449 Retry With (Microsoft)

A Microsoft extension. The request should be retried after performing the appropriate action.

450 Blocked by Windows Parental Controls (Microsoft)

A Microsoft extension. This error is given when Windows Parental Controls are turned on and are blocking access to the given webpage.

499 Client Closed Request (Nginx)

An Nginx HTTP server extension. This code is introduced to log the case when the connection is closed by client
while HTTP server is processing its request, making server unable to send the HTTP header back.

500 Internal Server Error

A generic error message, given when no more specific message is suitable.

501 Not Implemented

The server either does not recognise the request method, or it lacks the ability to fulfill the request.

502 Bad Gateway

The server was acting as a gateway or proxy and received an invalid response from the upstream server.

503 Service Unavailable

The server is currently unavailable (because it is overloaded or down for maintenance). Generally, this is a temporary state.

504 Gateway Timeout

The server was acting as a gateway or proxy and did not receive a timely response from the upstream server.

505 HTTP Version Not Supported

The server does not support the HTTP protocol version used in the request.

506 Variant Also Negotiates (RFC 2295)

Transparent content negotiation for the request results in a circular reference.

507 Insufficient Storage (WebDAV; RFC 4918)

The server is unable to store the representation needed to complete the request.

508 Loop Detected (WebDAV; RFC 5842)

The server detected an infinite loop while processing the request (sent in lieu of 208).

509 Bandwidth Limit Exceeded (Apache bw/limited extension)

This status code, while used by many servers, is not specified in any RFCs.

510 Not Extended (RFC 2774)

Further extensions to the request are required for the server to fulfill it.

511 Network Authentication Required (RFC 6585)

The client needs to authenticate to gain network access. Intended for use by intercepting proxies used to control access to the network
(e.g. "captive portals" used to require agreement to Terms of Service before granting full Internet access via a Wi-Fi hotspot).

598 Network read timeout error (Unknown)

This status code is not specified in any RFCs, but is used by Microsoft Corp.
HTTP proxies to signal a network read timeout behind the proxy to a client in front of the proxy.

599 Network connect timeout error (Unknown)

This status code is not specified in any RFCs, but is used by Microsoft Corp.
HTTP proxies to signal a network connect timeout behind the proxy to a client in front of the proxy.
back to top