Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Sunday, 29 November 2015

How to create and use a Database in SQL Server

SQL is not a case sensitive language
Press F5 for Execute SQL Query:

For Creating a Database we use 

create database [databasename]

Example: create database DemoDB

Select or Use Database using Query:

Use [databasename]

Example: use DemoDB

Moving One ListBox ListItems to another ListBox in Asp.Net using C#


MovingLIstIten.aspx.cs


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MovingListItemsInListbox
{
    public partial class MovingLIstIten : System.Web.UI.Page
    {
        ArrayList arrList1 = new ArrayList();
        ArrayList arrList2 = new ArrayList();
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btn1_Click(object sender, EventArgs e)
        {
            lblMessage.Visible = false;
            if (ListBox1.Items.Count > 0)
            {
                if (ListBox1.SelectedIndex >= 0)
                {
                    for (int i = 0; i < ListBox1.Items.Count; i++)
                    {
                        if (ListBox1.Items[i].Selected)
                        {
                            if (!arrList1.Contains(ListBox1.Items[i]))
                            {
                                arrList1.Add(ListBox1.Items[i]);
                            }
                        }
                    }
                    for (int i = 0; i < arrList1.Count; i++)
                    {
                        if (!ListBox2.Items.Contains((ListItem)arrList1[i]))
                        {
                            ListBox2.Items.Add((ListItem)arrList1[i]);
                        }
                        ListBox1.Items.Remove((ListItem)arrList1[i]);
                    }
                    ListBox2.SelectedIndex = -1;
                    arrList1.Clear();
                }
                else
                {
                    lblMessage.Visible = true;
                    lblMessage.Text = "Please select atlest one list item for move";
                }
            }
            else
            {
                lblMessage.Visible = true;
                lblMessage.Text = "There is no items in listbox1";
            }
        }

        protected void btn2_Click(object sender, EventArgs e)
        {
            lblMessage.Visible = false;
            if (ListBox1.Items.Count > 0)
            {
                while (ListBox1.Items.Count != 0)
                {
                    for (int i = 0; i < ListBox1.Items.Count; i++)
                    {
                        ListBox2.Items.Add(ListBox1.Items[i]);
                        ListBox1.Items.Remove(ListBox1.Items[i]);
                    }
                }
            }
            else
            {
                lblMessage.Visible = true;
                lblMessage.Text = "There is no items in list box1 for move";
            }        
        }

        protected void btn3_Click(object sender, EventArgs e)
        {
            lblMessage.Visible = false;
            if (ListBox2.Items.Count > 0)
            {
                if (ListBox2.SelectedIndex >= 0)
                {
                    for (int i = 0; i < ListBox2.Items.Count; i++)
                    {
                        if (ListBox2.Items[i].Selected)
                        {
                            if (!arrList2.Contains(ListBox2.Items[i]))
                            {
                                arrList2.Add(ListBox2.Items[i]);
                            }
                        }
                    }
                    for (int i = 0; i < arrList2.Count; i++)
                    {
                        if (!ListBox1.Items.Contains((ListItem)arrList2[i]))
                        {
                            ListBox1.Items.Add((ListItem)arrList2[i]);
                        }
                        ListBox2.Items.Remove((ListItem)arrList2[i]);
                    }
                    ListBox1.SelectedIndex = -1;
                }
                else
                {
                    lblMessage.Visible = true;
                    lblMessage.Text = "Please select atleast one listItem for move";
                }
            }
            else
            {
                lblMessage.Visible = true;
                lblMessage.Text = "There is no listitem in List box2";
            }
        }

        protected void btn4_Click(object sender, EventArgs e)
        {
            lblMessage.Visible = false;
            if (ListBox2.Items.Count > 0)
            {
                while (ListBox2.Items.Count > 0)
                {
                    for (int i = 0; i < ListBox2.Items.Count; i++)
                    {
                        ListBox1.Items.Add(ListBox2.Items[i]);
                        ListBox2.Items.Remove(ListBox2.Items[i]);
                    }
                }
            }
            else
            {
                lblMessage.Visible = true;
                lblMessage.Text = "There is no items in list box2 for move";
            }
        }
    }
}

Saturday, 28 November 2015

Check Login details from Database using Asp.Net C#



