Wednesday, 25 April 2012

Exception Handling in asp.net

You can't make half boiled without breaking eggs and you cannot write code without creating bugs(errors)
but we should work to minimize the impact of these bugs ,aiming for a "zero error count" for this .net support Exception Handling Methodology.
 Here we are going to see Try,Catch and Finally..

Definition:

Exception handling is an in built mechanism in .NET framework to Find and handle run time errors.
try
{
    // Statements that are can cause exception
}
catch(Type x)
{
    // Statements to handle exception
}
finally
{
    // Statement to clean up 
}
When error occurs in try block it throw error into catch block,so that we can handle that error, than finally block is used to clean up the statement.

Difference Between Session State and View State in asp.net



ViewState persist the values of controls of particular page in the client (browser) when post back operation done. When user requests another page previous page data no longer available.

SessionState persist the data of particular user in the server. This data available till user close the browser or session time completes.
protected void btnSubmit_Click(object sender, EventArgs e)  
 {   
      ViewState["DataScorceName"] = datasource;  
      ViewState["ClientName"] = txtCustomer.Text;  
 }  
 //Retrieve viewstate information  
 txtCname.Text = ViewState["ClientName"]  
 Store information in Session State:  
 Session["EmpName"] = txtUser.Text;  
 //Retrieve session value in 2nd page  
 lblEmp.Text = Session["UserName"].ToString();  

Saturday, 14 April 2012

CompareValidator Control in asp.net

Definition 

The CompareValidator control allows you to compare the value entered by the user into an input control such as TextBox,TextArea,etc..
syntax :
<asp:CompareValidator
     id="ProgrammaticID"
     ControlToValidate="Programmatic ID of Server Control to Validate"
     ValueToCompare="value"
     ControlToCompare="value"  
     Type="DataType" 
     Operator="Operator Value" 
     ErrorMessage="Message to display in ValidationSummary control"
     Text="Message to display in control"  
     ForeColor="value"
     BackColor="value"  
     runat="server" > 
</asp:CompareValidator>
Properties For Campare Validator:
Property
Description
BackColor
This Property is use to change the background color.
ControlToCompare
The name of the control which is going to compare with
ControlToValidate
The id of the control to validate
Display
The display behavior for the validation control. Legal values are:
          None – does not display the validation and only displayed in the          ASP.NET Validation Summary control.         Static – displays the validation message if check fails. The space of the control is reserved even if the check passes.          Dynamic – displays the validation message if check fails. The space of the control is not reserved if the check passes.
EnableClientScript
Boolean value to specify if client-side validation is enabled or disabled.
Enabled
Property to set a Boolean value to specify if validation control is enabled or disabled.
ErrorMessage
The text to display in the Validation Summary control when validation fails. Note: This text will also be displayed in the validation control if the Text property is not set
ForeColor
The foreground color of the control
id
A unique id for the control
IsValid
A Boolean value that indicates whether the control specified by ControlToValidate is determined to be valid
Operator
The type of comparison to perform. The operators are:
  • NotEqual
  • DataTypeCheck
  • Equal
  • GreaterThan
  • GreaterThanEqual
  • LessThan
  • LessThanEqual
runat
Specifies that the control is a server control. Must be set to "server"
Text
The message to display when validation fails
Type
Specifies the data type of the values to compare. The types are:
  • Currency
  • Date
  • Double
  • Integer
  • String
ValueToCompare
A specified value to compare with
Example:
<form runat="server"> <table>    <tr valign="top">      <td colspan="4"><h4>Compare two values</h4></td>    </tr>     <tr valign="top">      <td><asp:TextBox id="txt01" runat="server" /></td>      <td> = </td>      <td><asp:TextBox id="txt02" runat="server" /></td>      <td><asp:Button Text="Validate" runat="server" /></td>    </tr> </table> <br /> <asp:CompareValidator id="compval"  Display="dynamic" ControlToValidate="txt01"  ControlToCompare="txt02"  ForeColor="red"  BackColor="yellow"  Type="String" EnableClientScript="false"  Text="Validation Failed!"  runat="server" /> </form>






