Friday 24 August 2012

Substring() in C#

Example On String Substring() method.


Substring in C# string Class returns a new string that is a substring of this string. The substring begins at the specified given index and extended up to the given length.

Syntax : string string.substring(int startIndex,int length)


Parameters:

startIndex: The index of the start of the substring.
length: The number of characters in the substring.



public class SubstringExample
      {
            public static void Main()
            {                
                  string str = null;
                  string SubStr = null;
                  str = "Dotnet Masty Substring Example";
                  SubStr = str.Substring(7, 15);

                  Console.WriteLine(SubStr);               
                  Console.ReadLine();
            }
      }

Thursday 23 August 2012

String Copy() and CopyTo() in C#

Example on String Copy() and CopyTo() Method.

Copy() :

CSharp String Copy method is create a new String object with the same content.
Syntax: string string.Copy(string str)


Parameters:
String str : The argument String for Copy method.




CopyTo() :

CSharp string CopyTo method Copies a specified number of characters from a specified position in this instance to a specified position in an array of characters.

Syntax: void string.CopyTo(int sourceIndex,char[] destination,  int destinationindex,int count)

Parameters:
int sourceIndex : The starting position of the source String
char[] destination : The character Array
int destinationindex : Array element in the destination
int count : The number of characters to destination


public class StringCopy&CopyToExample
      {
            public static void Main()
            {
                  //Copy() Methode
                  string strCopy1 = null;
                  string strCopy2 = null;

                  strCopy1 = "C# Copy() Method test";
                  strCopy2 = string.Copy(strCopy1);
                  Console.WriteLine(strCopy2);
                  //MessageBox.Show(str2);
                 
                  //CopyTo() Methode
                  string strTo = "C#CopyTo() sample";
                  char[] chrs = new char[5];
                  strTo.CopyTo(0, chrs, 0, 5);
                 
                  Console.WriteLine(chrs[0].ToString() + chrs[1].ToString() + chrs[2].ToString()+ chrs[3].ToString()  + chrs[4].ToString() + chrs[5].ToString());
           
                  Console.ReadLine();
            }
      }

String Clone() in C#

Example on String Clone() Method.


The C# String Clone() method creates and returns a copy of string object. This methode returns a reference to this instance of string.


public class StringCloneExample
      {
            public static void Main()
            {
                  string Str = "Clone Methode Testing";
                  string StrCloned = null;
                  StrCloned = (String)Str.Clone();
                  Console.WriteLine(StrCloned);
                  Console.ReadLine();
            }
      }

String Split in C#

Example on Split String using C#



C# string Split function returns an array of String containing the substrings delimited by the given System.Char array.



public class StringSplitExample
      {
            public static void Main()
            {
                  string str = null;
                  string[] strArr = null;
                  int count = 0;
                  str = "Dot Net Masty";
                  char[] splitchar = { ' ' };
                  strArr = str.Split(splitchar);
                  for (count = 0; count <= strArr.Length - 1; count++)
                  {
                        Console.WriteLine(strArr[count]);                    
                  }
                  Console.ReadLine();
            }
      }

String.Compare Methods in C#

Different types of String Compare Methods Examples 

public class StringCompareExample
      {
            public static void Main()
            {
                  string s1 = "Dot\u00ADNet"; // '\u00AD' Unicode Character 'SOFT HYPHEN'
                  string s2 = "DotNet";                    
                  Console.WriteLine("Comparison of '{0}' and '{1}': {2}", s1, s2, String.Compare(s1, s2, true));           
                 
                  Console.WriteLine("2nd Example : ");
                  String MyString = "Hello World1";
                  String OtherString = "Hello World";
                  int MyInt = MyString.CompareTo(OtherString);
                  Console.WriteLine( MyInt );
                 
                  Console.WriteLine("3rd Example : ");
                  string MyString1 = "Hello World";
                  string YourString = "Hello World1";
                  Console.WriteLine(String.Equals(MyString1, YourString));

                  Console.WriteLine("4th Example : ");
                  string MyString2 = "Hello World";
                  Console.WriteLine(MyString2.StartsWith("Hello"));
                 
                  // String.Compare Methods
                  Console.WriteLine("5th Example : ");
                  string str1 = null;
                  string str2 = null;
                 
                  str1 = "csharp";
                  str2 = "CSharp";
                 
                  int result = 0;
                 
                  result = string.Compare(str1, str2);
                  Console.WriteLine(result.ToString());                
                 
                  result = string.Compare(str1, str2, true);                 
                  Console.WriteLine(result.ToString());
                 
                  result = string.Compare(str1, str2, false);                
                  Console.WriteLine(result.ToString());
                 
                  Console.ReadLine();
            }
      }