protected void btnLogin_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection("server=.;database=DemoDB;integrated security=true");
            SqlCommand cmd = new SqlCommand("select * from tblLogin where Username=@UName and Password=@Pwd", con);
            cmd.Parameters.Add(new SqlParameter("@UName", txtUsername.Text));
            cmd.Parameters.Add(new SqlParameter("@Pwd", txtPassword.Text));
            con.Open();

            int NoOfRowsAffected = (int)cmd.ExecuteScalar();
            con.Close();

            if (NoOfRowsAffected > 0)
            {
                Response.Redirect("Homepage.aspx");
                //Server.Transfer("Homepage.aspx");
            }
            else
            {
                lblResult.ForeColor = System.Drawing.Color.Red;
                lblResult.Text = "Invalid User Name or password";
            }
        }

Monday, 23 November 2015

Use of ThreadStart delegate in C#

using System;
using System.Threading;
class Program
{
    static void Main()
    {
        ThreadStart ts = new ThreadStart(Test.DemoMethod);
        Thread t = new Thread(ts);
        t.Start();
    }
}
class Test
{
    public static void DemoMethod()
    {
        for (int i = 1; i <= 10; i++)
        {
            Console.WriteLine(i);
        }
    }
}

Simple Use of ThreadStart Delegate in C#

using System;
using System.Threading;
class Program
{
    static void Main()
    {
        Thread t = new Thread(new ThreadStart(Test.DemoMethod));
        t.Start();
    }
}
class Test
{
    public static void DemoMethod()
    {
        for (int i = 1; i <= 10; i++)
        {
            Console.WriteLine(i);
        }
    }
}

Simple Threading in C#

using System;
using System.Threading;
class Program
{
    static void Main()
    {
        Thread t = new Thread(Test.DemoMethod);
        t.Start();
    }
}
class Test
{
    public static void DemoMethod()
    {
        for (int i = 1; i <= 10; i++)
        {
            Console.WriteLine(i);
        }
    }
}

Wednesday, 4 November 2015

Verbatim String in C#

A String can be created as a verbatim string using @ symbol. Verbatim strings start with @ symbol. The C# compiler understand this type of string as verbatim. Basically the @ symbol tells the string constructor to ignore escape characters and line breaks.


using System;
class Program
{
    static void Main()
    {
        string str1 = "One\nTwo\nThree\nFour\nFive";
        //In statement above the compiler understand escape sequence', but if we write the code like this:

        string str2 = @"One\nTwo\nThree\nFour\nFive";
        //In statement above the compiler ignores escape sequence.

        Console.WriteLine(str1);
        Console.WriteLine("\n");
        Console.WriteLine(str2);
    }
}

Output:

One
Two
Three
Four
Five


One\nTwo\nThree\nFour\nFive



Saturday, 31 October 2015

Write a Program in C# to Validate Mobile Number using Regular Expressions.

using System;
using System.Text.RegularExpressions;
class Program
{
    static void Main()
    {
        Console.WriteLine("Enter your mobile number");
        string mobileNumber = Console.ReadLine();

        string MNregExp = @"^\+?\d{0,2}\-?\d{4,5}\-?\d{5,6}";

        if (Regex.IsMatch(mobileNumber, MNregExp))
        {
            Console.WriteLine("Mobile number is in correct format");
        }
        else
        {
            Console.WriteLine("Mobile number is in incorrect format");
        }
    }
}

Write a Program in C# using Regular Expressions to read IP Address from the user and validate it.

using System;
using System.Text.RegularExpressions;
class Program
{
    static void Main()
    {
        Console.WriteLine("Enter Your IP Address");
        string Ip = Console.ReadLine();

        string ipregex= @"^(([01]?\d\d?|2[0-4]\d|25[0-5])\.){3}([01]?\d\d?|25[0-5]|2[0-4]\d)$";

        if (Regex.IsMatch(Ip, ipregex))
        {
            Console.WriteLine("You entered ip address in correct format");
        }
        else
        {
            Console.WriteLine("ip address in invalid format");
        }
    }
}

Write a Program in C# using Regular Expressions to read an Email from the user and validate it.

using System;
using System.Text.RegularExpressions;
class Program
{
    static void Main()
    {
        Console.WriteLine("Enter your email id");
        string email = Console.ReadLine();
        string regExpEmail= @"^((([\w]+\.[\w]+)+)|([\w]+))@(([\w]+\.)+)([A-Za-z]{1,3})$";

        if (Regex.IsMatch(email, regExpEmail))
        {
            Console.WriteLine("Email in Correct format");
        }
        else
        {
            Console.WriteLine("Invalid Email format");
        }
    }
}

Regular Expressions in C#

Regular Expressions
Regular expressions are Patterns that can be used to match strings. We can call it a formula for matching strings that follow some pattern. Regular expression(s) can be considered as a Language, which is designed to manipulate text.