Validation Server Controls in asp.net

A Validation server control is used to validate the data which the user gives. If the data does not pass validation, it will display an warning message to the user.

 Validation Server Control Description:

CompareValidator :Compares the value of one input control to the value of another input control or to a fixed value.
CustomValidator: Allows you to write a method to handle the validation of the value entered.
RangeValidator: Checks that the user enters a value that falls between two values.
RegularExpressionValidator: Ensures that the value of an input control matches a specified pattern.
RequiredFieldValidator: Makes an input control a required field.
ValidationSummary:Displays a report of all validation errors occurred in a Web page.


The syntax for creating a Validation server control is:


<asp:controlname id="someid" runat="server" />

Tuesday, 10 April 2012

Concatenate columns in SQL


Syntax:
SELECT Concat(Field1,Field2) From Tablename

concat(firstname, lastname)


SELECT e.Emp_Id,Concat(e.fir_name,',',e.Las_name) as Fir_name FROM  emp_detail e,emp_off_detail e1 where e.Emp_ID=e1.Emp_ID

To Upload PDF Files Only Using Asp.net File Upload Control


File Upload Only PDF Files:
----------------------------
Using RegularExpressionValidator
================================
<asp:FileUpload ID="FileUpload1" runat="server" class="textb" Width="220px" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"  Text="Only PfFiles are allowed." ErrorMessage="Only PDF Files are allowed."
ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.pdf)$" ControlToValidate="FileUpload1"></asp:RegularExpressionValidator>

Saturday, 7 April 2012

Automatic Database Backup in Mysql with the help of Batch file


To take backup in MySql we have to use following steps,

        1.Open a Notepad, then Place your Backup Script as given in figure.

        2.Then, go to file in notepad and select  ‘Save as..’ and give name for your Batch file.

For Example,

        Mybackup and save with .bat format as shown in figure.


        Add your batch file  in scheduler using instruction given below.
Schedule a task to take back up every day
You must be logged on as an administrator to perform these steps. If you aren't logged on as an administrator, you can only change settings that apply to your user account.
If you use a specific program on a regular basis, you can use the Task Scheduler wizard to create a task that opens the program for you automatically according to the schedule you choose. For example, if you use a financial program on a certain day each month, you can schedule a task that opens the program automatically to avoid the risk of forgetting to open it yourself.
1.   Open Task Scheduler by clicking the Start button , clicking Control Panel, clickingSystem and Security, clicking Administrative Tools, and then double-clicking Task Scheduler.  If you're prompted for an administrator password or confirmation, type the password or provide confirmation.
2.   Click the Action menu, and then click Create Basic Task.
3.   Type a name for the task and an optional description, and then click Next.
4.   Do one of the following:
·         To select a schedule based on the calendar, click DailyWeeklyMonthly, or One time, click Next; specify the schedule you want to use, and then click Next.
·         To select a schedule based on common recurring events, click When the computer starts or When I log on, and then click Next.
·         To select a schedule based on specific events, click When a specific event is logged, click Next; specify the event log and other information using the drop-down lists, and then click Next.
5.   To schedule a program to start automatically, click Start a program, and then clickNext.
6.   Click Browse to find the program you want to start, and then click Next.
7.   Click Finish.




Arrays in C#


Here Arrays are divided into the following sections:

  • General Arrays
  • Declaring Arrays
  • Initializing Arrays
  • Accessing Array Members
  • Arrays are Objects
  • Using for each with Arrays

Arrays in General

In C# we can call arrays as zero indexed because the array indexes start at zero. Arrays in C# work similarly to how arrays work in most other popular languages there are, however, a few differences that you should be aware of.
When declaring an array, the square brackets ([]) must come after the type, not the identifier. Placing the brackets after the identifier is not legal syntax in C#.
int[] sajil; // not int sajil[]; 
Another think  is that the size of the array is not part of its type as it is in the C language. This allows you to declare an array and assign any array of int objects to it, regardless of the array's length.

int[] num; // declare num as an int array of any size
num = new int[10];  // num is a 10-element array
num = new int[20];  // now it's a 20-element array