Differences in string compare methods using C#



Different types of String Compare methods


public class Example
      {
            public static void Main()
            {
                  string testString1 = "String1";
                  string testString2 = "String2";

                  if (testString1.CompareTo(testString2) == 0) //or 1
                  {
                        //Condition
                  }
                  if (testString1.Equals(testString2))
                  {
                        //Condition
                  }
                  if (testString1 == testString2)
                  {
                        //Condition
                  }
                  Console.ReadLine();
            }
      }

Friday 8 June 2012

LINQ To SQL Insert,Update,Delete

The process of inserting updating and deleting from LinQ to SQL.

Create Database name (LINQ2SQL)


USE [LINQ2SQL]

CREATE TABLE [dbo].[Department](
      [Id] [int] IDENTITY(1,1) NOT NULL,
      [DeptName] [varchar](50) NULL,
 CONSTRAINT [PK_Department] PRIMARY KEY CLUSTERED
(
      [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Employee]    Script Date: 06/08/2012 16:05:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Employee](
      [Id] [int] IDENTITY(1,1) NOT NULL,
      [EmpName] [varchar](50) NULL,
      [Salary] [varchar](50) NULL,
      [DeptId] [int] NULL,
 CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED
(
      [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  ForeignKey [FK_Employee_Department]    Script Date: 06/08/2012 16:05:13 ******/
ALTER TABLE [dbo].[Employee]  WITH CHECK ADD  CONSTRAINT [FK_Employee_Department] FOREIGN KEY([DeptId])
REFERENCES [dbo].[Department] ([Id])
GO
ALTER TABLE [dbo].[Employee] CHECK CONSTRAINT [FK_Employee_Department]
GO


Creating a LINQ 2 SQL class to Map Tables

  • Take One Class Library from New Projects name it as DAL.
  • Right click on project  from solution explorer and Add New Item LINQ to SQL Classes
  • Create connection from Server Explorer by right click on the data connection and drag and drop the tables.
  • Build The application.


Implementing the LinQ through Code Behind

  • Take One Web Application from New Projects.
  • Right click on the Project from solution explorer and click on Add References.
  • And Select the builded DAL application's DAL.dll file from Browse -> DAL  -> Bin -> Debug-> DAL.dll.

in Default.aspx page.


<table border="2" cellspacing="5" cellpadding="5" width="70%">
        <tr>
            <td align="right">
                DepartMent Name
            </td>
            <td>
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td align="right">
                </td>
            <td>
                <asp:Button ID="Button1" runat="server" Text="Save" Width="100" OnClick="Button1_Click" />
            </td>
        </tr>
        <tr>
            <td align="right">
                Department
            </td>
            <td>
                <asp:DropDownList ID="DropDownList1" runat="server" Width="130px" AutoPostBack="True">
                </asp:DropDownList>
            </td>
        </tr>
        <tr>
            <td align="right">
                Employee Name
            </td>
            <td>
                <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                <asp:HiddenField ID="HiddenField1" runat="server" />
            </td>
        </tr>
        <tr>
            <td align="right">
                Employee Sal
            </td>
            <td>
                <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td align="right">
                <asp:Button ID="Button2" runat="server" Text="Save" Width="100" OnClick="Button2_Click" />
            </td>
            <td>
                <asp:Button ID="Button3" runat="server" Text="Update" Width="100" OnClick="Button3_Click" />
                <asp:Button ID="Button4" runat="server" Text="Delete" Width="100" OnClick="Button4_Click" />
            </td>
        </tr>
    </table>
    </br>
    <asp:GridView ID="GridView1" runat="server" Width="487px" AutoGenerateSelectButton="True"
        OnSelectedIndexChanged="GridView1_SelectedIndexChanged" CellPadding="4"
        ForeColor="#333333" GridLines="None">
        <AlternatingRowStyle BackColor="White" />
        <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
        <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
        <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
        <SortedAscendingCellStyle BackColor="#FDF5AC" />
        <SortedAscendingHeaderStyle BackColor="#4D0000" />
        <SortedDescendingCellStyle BackColor="#FCF6C0" />
        <SortedDescendingHeaderStyle BackColor="#820000" />
    </asp:GridView>


in Default.aspx.cs page.

  • Add the Namespace DAL
         using DAL;

    using System.Linq;

    public partial class _Default : System.Web.UI.Page
    {

         ExampleDALDataContext contextVar = new ExampleDALDataContext();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                fillDropdown();
                FillGrid();
            }
        }
        // Adding The Department in DB
        protected void Button1_Click(object sender, EventArgs e)
        {
            Department depart = new Department()
            {
                DeptName = TextBox1.Text
            };
            contextVar.Departments.InsertOnSubmit(depart);
            contextVar.SubmitChanges();

            fillDropdown();
            TextBox1.Text = string.Empty;
        }
        // Inserting the Employee Details in Employee Table
        protected void Button2_Click(object sender, EventArgs e)
        {
            Employee empy = new Employee()
            {
                DeptId = int.Parse(DropDownList1.SelectedValue),
                EmpName = TextBox2.Text,
                Salary = TextBox3.Text
            };
            contextVar.Employees.InsertOnSubmit(empy);
            contextVar.SubmitChanges();
            TextBox3.Text = string.Empty;
            TextBox2.Text = string.Empty;

            FillGrid();
        }
        // Updating the Employee Details in Employee Table
        protected void Button3_Click(object sender, EventArgs e)
        {
            var EditEmp = contextVar.Employees.Single(x => x.Id == int.Parse(HiddenField1.Value));
            EditEmp.DeptId = int.Parse(DropDownList1.SelectedValue);
            EditEmp.EmpName = TextBox2.Text;
            EditEmp.Salary = TextBox3.Text;
            contextVar.SubmitChanges();
            TextBox3.Text = string.Empty;
            TextBox2.Text = string.Empty;
            FillGrid();
        }

        // Deleting the Employee Details in Employee Table
        protected void Button4_Click(object sender, EventArgs e)
        {
            var DeleteEmp = contextVar.Employees.Single(x => x.Id == int.Parse(HiddenField1.Value));
            contextVar.Employees.DeleteOnSubmit(DeleteEmp);
            contextVar.SubmitChanges();
            TextBox3.Text = string.Empty;
            TextBox2.Text = string.Empty;
            FillGrid();
        }

        void fillDropdown()
        {
            DropDownList1.Items.Clear();
            DropDownList1.DataSource = contextVar.Departments.OrderByDescending(x => x.Id);
            DropDownList1.DataTextField = "DeptName";
            DropDownList1.DataValueField = "Id";
            DropDownList1.DataBind();
        }

        void FillGrid()
        {
            var gdata = from ep in contextVar.Employees
                        select new
                        {
                            Id = ep.Id.ToString(),
                            Name = ep.EmpName,
                            Salary = ep.Salary,
                            Department = ep.Department.DeptName
                        };
            GridView1.DataSource = gdata;
            GridView1.DataBind();

        }

        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            HiddenField1.Value = GridView1.SelectedRow.Cells[1].Text;
            TextBox2.Text = GridView1.SelectedRow.Cells[2].Text;
            TextBox3.Text = GridView1.SelectedRow.Cells[3].Text;
        }
    }