Regular Expressions may be used to find one or more occurrences of a pattern of characters within a string. You may choose to replace it with some other characters or perform some other tasks based on the results obtained. These patterns of characters can be simple or very complex. Regular Expressions generally comprises of two types of characters -
  1. Literal or Normal Characters such as "abcd123"
  2. Special Characters that have a special meaning such as "." Or "$" or "^" 
Due to the special characters Regular Expressions form a very powerful means of manipulating strings and text.

Meta-characters and their Description


.

Matches any single character. An example of this is the regular expression s.t would match the strings sat, sit, but not sight.

$

Matches the end of a line. For instance, the regular expression reason$ would match the end of the string "He has a reason" but not the string "He has his reasons"

^

Matches the beginning of a line. For instance, the regular expression ^Where would match the beginning of the string "Where is my cap" but would not match "Do you know Where it is " .

*

Matches zero or more occurrences of the character immediately preceding. For example, the regular expression .* means match any number of any characters.

[ ]


[c1-c2]



 
[^c1-c2]
·         Matches any one of the characters between the brackets.
For example, the regular expression s[ia]t matches sat, sit, but not set.
·         Ranges of characters can specified by using a hyphen.
For example, the regular expression [0-9] means match any digit. Multiple ranges can be specified as well. The regular expression [A-Za-z] means match any upper or lower case letter.

·         To match any character except those in the range, the complement range, use the caret as the first character after the opening bracket.
For example, the expression [^123a-z] will match any characters except 1,2, 3, and lower case letters.

|

Or two conditions together. For example (him|her) matches the line "it belongs to him" and matches the line "it belongs to her" but does not match the line "it belongs to them."

+

Matches one or more occurrences of the character or regular expression immediately preceding. For example, the regular expression 9+ matches 9, 99, 999.

?

Matches 0 or 1 occurrence of the character or regular expression immediately preceding.

{i}




{i,j}
·         Match a specific number of instances or instances within a range of the preceding character.
For example, the expression A[0-9]{3} will match "A" followed by exactly 3 digits. That is, it will match A123 but not A1234.

·         The expression [0-9]{4,6} any sequence of 4, 5, or 6 digits

\d Matches a digit character. Equivalent to [0-9].

\D Matches a non-digit character. Equivalent to [^0-9].

\w Matches any word character including underscore. Equivalent to "[A-Za-z0-9_]".

 \W Matches any non-word character. Equivalent to "[^A-Za-z0-9_]".

\b Matches a word boundary, that is, the position between a word and a space. For example, "er\b" matches the "er" in "never" but not the "er" in "verb".
\B Matches a non-word boundary. "ea*r\B" matches the "ear" in "never early".

Sunday, 18 October 2015

String.Trim(), String.TrimStart() and String.TrimEnd() Methods in String in C#

using System;
class Program
{
    static void Main()
    {
        string s = "     rao12345@gmail.com     ";
        //Trim() removes white space from Beginning and end of the string
        Console.WriteLine(s.Trim()+"Done");
        //TrimStart() removes white space from Beginning of the string
        Console.WriteLine(s.TrimStart() + "Done");
        //TrimEnd() removes white space from end of the string
        Console.WriteLine(s.TrimEnd() + "Done");
    }
}

Friday, 16 October 2015

Lower case, Upper case and Substring in string in C#

using System;
class Program
{
    static void Main()
    {
        string str = "inDia Is mY CoUnTrY";
        Console.WriteLine("Displaying same input string\n");
        Console.WriteLine(str);
        Console.WriteLine("\nCalling ToLower instance method which creates new copy in lower case\n");
        Console.WriteLine(str.ToLower());
        Console.WriteLine("\nCalling ToUpper instance method which creates new copy in Upper case\n");
        Console.WriteLine(str.ToUpper());
        Console.WriteLine("\nCalling Substring instance method to start from 5th index and retrieve rest of string");
        Console.WriteLine(str.Substring(5));
        Console.WriteLine("\nCalling Substring instance method to start from 0 index to 5 length");
        Console.WriteLine(str.Substring(0, 5));
    }
}

Split a string array in C#

using System;
class Program
{
    static void Main()
    {
        string str = "India is my country";
        string[] splitArray = str.Split();
        foreach (string s in splitArray)
        {
            Console.WriteLine(s);
        }
    }
}


/*
Output :-

 India
 is
 my
 country
*/

input from user in Jagged Array Demonstration in C#

