Saturday, March 23, 2013

How to check whether a TextBox has value or not using JavaScript

Using JavaScript we can perform client side validation. It will improve the performance of your web application. Here i have shown a simple basic validation, how to check whether a text box has value or not.
    var username=document.getElementById("uname").value;  
    if (username==null || username=="")  
    {  
        alert("Please Enter Username");  
        document.getElementById("uname").focus();  
    }  

Here the alert is used to display a message box with the text it has. And the focus() is used to move the cursor to the corresponding text box.

Sample HTML5 Validations

Some HTML5 validation samples are here. You can use it in your project.
  • Limit the character count in text box. Here it's uses pattern attribute that is used to provide the Regular expression validation. So the ".{4,4}" is a regular expression that's allows only 4 character.
<input type="text" pattern=".{4,4}" name="username" id="username" value=""/>
  • Allow only numbers in text box. Here it's uses pattern attribute that is used to provide the Regular expression validation. So the "\d*" is a regular expression that's represents decimal.
<input type="text" pattern="\d*" name="phonenumber" id="phonenumber" value="" />
  • Required field validation for drop down list. If the selected field has no value means the validation will be triggered. In the below sample the "Select" field has empty value in the "value" attribute.
<select id="grade" name="grade"  required>
<option value="">Select</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
  • Email validation. The following code has the type="email". So it will allow only email.
<input type="email" name="email" id="email" value="">
  • Required field validation for text box. The following code has "required" attribute. That is used to provide this validation,
<input type="text" name="firstname" id="firstname" value="" required/>

Create a Tab control using JQuery in ASP.NET

By using the below code we can make a simple JQuery tab control. In this example i am going to create two tab. When we click a tab a table will be hide and another table will be visible.
  • Befor start coding download and add latest JQuery library and refer it in code like below inside head section.
<script src='js/common/jquery-1.9.1.js' ></script>
  •  Then add the below JQuery code inside head section in ASP.NET HTML design page

<script type="text/javascript">
    $(document).ready(function () {
        $(".tabLink").each(function () {
            $(this).click(function () {
                tabeId = $(this).attr('id');
                $(".tabLink").removeClass("activeLink");
                $(this).addClass("activeLink");
                $(".tabcontent").addClass("hide");
                $("#" + tabeId + "-1").removeClass("hide")
                return false;
            });
        });
    });
 </script>
  • Then add the below code in body section. This is actually a tab design.
<table cellpadding="0" cellspacing="0">
    <tr>
        <td class="contact_tab_box">
        <a href="javascript:;" class="tabLink activeLink" id="tab1">Tab1</a>
        <a href="javascript:;" class="tabLink " id="cont-2">Tab2</a>
        </td>
    </tr>
</table>
  • Now we have to design two tables to work with the tab when we click it
<table width="100%" class="tabcontent" id="t1">
    <tr>
        <td>
        DO YOUR DESIGN HERE
        </td>
    </tr>
</table>

<table width="100%" class="tabcontent hide" id="t2"> <tr> <td> DO YOUR DESIGN HERE </td> </tr> </table>
  • We need the below CSS for better design