Declaring Arrays

In C# we can Create single-dimensional arrays, multidimensional arrays (rectangular arrays), and array-of-arrays (jagged arrays). The following examples show how to declare different kinds of arrays:
Single-dimensional arrays:
int[] num;
Multidimensional arrays:
String [,] nam;
Array-of-arrays (jagged):
Byte [][] score;
Declaring them (as shown above) does not actually create the arrays. In C#, arrays are objects and must be instantiated. The following examples show how to create arrays:
Single-dimensional arrays:
int [] num = new int [5];
Multidimensional arrays:
String [,] name = new string [5, 4];
Array-of-arrays (jagged):
byte[][] score = new byte[5][];
for (int x = 0; x < score.Length; x++) 
{
   score[x] = new byte[4];
}
You can also have larger arrays. For example, you can have a three-dimensional rectangular array:
int[,,] buttons = new int[4,5,3];
You can even mix rectangular and jagged arrays. For example, the following code declares a single-dimensional array of three-dimensional arrays of two-dimensional arrays of type int:
int[][,,][,] numbers;

Example

The following is a complete C# program that declares and instantiates arrays as discussed above.
// array.cs
using System;
class Sample
{
    public static void Main()
    {
        // Single-dimensional array
        int[] num = new int[5];
 
        // Multidimensional array
        string[,] name = new string[5,4];
 
        // Array-of-arrays (jagged array)
        byte[][] score = new byte[5][];
 
        // Create the jagged array
        for (int i = 0; i < score.Length; i++)
        {
            score[i] = new byte[i+3];
        }
 
        // Print length of each row
        for (int i = 0; i < score.Length; i++)
        {
            Console.WriteLine("Length of row {0} is {1}", i, score[i].Length);
        }
    }
}

Output

Length of row 0 is 3
Length of row 1 is 4
Length of row 2 is 5
Length of row 3 is 6
Length of row 4 is 7

Initializing Arrays

C# provides simple ways to initialize arrays at declaration time by enclosing the initial values in curly braces ({}). The following examples show different ways to initialize different kinds of arrays.
Note   If you do not initialize an array at the time of declaration, the array members are automatically initialized to the default initial value for the array type. Also, if you declare the array as a field of a type, it will be set to the default value null when you instantiate the type.

Single-Dimensional Array

int[] num = new int[5] {1, 2, 3, 4, 5};
string[] name = new string[3] {"sajil", "vinoth", "viji"};
You can omit the size of the array, like this:
int[] num = new int[] {1, 2, 3, 4, 5};
string[] name = new string[] {" sajil ", " vinoth ", " viji "};
You can also omit the new operator if an initializer is provided, like this:
int[] numbers = {1, 2, 3, 4, 5};
string[] names = {" sajil ", " vinoth ", " viji "};

Multidimensional Array

int[,] numbers = new int[3, 2] { {1, 2}, {3, 4}, {5, 6} };
string[,] siblings = new string[2, 2] { {" sajil ","viji"}, {"anand","vinoth"} };
You can omit the size of the array, like this:
int[,] numbers = new int[,] { {1, 2}, {3, 4}, {5, 6} };
string[,] siblings = new string[,] { {" sajil ","viji"}, {"anand","vinoth"} };
You can also omit the new operator if an initializer is provided, like this:
int[,] numbers = { {1, 2}, {3, 4}, {5, 6} };
string[,] siblings = { {"sajil", "viji"}, {"anand", "vinoth"} };

Jagged Array (Array-of-Arrays)

You can initialize jagged arrays like this example:
int[][] num = new int[2][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} };
You can also omit the size of the first array, like this:
int[][] num = new int[][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} };
-or-
int[][] numb = { new int[] {2,3,4}, new int[] {5,6,7,8,9} };
Notice that there is no initialization syntax for the elements of a jagged array.

Accessing Array Members