using System;
class Program
{
    static void Main()
    {
        Console.WriteLine("Please enter the number of element");
        int NoOfElement = int.Parse(Console.ReadLine());
        int[][] jaggedArray = new int[NoOfElement][];
        Console.WriteLine("Initializing each element in Jagged Array");
        for (int i = jaggedArray.GetLowerBound(0); i <= jaggedArray.GetUpperBound(0); i++)
        {
            Console.WriteLine("Please Enter the number of element in Row : {0}", i + 1);
            int colsize = int.Parse(Console.ReadLine());
            jaggedArray[i] = new int[colsize];
            Console.WriteLine("Reading Data in Jagged Array");
            for (int j = jaggedArray[i].GetLowerBound(0); j <= jaggedArray[i].GetUpperBound(0); j++)
            {
                Console.WriteLine("Please enter the value [{0} {1}]",i,j);
                jaggedArray[i][j] = int.Parse(Console.ReadLine());
            }
        }
        Console.Clear();
        Console.WriteLine("Displaying the jagged array Element");

        foreach (int[] elementArray in jaggedArray)
        {
            foreach (int element in elementArray)
            {
                Console.Write(element + "\t");
            }
            Console.WriteLine("\n");
        }
       
    }
}

simple Jagged Array Demonstration in C#

using System;
class Program
{
    static void Main()
    {
        int[][] jaggedArray = new int[5][];
        jaggedArray[0] = new int[6] { 1, 2, 3, 4, 5, 6 };
        jaggedArray[1] = new int[3] { 1, 2, 3 };
        jaggedArray[2] = new int[5] { 1, 2, 3, 4, 5 };
        jaggedArray[3] = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        jaggedArray[4] = new int[1] { 1 };

        foreach (int[] elementArray in jaggedArray)
        {
            foreach (int i in elementArray)
            {
                Console.Write(i + "\t");
            }
            Console.WriteLine("\n");
        }
    }
}

Jagged Array in C#

Jagged Arrays (array-of-arrays)

A jagged array is an array of arrays. Each element in jagged array act as an array. The elements of a jagged array can be of different dimensions and sizes. A jagged array is sometimes called an "array of arrays."

A special type of array is introduced in C#. A Jagged Array is an array of an array in which the length of each array index can different.

Example:

int[][] jaggedArray = new int[5][];

In the above declaration the rows are fixed in size. But columns are not specified as they can vary.

Declaring and initializing jagged array.

int[][] jaggedArray = new int[5][];

jaggedArray[0] = new int[5];

jaggedArray[1] = new int[6];

jaggedArray[2] = new int[2];

jaggedArray[3] = new int[4];

jaggedArray[4] = new int[10];


jaggedArray[0] = new int[] { 2, 3, 5, 7, 9 };

jaggedArray[1] = new int[] { 7, 1, 0, 2, 4, 6 };

jaggedArray[2] = new int[] { 2, 6 };

jaggedArray[3] = new int[] { 2, 4, 6, 45 };

jaggedArray[4] = new int[] { 4, 6, 43, 45, 76, 78, 17, 18, 22, 26, 12 };

You can also initialize the array upon declaration like this:

int[][] jaggedArray = new int[][]
{
new int[] { 2, 3, 5, 7, 9 },

new int[] { 7, 1, 0, 2, 4, 6 },

new int[] { 2, 6 },

new int[] { 2, 4, 6, 45 },

new int[] { 4, 6, 43, 45, 76, 78, 17, 18, 22, 26, 12 }
};

You can use the following shorthand form:

int[][] jaggedArray =
{
new int[] { 2, 3, 5, 7, 9 },

new int[] { 7, 1, 0, 2, 4, 6 },

new int[] { 2, 6 },

new int[] { 2, 4, 6, 45 },

new int[] { 4, 6, 43, 45, 76, 78, 17, 18, 22, 26, 12 }
};

Calculating the sum of a Digits in C#

using System;
class Program
{
    static void Main()
    {
        int sum = 0;
        Console.WriteLine("Enter a Number");
        int Number = int.Parse(Console.ReadLine());
        int temp = Number;
        while (temp > 0)
        {
            sum = sum + (temp % 10);
            temp = temp / 10;
        }
        Console.WriteLine("Sum of {0} Digit is : {1}",Number,sum);

    }
}

How to create non zero index based Array in C#

using System;
class program
{
    static void Main()
    {
        int[] lowerBound = { 2015, 10 };
        int[] length = { 3, 3 };
        int[,] testArray=(int[,])Array.CreateInstance(typeof(int),length,lowerBound);
       
     
        for (int i = testArray.GetLowerBound(0); i <= testArray.GetUpperBound(0); i++)
        {
            for (int j = testArray.GetLowerBound(1); j <= testArray.GetUpperBound(1); j++)
            {
                Console.WriteLine("Enter the Data [{0} {1}]",i,j);
                testArray[i, j] = int.Parse(Console.ReadLine());

            }
        }
        for (int i = testArray.GetLowerBound(0); i <= testArray.GetUpperBound(0); i++)
        {
            for (int j = testArray.GetLowerBound(1); j <= testArray.GetUpperBound(1); j++)
            {
                Console.Write("{0:C}" + "\t", testArray[i, j]);
            }

            Console.WriteLine("\n");
        }
    }
}