.contact_tab_bar_left {
    background: #F2F2F2;
}
.contact_tab_bar_right {
    background: #F2F2F2;     border-radius:0px 6px 6px 0px; }
.contact_tab_box {     background: #EEEEEE; }
.contact_tab_box a {     font-family:Arial;     font-size:14px;     border:1px solid #797979;     color:#000;
    padding: 7px 30px;     text-decoration:none;     background-color: #eee;     border-radius: 6px 6px 0px 0px;     -moz-border-radius: 6px 6px 0px 0px;     -webkit-border-radius: 6px 6px 0px 0px; }
.contact_tab_box a.activeLink {     font-family:Arial;     font-size:14px;     font-weight: bold;     background-color: #3F3F3F;     color:#FFFFFF;     border-bottom: 0;     padding: 7px 30px;     border-radius: 6px 6px 0px 0px;     -moz-border-radius: 6px 6px 0px 0px;     -webkit-border-radius: 6px 6px 0px 0px; }
.contact_tab_content {     border: 1px solid #797979;     -moz-border-radius: 6px;     -webkit-border-radius: 6px;     border-radius: 6px; } .hide { display: none;}

Monday, March 18, 2013

How to read value from Web.Config file in ASP.NET

We can use Web.Config file to store any string value and that can be used in our ASP.NET application. After deploying the application also we can change the value in the config file. To do so,

In Web.Config file add a key and value that can be used in your application within the appSettings tags like below.
    <configuration>  
        <appSettings>  
            <add key="KEYNAME" value="KEYVALUE"/>  
        </appSettings>  
    </configuration> 
To retrieve the value use the below code,
string value = System.Configuration.ConfigurationManager.AppSettings["KEYNAME"].ToString();

Friday, March 8, 2013

How to call and pass parameter to a MS SQL Server Stored procedure


Refer the below code to call and pass parameter to a MS SQL Server Stored procedure. Replace the YOUR CONNECTION STRING text with the connection string of your database.
 Here UpdateIssueStatus_SP is the Stored Procedure name.
SqlParameter param;  
SqlCommand cmd;  
string connStr = "YOUR CONNECTION STRING";  

public void UpdateIssueStatus(int issueNo, char status)  
{  
    try  
    {  
        SqlConnection conn = new SqlConnection(connStr);  
        conn.Open();  
        cmd = new SqlCommand("UpdateIssueStatus_SP", conn);  
        cmd.CommandType = System.Data.CommandType.StoredProcedure;  
   
        param = new SqlParameter("@IssueNo", SqlDbType.Int);  
        param.Direction = ParameterDirection.Input;  
        param.Value = issueNo;  
        cmd.Parameters.Add(param);  
   
        param = new SqlParameter("@ApprovalStatus", SqlDbType.Char);  
        param.Direction = ParameterDirection.Input;  
        param.Value = status;  
        cmd.Parameters.Add(param);  
   
        cmd.ExecuteNonQuery();  
        conn.Close();  
    }  
    catch (Exception ex)  
    {  
    }  
}  

Write Javascript alert message box in ASP.NET code behind


To Write Javascript alert message box function  in ASP.NET code behind refer the below code. Just pass the error message as parameter to this function by calling it.
public void ShowAlertMessage(string error)  
{  
     Page page = HttpContext.Current.Handler as Page;  
     if (page != null)  
     {  
          error = error.Replace("'", "\'");  
          ScriptManager.RegisterStartupScript(page, page.GetType(), "errmsg", "alert('" + error + "');", true);  
     }  
}  

How to check whether a database exist or not in MS SQL Server

Using a simple SQL query we can check whether a database exist or not. Refer the below query.
Query:
SELECT database_id FROM sys.databases WHERE Name = 'DATABASE NAME'  

If the output is greater then 0 then the Database is exist else it's not exist

Replace the DATABASE NAME with the database name you going to check

Sample program to Encrypt and Decrypt string using TripleDESCryptoServiceProvider in CSharp (C#)


When we developing a .NET application there may be a need to encrypt a string before it getting stored into the database. And also it can be Decrypted when the string retrieved back from the database. To achieve that refer the below code.

To Encrypt:
public string key = "ab99";  
public string encryption(string strToEncrypt)  
{  
     try  
     {  
          TripleDESCryptoServiceProvider DescCryptoprovider = new TripleDESCryptoServiceProvider();  
          MD5CryptoServiceProvider MD5serviceprovider = new MD5CryptoServiceProvider();  
          byte[] bytehash = null;  
          byte[] bytebuff = null;  
          bytehash = MD5serviceprovider.ComputeHash(ASCIIEncoding.ASCII.GetBytes(key));  
          MD5serviceprovider = null;  
          DescCryptoprovider.Key = bytehash;  
          DescCryptoprovider.Mode = CipherMode.ECB;  
          bytebuff = ASCIIEncoding.ASCII.GetBytes(strToEncrypt);  
          return Convert.ToBase64String(DescCryptoprovider.CreateEncryptor().TransformFinalBlock(bytebuff, 0, bytebuff.Length));  
     }  
     catch (Exception ex)  
     {  
          throw;  
     }  
}  

To Decrypt:
public string decrypt(string strTodecrypt)  
{  
     try  
     {  
          TripleDESCryptoServiceProvider DescCryptoprovider = new TripleDESCryptoServiceProvider();  
          MD5CryptoServiceProvider MD5serviceprovider = new MD5CryptoServiceProvider();  
          byte[] bytehash = null;  
          byte[] bytebuff = null;  
          string decryptedstring = null;  
   
          bytehash = MD5serviceprovider.ComputeHash(ASCIIEncoding.ASCII.GetBytes(key));  
          MD5serviceprovider = null;  
          DescCryptoprovider.Key = bytehash;  
          DescCryptoprovider.Mode = CipherMode.ECB;  
          bytebuff = System.Convert.FromBase64String(strTodecrypt);  
          decryptedstring = ASCIIEncoding.ASCII.GetString(
               DescCryptoprovider.CreateDecryptor().TransformFinalBlock(bytebuff, 0, bytebuff.Length)); 
 
          return decryptedstring;  
     }  
     catch (Exception ex)  
     {  
          throw;  
     }  
}  

How to Get MD5 hash value of a file using CSharp (C#)

When transferring a file through internet there is no guarantee that the file will be secured till it reach the receiver. It may be attacked by any virus or hacker. So the receiver should ensure whether the received file is secured or it attacked. To ensure that before transfer the file we have to get the MD5 hash value of the file. Then after receiving that file the receiver should get the MD5 hash value. If the both hash value is same means the file is secured one. Else it’s an attacked one.
Below is the CSharp code to find the MD5 hash value of a file,
public string GetMD5HashOfAFile(string file)  
{  
    MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();  
    FileStream stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, 8192);  
    md5.ComputeHash(stream);  
    stream.Close();  

    byte[] hash = md5.Hash;  
    StringBuilder sb = new StringBuilder(); 
 
    foreach (byte b in hash)  
    {  
        sb.Append(string.Format("{0:X2}", b));  
    }  

    return sb.ToString();  
}  

Wednesday, March 6, 2013

Default Web Site not found in IIS 7

I recently had a problem that i couldn't find the "Default Web Site" under Sites tree view in IIS 7 and i found the solution too.

To Solve this we have to re install the IIS and WAS (Windows Process Activation Service)
To do this,

  • Go to Control Panel
  • Make sure the View By filter is set to "Category"
  • Click the Program link
  • Under the Programs and Features click "Turn windows features on or off link"
  • A window will popup
  • There uncheck the Internet Information Services and Windows Process Activation Services checkbox
  • Restart the system
  • Then recheck the check box you have unchecked(IIS & WAS)
  • Now check the Default Web Site in IIS, that will be there!

Friday, March 1, 2013

(Solved) Error: 503 Service Unavailable in IIS7

Solution:

  • Go to IIS
  • Select the Application Pool in the left side
  • Select the application pool that you are using for your application
  • Start the application pool if its stopped