Accessing array members is straightforward and similar to how you access array members in C/C++. For example, the following code creates an array called numbers and then assigns a 5 to the fifth element of the array:
int[] num = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
numbers[4] = 5;
The following code declares a multidimensional array and assigns 5 to the member located at [1, 1]:
int[,] num = { {1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10} };
numb[1, 1] = 5;
The following is a declaration of a single-dimension jagged array that contains two elements. The first element is an array of two integers, and the second is an array of three integers:
int[][] num = new int[][] { new int[] {1, 2}, new int[] {3, 4, 5}
};
The following statements assign 58 to the first element of the first array and 667 to the second element of the second array:
num[0][0] = 58;
num[1][1] = 667;

Arrays are Objects

In C#, arrays are actually objects. System.Array is the abstract base type of all array types. You can use the properties, and other class members, that System.Array has. An example of this would be using the Length property to get the length of an array. The following code assigns the length of the numbers array, which is 5, to a variable calledLengthOfNumbers:
int[] num = {1, 2, 3, 4, 5};
int LengthOfNumbers = num.Length;
The System.Array class provides many other useful methods/properties, such as methods for sorting, searching, and copying arrays.

Using foreach on Arrays

C# also provides the foreach statement. This statement provides a simple, clean way to iterate through the elements of an array. For example, the following code creates an array called numbers and iterates through it with the foreach statement:
int[] num = {4, 5, 6, 1, 2, 3, -2, -1, 0};
foreach (int i in num)
{
   System.Console.WriteLine(i);
}
With multidimensional arrays, you can use the same method to iterate through the elements, for example:
int[,] num = new int[3, 2] {{9, 99}, {3, 33}, {5, 55}};
foreach(int i in num)
{
   Console.Write("{0} ", i);
}
The output of this example is:
9 99 3 33 5 55
However, with multidimensional arrays, using a nested for loop gives you more control over the array elements.

Error Message:An item with the same key has already been added in Windows Application


Changing the Background Image:

        When we trying to change the background Image of a control (forms,tabcontrol,groupbox,etc.,) in Windows Form an error message will be appear like,

Error message: An item with the same key has already been added

The Solution is-If you have two Resource.resx file in solution explorer, delete one of  the Resource.resx file  from them.

Examples:

Delete this Resource.resx file



Don’t Delete this one.


Wednesday, 4 April 2012

SQL UPDATE Statement


UPDATE Statement
        The UPDATE statement is used to modify the data values for particular record in the table.

Syntax:

UPDATE table_name SET column1=value, column2=value2,...
WHERE some_column=some_value

Note: ‘WHERE’ Clause in Update command to be must. That WHERE Clause specifies which record or records that should be updated. Without WHERE Clause all records of table to be modified.

Example:

        The Table “Contact” has following data,

ID
NAME
DESIGNATION
CITY
MOBILE
1
venkat
CEO
Kodambakkam
999989845
2
Santhosh
manager
Puddukottai
9999898978
3
Kousilaya
Asst.manager
Trichy
9659315754
4
Ananth
CEO
Chennai
9999999945
5
Sajil
MD
Surandai
6677888997

If we want to change designation of employee “Ananth” as Developer and mobile-9698958775, we use following syntax,

UPDATE contact SET Designation=’Developer’, Mobile=9698958775 WHERE Name=’Ananth’

The Result-Set is,

ID
NAME
DESIGNATION
CITY
MOBILE
1
venkat
CEO
Kodambakkam
999989845
2
Santhosh
manager
Puddukottai
9999898978
3
Kousilaya
Asst.manager
Trichy
9659315754
4
Ananth
Developer
Chennai
9698958775
5
Sajil
MD
Surandai
6677888997

Note: SQL Not Case-Sensitive and Varchar datatype should be enclosed with single quote.

If we omit the WHERE Clause in the above command like,

UPDATE contact SET Designation=’Developer’, Mobile=9698958775

The Result-set is,

ID
NAME
DESIGNATION
CITY
MOBILE
1
venkat
Developer
Kodambakkam
9698958775
2
Santhosh
Developer
Puddukottai
9698958775
3
Kousilaya
Developer
Trichy
9698958775
4
Ananth
Developer
Chennai
9698958775
5
Sajil
Developer
Surandai
9698958775