Perform Addition, Substraction, Multiplication of two Matrices using two Dimensional (2D) Array in C#

using System;
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter the Row size of Array");
            int rowsize = int.Parse(Console.ReadLine());
            Console.WriteLine("Enter the column size of array");
            int colsize = int.Parse(Console.ReadLine());
            int[,] Matrix1=new int[rowsize,colsize];

            for (int i = Matrix1.GetLowerBound(0); i <= Matrix1.GetUpperBound(0); i++)
            {
                for (int j = Matrix1.GetLowerBound(1); j <= Matrix1.GetUpperBound(0); j++)
                {
                    Console.WriteLine("Enter Data of Matrix1 [{0} {1}]",i,j);
                    Matrix1[i, j] = int.Parse(Console.ReadLine());
                }
            }
            int[,] Matrix2 = new int[rowsize, colsize];
            for (int i = Matrix2.GetLowerBound(0); i <= Matrix2.GetUpperBound(0); i++)
            {
                for (int j = Matrix2.GetLowerBound(1); j <= Matrix2.GetUpperBound(0); j++)
                {
                    Console.WriteLine("Enter Data of Matrix2 [{0} {1}]", i, j);
                    Matrix2[i, j] = int.Parse(Console.ReadLine());
                }
            }
            Console.Clear();
            Console.WriteLine("\n Displaying the Data of Matrix1 \n");
            for (int i = Matrix1.GetLowerBound(0); i <= Matrix1.GetUpperBound(0); i++)
            {
                for (int j = Matrix1.GetLowerBound(1); j <= Matrix1.GetUpperBound(0); j++)
                {
                    Console.Write(Matrix1[i, j] + "\t");
                }
                Console.WriteLine("\n");
            }
            Console.WriteLine("\n Displaying the Data of Matrix2 \n");
            for (int i = Matrix2.GetLowerBound(0); i <= Matrix2.GetUpperBound(0); i++)
            {
                for (int j = Matrix2.GetLowerBound(1); j <= Matrix2.GetUpperBound(0); j++)
                {
                    Console.Write(Matrix2[i,j]+"\t");
                }
                Console.WriteLine("\n");
            }
            int[,] Matrix3 = new int[rowsize, colsize];
            Console.WriteLine("Press 1 for Addition");
            Console.WriteLine("Press 2 for Substraction");
            Console.WriteLine("Press 3 for Multiplication");
            int userChoice = int.Parse(Console.ReadLine());
            switch (userChoice)
            {
           
                case 1:
                    Console.WriteLine("\n Addition of Matrix1 and Matrix2 \n");
            for (int i = Matrix3.GetLowerBound(0); i <= Matrix3.GetUpperBound(0); i++)
            {
                for (int j = Matrix3.GetLowerBound(1); j <= Matrix3.GetUpperBound(0); j++)
                {
                    Matrix3[i, j] = Matrix1[i, j] + Matrix2[i, j];
                    Console.Write(Matrix3[i, j] + "\t");
                }
                Console.WriteLine("\n");
            }
                    break;
                case 2:
                    Console.WriteLine("\n Substraction of Matrix1 and Matrix2 \n");
            for (int i = Matrix3.GetLowerBound(0); i <= Matrix3.GetUpperBound(0); i++)
            {
                for (int j = Matrix3.GetLowerBound(1); j <= Matrix3.GetUpperBound(0); j++)
                {
                    Matrix3[i, j] = Matrix1[i, j] - Matrix2[i, j];
                    Console.Write(Matrix3[i, j] + "\t");
                }
                Console.WriteLine("\n");
            }
            break;
                case 3:
                    Console.WriteLine("\n Multiplication of Matrix1 and Matrix2 \n");
            for (int i = Matrix3.GetLowerBound(0); i <= Matrix3.GetUpperBound(0); i++)
            {
                for (int j = Matrix3.GetLowerBound(1); j <= Matrix3.GetUpperBound(0); j++)
                {
                    Matrix3[i, j] = Matrix1[i, j] * Matrix2[i, j];
                    Console.Write(Matrix3[i, j] + "\t");
                }
                Console.WriteLine("\n");
            }
            break;
                default:
            Console.WriteLine("You entered invalid Option... Plz try again...");
            break;
            }
           
        }
    }