Friday, 28 December 2012

Remove a backslash character from a string in C#

Remove a backslash character from a string in C# 




String str = "\"Hello\" \"World\"";

Console.WriteLine(str);

output: "Hello" "World";

Case1://Remove/replace  backslash with Empty char
str = str.Replace('"',' ');
Console.WriteLine(str);

output:Hello World

Case 2://Remove/replace  backslash with single quote '
str = str.Replace('"',@''');
Console.WriteLine(str);

output:  'Hello' 'World'


Friday, 21 December 2012

Find Current Culture in VB.NET


Find Current Culture in VB.NET


Dim t As System.Threading.Thread = System.Threading.Thread.CurrentThread 

'current culture datetime format
Console.WriteLine(t.CurrentCulture.DateTimeFormat.FullDateTimePattern)

'current culture  Name,display name and native name
Console.WriteLine(t.CurrentCulture.NativeName " "
                        t.CurrentCulture.EnglishName " "
                        t.CurrentCulture.DisplayName)

'current culture  Name,display name and native name
 Console.WriteLine(t.CurrentUICulture.NativeName " "  
                        t.CurrentUICulture.EnglishName " "  
                        t.CurrentUICulture.DisplayName)

Find Current Culture in C#

Find Current Culture in C#




System.Threading.Thread t=System.Threading.Thread.CurrentThread;

//current culture datetime format
Console.WriteLine(t.CurrentCulture.DateTimeFormat.FullDateTimePattern);

//current culture  Name,display name and native name
Console.WriteLine(t.CurrentCulture.NativeName+" "+t.CurrentCulture.EnglishName+" "+t.CurrentCulture.DisplayName);

//current culture  Name,display name and native name
 Console.WriteLine(t.CurrentUICulture.NativeName + " " + t.CurrentUICulture.EnglishName + " " + t.CurrentUICulture.DisplayName);

Thursday, 13 December 2012

Convert an Enum to String Vb.NET

Convert an Enum to String Vb.NET


Enum colors
    red
    blue
    green
End Enum


Private  Sub Convert_Enum_To_String()

         Dim strColor As String
         For Each strColor In Enum.GetNames(Type.GetType(colors))
             Console.WriteLine(strColor)
         Next

End Sub

Enum value type has Static method GetNames, Which will convert all enum constants to strings.

Convert an Enum to String C#

Convert an Enum to String C#


enum colors{red,blue,green};

private void Convert_Enum_To_String()
{
         foreach(String strColor in Enum.GetNames(typeof(colors)))
         {
             Console.WriteLine(strColor);
         }
}

Enum value type has Static method GetNames, Which will convert all enum constants to strings.

How to find odd and even numbers in VB.NET

How to find odd and even numbers in VB.NET

How to find odd and even numbers in Vb.NET

 

There are 2 methods find even or odd numbers inVB.NET

 

  Method 1: Modulus operator %

  Method 2:   BitField Operator &

Method 1:  Modulus Operator %

  Note:Find even or odd with modulus operator,When divided by 2 if remainder of the number is 0, then number is even otherwise odd.
    for  number 3  remainder is 1 so odd  3%2=1
    for number 4 remainder is 0 so even.  4 %2=0
Public Function isEven(ByVal num As Integer) As Boolean
           If num % 2 = 0 Then
                Return True
           Else If else Return False Then
           End If
 End Function
 

  Method 2:   BitField Operator &


        Public Function isEvenUsingBitFields(ByVal num As Int32) As Boolean
           If (num & 1) =0 Then
                Return True
           Else If else Return False Then
           End If
        End Function

 This examples uses bit operator And. If result is 0 then Even number, otherwise Odd Number.

How to find odd and even numbers in C#

How to find odd and even numbers in C#

 

There are 2 methods find even or odd numbers in C#.

 

  Method 1: Modulus operator %

  Method 2:   BitField Operator &

Method 1:  Modulus Operator %

  Note:Find even or odd with modulus operator,When divided by 2 if remainder of the number is 0, then number is even otherwise odd.
    for  number 3  remainder is 1 so odd  3%2=1
    for number 4 remainder is 0 so even.  4 %2=0

 public bool isEven(int num)
       {
           if (num % 2 == 0) return true;
           else return false;
       }

  Method 2:   BitField Operator &

       public bool isEvenUsingBitFields(Int32 num)
       {
           if ((num & 1) ==0) return true;
           else return false;
       }

 This examples uses bit operator And. If result is 0 then Even number, otherwise Odd Number.

Saturday, 8 December 2012

programatically add listbox items in visual Basic.NET


programatically add listbox items in visual Basic.NET

Create ListBox object add items to it, finally add it Controls list,

 Dim box As ListBox =  New ListBox()
            box.Width= 100
            box.Height=100
            box.Items.Add("Jan")
            box.Items.Add("Feb")
            box.Items.Add("Mar")
            box.Items.Add("Apr")
            box.Items.Add("Jun")
            box.Items.Add("Jul")
            box.Items.Add("Aug")
            box.Items.Add("Sep")
            box.Items.Add("Oct")
            box.Items.Add("Nov")
            box.Items.Add("Dec")

            Me.Controls.Add(box)

programatically add listbox items in visual C#

programatically add listbox items in visual C#

Create ListBox object add items to it, finally add it Controls list,

     ListBox box = new ListBox();
            box.Width= 100;
            box.Height=100;
            box.Items.Add("Jan");
            box.Items.Add("Feb");
            box.Items.Add("Mar");
            box.Items.Add("Apr");
            box.Items.Add("Jun");
            box.Items.Add("Jul");
            box.Items.Add("Aug");
            box.Items.Add("Sep");
            box.Items.Add("Oct");
            box.Items.Add("Nov");
            box.Items.Add("Dec");

            box.SelectedIndexChanged += box_SelectedIndexChanged;
            this.Controls.Add(box);
        }

        void box_SelectedIndexChanged(object sender, EventArgs e)
        {
            MessageBox.Show(((ListBox)sender).SelectedItem.ToString());
        }

Creating Master Details using DataGirdView in Winforms/VB.NET


How to Create Master Details using DataGirdView in Winforms/Visual C#


Creating Master  Details using DataGirdView in Winforms/VB.NET



Step1)  Add 2 datagridviews to same page

Step 2) Custom dataSet/Pragmatically Add DataSet
  • @ tables  1 for Employee Details
  • Second table has sales details for each Employee

Private  Sub builddataset()
 
dataset.Clear() 
If dataset.Tables.Count > 0 Then
dataset.Tables(01).Constraints.Clear() 
dataset.Tables(0).Constraints.Clear() 
 
 
End If
dataset.Tables.Clear() 
Dim table As DataTable =  New DataTable("SalesData") 
Dim id As DataColumn =  New DataColumn("ID",Type.GetType(System.Int64)) 
id.AutoIncrement = True 
id.AutoIncrementSeed = 100 
Dim salesman As DataColumn =  New DataColumn("Sales Name",Type.GetType(System.String)) 
Dim SalesManID As DataColumn =  New DataColumn("Emp ID",Type.GetType(System.Int32)) 
Dim yr2003 As DataColumn =  New DataColumn("2003",Type.GetType(System.Int32)) 
Dim yr2004 As DataColumn =  New DataColumn("2004",Type.GetType(System.Int32)) 
Dim yr2005 As DataColumn =  New DataColumn("2005",Type.GetType(System.Int32)) 
Dim yr2006 As DataColumn =  New DataColumn("2006",Type.GetType(System.Int32)) 
Dim yr2007 As DataColumn =  New DataColumn("2007",Type.GetType(System.Int32)) 
 
 
table.Columns.Add(id) 
table.Columns.Add(salesman) 
table.Columns.Add(yr2003) table.Columns.Add(yr2004) table.Columns.Add(yr2005) 
table.Columns.Add(yr2006) table.Columns.Add(yr2007) table.Columns.Add(SalesManID) 
 
 
Dim row As DataRow =  table.NewRow() 
row(1) = "Shayam" row(2) = 5000 row(3) = 6000 row(4) = 6000 row(5) = 8000 row(6) = 10000 row(7) = 11 
table.Rows.Add(row) 
row = table.NewRow() 
row(1) = "Benegal" row(2) = 8000 row(3) = 9000 row(4) = 10000 row(5) = 12000 row(6) = 14000 row(7) = 12 
table.Rows.Add(row) 
row = table.NewRow() 
row(1) = "Rowdy rathore" row(2) = 8000 row(3) = 9000 row(4) = 10000 row(5) = 12000 row(6) = 14000 row(7) = 13 
table.Rows.Add(row) 
 
 
row = table.NewRow() 
row(1) = "talaash" row(2) = 8000 row(3) = 9000 row(4) = 10000 row(5) = 12000 row(6) = 14000 row(7) = 14 
table.Rows.Add(row) 
 
 
 
 
Dim personalDetailsTbl As DataTable =  New DataTable("EmpDetails") 
Dim ID As DataColumn =  New DataColumn("ID",Type.GetType(System.Int32)) 
ID.AutoIncrement = True 
ID.AutoIncrementSeed = 11 
ID.ReadOnly = True 
Dim FirstName As DataColumn =  New DataColumn("FirstName",Type.GetType(System.String)) 
Dim LastName As DataColumn =  New DataColumn("LastName",Type.GetType(System.String)) 
Dim HireDate As DataColumn =  New DataColumn("HireDate",Type.GetType(System.DateTime)) 
Dim Dept As DataColumn =  New DataColumn("Department",Type.GetType(System.Int32)) 
Dim CTC As DataColumn =  New DataColumn("Cost to Company",Type.GetType(System.Single)) 
personalDetailsTbl.Columns.Add(ID)
personalDetailsTbl.Columns.Add(FirstName)
personalDetailsTbl.Columns.Add(LastName) 
personalDetailsTbl.Columns.Add(HireDate)
personalDetailsTbl.Columns.Add(Dept)
personalDetailsTbl.Columns.Add(CTC) 
personalDetailsTbl.Constraints.Add("PrimaryKey_EmpID", ID, True) 
Dim PersonalRow As DataRow =  personalDetailsTbl.NewRow() 
PersonalRow(1) = "Shyam" PersonalRow(2) = "Prasad"
PersonalRow(3) = New System.DateTime(2000, 10, 12) 
PersonalRow(4) = 10 PersonalRow(5) = 10000.33f 
personalDetailsTbl.Rows.Add(PersonalRow) 
PersonalRow = personalDetailsTbl.NewRow() 
PersonalRow(1) = "Benegal" PersonalRow(2) = "Prasad"
PersonalRow(3) = New System.DateTime(2012, 10, 12) 
PersonalRow(4) = 10 PersonalRow(5) = 11100.33f 
personalDetailsTbl.Rows.Add(PersonalRow) 
PersonalRow = personalDetailsTbl.NewRow() 
PersonalRow(1) = "Rowdy Rathore" PersonalRow(2) = "Kirshna"
PersonalRow(3) = New System.DateTime(1990, 10, 12) 
PersonalRow(4) = 10 PersonalRow(5) = 5555.55f 
personalDetailsTbl.Rows.Add(PersonalRow) 
PersonalRow = personalDetailsTbl.NewRow() 
PersonalRow(1) = "talaash" PersonalRow(2) = "Prasad"
PersonalRow(3) = New System.DateTime(1983, 10, 12) 
PersonalRow(4) = 10 PersonalRow(5) = 77677.77f 
personalDetailsTbl.Rows.Add(PersonalRow) 
 
 
dataset.Tables.Add(personalDetailsTbl) 
dataset.Tables.Add(table) 
 
 
Dim parentCol As DataColumn =  dataset.Tables("EmpDetails").Columns("ID") 
Dim childCol As DataColumn =  dataset.Tables("SalesData").Columns("Emp ID") 
Dim fconstraint As ForeignKeyConstraint =  New ForeignKeyConstraint(parentCol,childCol) 
'DataRelation relation = new DataRelation("foreign_key_id", parentCol, childCol); 
'relation.ParentTable.TableName = "EmpDetails"; 
'relation.ChildTable.TableName = "SalesData"; 
'dataset.Relations.Add(relation); 
fconstraInteger.UpdateRule = Rule.None 
fconstraInteger.DeleteRule = Rule.None 
fconstraInteger.AcceptRejectRule = AcceptRejectRule.None 
dataset.Tables(1).Constraints.Add(fconstraint) 
dataset.EnforceConstraints = True
End Sub


Step 3)  Mapping table columns and setting DataFieldValue
  as shown below

Step 4)  Add Button Control to Load dataSet and DataGridView1
  In Button Event Handler add following code

 Private  Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs)
'Programatically building the dataset with 2 tables employee +sales data
            builddataset()
 
'This is second approach to add datafield mapping or programatically mapping columns with DataProperty name ,defined in DataSet Table.
            dataGridView2.Columns(0).DataPropertyName = "Emp ID"
            dataGridView2.Columns(01).DataPropertyName = "Sales Name"
            dataGridView2.Columns(02).DataPropertyName = "2003"
            dataGridView2.Columns(03).DataPropertyName = "2004"
            dataGridView2.Columns(04).DataPropertyName = "2005"
            dataGridView2.Columns(05).DataPropertyName = "2006"
            dataGridView2.Columns(06).DataPropertyName = "2007"
            dataGridView1.DataSource = dataset.Tables(0)
 
 End Sub

Step 4)  In DataGridView add Event handler for "CellContentClick" 

Private  Sub dataGridView1_CellContentClick(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs)
  'Filter rows based on Emp ID.
'
            Dim cell As DataGridViewCell = dataGridView1.CurrentCell 
            Dim ChildRows As DataView =  New DataView(dataset.Tables(1),"[Emp ID]=" + cell.Value,"",DataViewRowState.CurrentRows) 
            dataGridView2.DataSource = ChildRows
End Sub

Step 5) Just Run the Program

Here is the OUTPUT


How to Create Master Details using DataGirdView in Winforms/Visual C#


How to Create Master  Details using DataGirdView in Winforms/Visual C#


Step1)  Add 2 datagridviews to same page

Step 2) Custom dataSet/Pragmatically Add DataSet
  • @ tables  1 for Employee Details
  • Second table has sales details for each Employee

        void builddataset()

        {


dataset.Clear();
if (dataset.Tables.Count > 0)
{
dataset.Tables[01].Constraints.Clear();
dataset.Tables[0].Constraints.Clear();


}
dataset.Tables.Clear();
DataTable table = new DataTable("SalesData");
DataColumn id = new DataColumn("ID", typeof(System.Int64));
id.AutoIncrement = true;
id.AutoIncrementSeed = 100;
DataColumn salesman = new DataColumn("Sales Name", typeof(System.String));
DataColumn SalesManID = new DataColumn("Emp ID", typeof(System.Int32));
DataColumn yr2003 = new DataColumn("2003", typeof(System.Int32));
DataColumn yr2004 = new DataColumn("2004", typeof(System.Int32));
DataColumn yr2005 = new DataColumn("2005", typeof(System.Int32));
DataColumn yr2006 = new DataColumn("2006", typeof(System.Int32));
DataColumn yr2007 = new DataColumn("2007", typeof(System.Int32));


table.Columns.Add(id);
table.Columns.Add(salesman);
table.Columns.Add(yr2003); table.Columns.Add(yr2004); table.Columns.Add(yr2005);
table.Columns.Add(yr2006); table.Columns.Add(yr2007); table.Columns.Add(SalesManID);


DataRow row = table.NewRow();
row[1] = "Shayam"; row[2] = 5000; row[3] = 6000; row[4] = 6000; row[5] = 8000; row[6] = 10000; row[7] = 11;
table.Rows.Add(row);
row = table.NewRow();
row[1] = "Benegal"; row[2] = 8000; row[3] = 9000; row[4] = 10000; row[5] = 12000; row[6] = 14000; row[7] = 12;
table.Rows.Add(row);
row = table.NewRow();
row[1] = "Rowdy rathore"; row[2] = 8000; row[3] = 9000; row[4] = 10000; row[5] = 12000; row[6] = 14000; row[7] = 13;
table.Rows.Add(row);


row = table.NewRow();
row[1] = "talaash"; row[2] = 8000; row[3] = 9000; row[4] = 10000; row[5] = 12000; row[6] = 14000; row[7] = 14;
table.Rows.Add(row);




DataTable personalDetailsTbl = new DataTable("EmpDetails");
DataColumn ID = new DataColumn("ID", typeof(System.Int32));
ID.AutoIncrement = true;
ID.AutoIncrementSeed = 11;
ID.ReadOnly = true;
DataColumn FirstName = new DataColumn("FirstName", typeof(System.String));
DataColumn LastName = new DataColumn("LastName", typeof(System.String));
DataColumn HireDate = new DataColumn("HireDate", typeof(System.DateTime));
DataColumn Dept = new DataColumn("Department", typeof(System.Int32));
DataColumn CTC = new DataColumn("Cost to Company", typeof(System.Single));
personalDetailsTbl.Columns.Add(ID);
personalDetailsTbl.Columns.Add(FirstName);
personalDetailsTbl.Columns.Add(LastName);
personalDetailsTbl.Columns.Add(HireDate);
personalDetailsTbl.Columns.Add(Dept);
personalDetailsTbl.Columns.Add(CTC);
personalDetailsTbl.Constraints.Add("PrimaryKey_EmpID", ID, true);
DataRow PersonalRow = personalDetailsTbl.NewRow();
PersonalRow[1] = "Shyam"; PersonalRow[2] = "Prasad";
PersonalRow[3] = new System.DateTime(2000, 10, 12);
PersonalRow[4] = 10; PersonalRow[5] = 10000.33f;
personalDetailsTbl.Rows.Add(PersonalRow);
PersonalRow = personalDetailsTbl.NewRow();
PersonalRow[1] = "Benegal"; PersonalRow[2] = "Prasad";
PersonalRow[3] = new System.DateTime(2012, 10, 12);
PersonalRow[4] = 10; PersonalRow[5] = 11100.33f;
personalDetailsTbl.Rows.Add(PersonalRow);
PersonalRow = personalDetailsTbl.NewRow();
PersonalRow[1] = "Rowdy Rathore"; PersonalRow[2] = "Kirshna";
PersonalRow[3] = new System.DateTime(1990, 10, 12);
PersonalRow[4] = 10; PersonalRow[5] = 5555.55f;
personalDetailsTbl.Rows.Add(PersonalRow);
PersonalRow = personalDetailsTbl.NewRow();
PersonalRow[1] = "talaash"; PersonalRow[2] = "Prasad";
PersonalRow[3] = new System.DateTime(1983, 10, 12);
PersonalRow[4] = 10; PersonalRow[5] = 77677.77f;
personalDetailsTbl.Rows.Add(PersonalRow);


dataset.Tables.Add(personalDetailsTbl);
dataset.Tables.Add(table);


DataColumn parentCol = dataset.Tables["EmpDetails"].Columns["ID"];
DataColumn childCol = dataset.Tables["SalesData"].Columns["Emp ID"];
ForeignKeyConstraint fconstraint = new ForeignKeyConstraint(parentCol, childCol);
//DataRelation relation = new DataRelation("foreign_key_id", parentCol, childCol);
//relation.ParentTable.TableName = "EmpDetails";
//relation.ChildTable.TableName = "SalesData";
//dataset.Relations.Add(relation);
fconstraint.UpdateRule = Rule.None;
fconstraint.DeleteRule = Rule.None;
fconstraint.AcceptRejectRule = AcceptRejectRule.None;
dataset.Tables[1].Constraints.Add(fconstraint);
dataset.EnforceConstraints = true;

        }

Step 3)  Mapping table columns and setting DataFieldValue
  as shown below

Step 4)  Add Button Control to Load dataSet and DataGridView1
  In Button Event Handler add following code
 private void button1_Click(object sender, EventArgs e)
        {
//Programatically building the dataset with 2 tables employee +sales data
            builddataset();
   
//This is second approach to add datafield mapping or programatically mapping columns with DataProperty name ,defined in DataSet Table.
            dataGridView2.Columns[0].DataPropertyName = "Emp ID";
            dataGridView2.Columns[01].DataPropertyName = "Sales Name";
            dataGridView2.Columns[02].DataPropertyName = "2003";
            dataGridView2.Columns[03].DataPropertyName = "2004";
            dataGridView2.Columns[04].DataPropertyName = "2005";
            dataGridView2.Columns[05].DataPropertyName = "2006";
            dataGridView2.Columns[06].DataPropertyName = "2007";
            dataGridView1.DataSource = dataset.Tables[0];
            
        }

Step 4)  In DataGridView add Event handler for "CellContentClick"


private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
  //Filter rows based on Emp ID.
//
            DataGridViewCell cell =dataGridView1.CurrentCell;
            DataView ChildRows= new DataView(dataset.Tables[1], "[Emp ID]=" + cell.Value, "", DataViewRowState.CurrentRows);
            dataGridView2.DataSource = ChildRows;
        }


Step 5) Just Run the Program

Here is the OUTPUT


Check for Leap year in VB.NET


Check for Leap year in VB.NET

How to determine whether a year is a leap year

To determine whether a year is a leap year, follow these steps:
  1. If the year is evenly divisible by 4, go to step 2. Otherwise, go to step 5.
  2. If the year is evenly divisible by 100, go to step 3. Otherwise, go to step 4.
  3. If the year is evenly divisible by 400, go to step 4. Otherwise, go to step 5.
  4. The year is a leap year (it has 366 days).
  5. The year is not a leap year (it has 365 days).
VB.NET Code

       Public Function isLeapYear(ByVal year As Integer) As Boolean
            Dim isLeap As Boolean =  True 
            If year % 4 = 0 Then
                If year % 100 = 0 Then
                 If year % 400 = 0 Then
                     Console.WriteLine("{0} is Leap Year", year)
                 End If
                Else If "{0} is Leap Year",year Then 
                End If
 
 
            Else 
                Console.WriteLine("{0} is not Leap Year", year)
                isLeap = False
            End If
 
            Return isLeap
       End Function


Check for Leap year in C#

Check for Leap year in C#


How to determine whether a year is a leap year

To determine whether a year is a leap year, follow these steps:
  1. If the year is evenly divisible by 4, go to step 2. Otherwise, go to step 5.
  2. If the year is evenly divisible by 100, go to step 3. Otherwise, go to step 4.
  3. If the year is evenly divisible by 400, go to step 4. Otherwise, go to step 5.
  4. The year is a leap year (it has 366 days).
  5. The year is not a leap year (it has 365 days).

C# Code

       public bool isLeapYear(int year)
        {
            bool isLeap = true;
            if (year % 4 == 0)
            {
                if (year % 100 == 0)
                {
                 if (year % 400 == 0)
                     Console.WriteLine("{0} is Leap Year", year);
                }
                else Console.WriteLine("{0} is Leap Year", year);


            }
            else
            {
                Console.WriteLine("{0} is not Leap Year", year);
                isLeap = false;
            }

            return isLeap;
        }

Thursday, 6 December 2012

String Concatenation in C#

String Concatenation in C#

Strings are immutable, so once it is created you cannot alter the content.

i.e String str="Hello";
     str[0]="G";   //will give compiler error.


String concatenations

Example 1
String str ="Hello";
  str = str+"World!";  
 //ouput HelloWorld!
//here new string object will be created, //previous reference will be released.

Example 2
---------------
   String str="Hello";
   String  nullStr=null;
   String  emptyStr=String.Empty;

Concatinating String with null values gives String

str = str+nullStr; //output: Hello


Concatinating String with Empty values gives String

str = str + emptyStr; //output: Hello

Example 3

Concatenating/joining multiple strings into single string using String.Concat


String strcat= String.Concat("Hello", "are ", " there?", " Where ", " are ", " u ", "going?");
Console.WriteLine(strcat);

Example 4


Concatenating/joining array values into single string using String.Concat   


String []strArr= new String[]{"Hello"," Are "," you "," there?"};

String strcat = String.Concat(strArr);  
//Output: Hello Are you there?

Add Integer/Single/Double to String 
String str2="Adding numbers to String";

str2 = str2 + 1;
           Console.WriteLine(str2);
           str2 = str2 + 1.1f;
           Console.WriteLine(str2);
           str2 = str2 + 2.0M;
           Console.WriteLine(str2);
           str2 = str2 + 2.2D;
           Console.WriteLine(str2);

/in above case no need of method  .ToString() to add int,single,double to string. Implicitely converted to String.


Concatenating
 String  with DateTime(Implicit conversion).

String str = "Time now is ";

str = str+DateTime.Now;

//output:
Time now is
 12/6/2014 11:40:19 AM





Sunday, 2 December 2012

send email with attachment using c#


Send email with attachment using C# through gmail.
sending email from C# through gmail
private void Send-EMail-through-Gmail()
{
                try
                {
                    System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587); ;
                    smtpClient.EnableSsl = true;
                    smtpClient.DeliveryFormat = System.Net.Mail.SmtpDeliveryFormat.International;
                    smtpClient.Credentials = new System.Net.NetworkCredential("YourgmailID", "Your gmail password");
                    System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
                    System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(@"C:\inetpub\wwwroot\Tutorials\CsharpSamples\DateOne.cs");
//just give file name, if u want specific files use System.IO.Stream object,

                    msg.Body="<h1>Pls see this code</h1>";
                    msg.IsBodyHtml=true; //set if your code contains html tags
                    msg.Priority = System.Net.Mail.MailPriority.High;
                    msg.Subject="pls see this code";
                    msg.SubjectEncoding = System.Text.Encoding.UTF8;
                    msg.To.Add("rockandhra.net@gmail.com"); //add as many you want 1 in eachline
                    msg.To.Add("xyz@yahoo.com");
                    msg.From = new System.Net.Mail.MailAddress("your from address","displayname");
                    msg.BodyEncoding = System.Text.Encoding.UTF8;
                 
//reply address in case you need to reply to someother e-mail address
                    msg.ReplyToList.Add("pzpurru@yahoo.com");
                  //attachment
                    msg.Attachments.Add(attachment);
                 

                    smtpClient.SendCompleted += new System.Net.Mail.SendCompletedEventHandler(smtpClient_SendCompleted);
//send e-mail asynchronously delegate will be called once send mail completes.
                    smtpClient.SendAsync(msg, "new e-mail");

                }
                catch (System.Net.Mail.SmtpException EX)
                {
                    Console.WriteLine(EX.Message);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
}
        static void smtpClient_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            try
            {
                if (e.Error != null)
                    Console.WriteLine(e.Error.InnerException.Message + ":" + e.Error.Message);
                else
                    Console.WriteLine("Message Sent");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

Tuesday, 30 October 2012

entity framework enum support | Enum Support in EF5

1)  Add new item to the Project "ADO.NET Entity Framework"
2) Name it as Projects.edmx
3) Add Properties to Project entity as shown below

5) Build the Project
6) Add Enum Entity to edmx file
            7)  Link Enum type to  Status Property as shown in the Enity
8)Build the Project

Model First in Entity Framework 5

Model First in Entity Framework 5


Step1)  Create a Console Project
Step 2) Add  New Item  --> select "ÄDO.NET Entity Framework" and name it as Hotel.edmx
   
Step 3)   Select Empty model , because you are going to generate SQL Tables based on Entities(Model First) you are going to create in step 4

Step 4) Add Entity from Toolbox  as shown below, Name it as Hotels

Step 5)   Right click on Edmx file
                  select Generate Database from Model... option

 Step 7)  Enter Database details with username & password/select windows authentication
              Select Existing database or Create new database using sqlcmd/Sql Management Studio.
  Note: Database name should exist.




Step 8)  Choose your database connection


Step 9)  Generate Database wizard with ur entity DDL commands
as shown below

Step 10)  Build the Project
Step 11)  Execute Hotel.edmx.sql  
Step 12)  Now Goto Sql server  and check DB Table corresponding to Hotel Entity created on selected database(Step 7)

Step 13) Open Hotel.Context.cs file
                You will find   DBcontext derived class with  HotelContainer

Step 14)  Open Program.cs file
                  Add following code

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {

            HotelContainer context1 = new HotelContainer();
            context1.Hotels.Add(new Hotels
            {
                 HotelName="mariott hotels",
                  Address="450 north mathilda",
                  City="Sunnyvale",
                   State="California",
                    ZipCode="94086",
                     Country="USA"
            });

            context1.SaveChanges();//save changes to database

            //Get hotel details from Database
            foreach (Hotels hotel in context1.Hotels)
            {
                Console.WriteLine(hotel.HotelName+"\t"+hotel.City+"\t"+hotel.Country);
            }

        }


Step 15) Output



Friday, 8 June 2012

Creating a Port Scanner in C#

Creating a Port Scanner in C#/List all occupied ports in a System



     IPGlobalProperties gp=System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties();
            Console.WriteLine("Computer Name={0}",gp.HostName);



            Console.WriteLine("TCP Active Listeners");
            foreach (IPEndPoint ipe in gp.GetActiveTcpListeners())
            {
                Console.WriteLine(ipe.Address+"\t\t"+ipe.AddressFamily+"\t\t"+ipe.Port);
            }
OUTPUT
List Active Tcp Active Connections  using C#
            IPGlobalProperties gp=System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties();
            Console.WriteLine("Computer Name={0}",gp.HostName);
            Console.WriteLine("TCP Active TCP Connections");
            foreach(TcpConnectionInformation tci in gp.GetActiveTcpConnections())
            {
                Console.WriteLine(tci.LocalEndPoint.Address + "\t\t" + tci.LocalEndPoint.AddressFamily + "\t\t" + tci.LocalEndPoint.Port);
            }

OUTPUT

Enumerate Files in a Directory using LINQ

List All files in a Directory using LINQ


            expr=System.IO.Directory.EnumerateFiles("C:\\");
            foreach (String file in expr)
            {
                Console.WriteLine(file);
            }

It displays complete path+filename.

Enumerate Directories using C#

list all directories  in C drive using C#


      var expr=System.IO.Directory.EnumerateDirectories(@"c:\");
            foreach (String file in expr)
            {
                Console.WriteLine(file);
            }

Tuesday, 5 June 2012

Dynamic Sized Arrays in C#

In Static Arrays Array size should be defined at compile time.  In some cases programmer may not know exact size of the array.  At that time, Programer can create dynamic arrays using following code.


       Array dynamicSizeArray= Array.CreateInstance(typeof(string), 2);
       dynamicSizeArray.SetValue("Hello",0);
       dynamicSizeArray.SetValue("World", 1);

       Console.Write(dynamicSizeArray.GetLength(0));
        Console .Write(dynamicSizeArray.GetUpperBound(0));

The above code Creates  an Single Dimensional Array of size 2  of type string.
0th location holds Hello
1st location holds World

GetLength method returns 2
GetUpperBound return 1.

Note: Programmer can create multi-dimenstional arrays using Array.CreateInstance method

Wednesday, 23 May 2012

IComparable Interface in c#

Sort by Price list;

Step 1)  Create console Application
Step 2) Add class called Stocks.cs  and implement IComparable interface

fileName: Stocks.cs

using System;
using System.Collections.Generic;
using System.Linq;


/// <summary>
/// Summary description for Stocks
/// </summary>
public class Stocks : IComparable
{
    public String Symbol;
    public decimal price;
    public DateTime dtPrice;

    public int CompareTo(object obj)
    {
        if (obj == null) return 1;
        Stocks st = obj as Stocks;
        return this.price.CompareTo(st.price);
    }
}

Step 3)  in Program.cs
             1)  Initialize array of objects(i.e stocks)
              2) display without sorting
             3) display after sorting

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            Stocks[] stockList =
    {
        new Stocks{Symbol="IBM", price=88.80M, dtPrice=new System.DateTime(2012,6,26,9,00,00)},
        new Stocks{Symbol="CSCO", price=22.80M, dtPrice=new System.DateTime(2012,6,26,9,00,00)},
        new Stocks{Symbol="INTL", price=32.80M, dtPrice=new System.DateTime(2012,6,26,9,00,00)},
 
    };

            Console.WriteLine("Before Sort ......");
            foreach (Stocks s in stockList)
            {
                Console.Write("Symbol={0},rate={1},date={2}",s.Symbol,s.price,s.dtPrice);
                Console.WriteLine();

            }

            Array.Sort(stockList); //sort arrays ,icomparable compare function will be called.

            Console.WriteLine("After Sort ......");
            foreach (Stocks s in stockList)
            {
                Console.Write("Symbol={0},rate={1},date={2}", s.Symbol, s.price, s.dtPrice);
                Console.WriteLine();

            }


        }
    }
}



OUTPUT








Saturday, 19 May 2012

Nullable types in .net

Nullable types in .net
Provides null values to value types(int,float,double,struct,enum)

Syntax:
int? i=null;  <==>  System.Nullable<int> i = null;
Integer i has all properties of default integer in addition to null value.

Partial classes in C#

Partial Classes in C#--> Partially define some methods in one file , add new methods to a class in another file, as shown below. it can be applied to class, struct or interface.

keyword: partial

file1.cs

namespace ConsoleApplication5
{
    public partial class Person
    {
        int Age;
        string Name;
        public Person(int age, string n)
        {
            Age = age;
            Name = n;
        }

        public bool isEligible() { if (Age > 18) return true; else return false; }
    }
}
file2.cs
namespace ConsoleApplication5
{
     public partial class Person
    {
         int pin;
         public Person(int p)
         {
             pin = p;
         }
         public bool isPinValid()
         {
             if (pin >100000 && pin > 999999) return false;
             else return true;
         }
     }
}

Program.cs(application Main file)

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person(20,"sitapati");
            Console.WriteLine(p.isEligible());
        }
    }
}