Wednesday, May 6, 2009

WORD,LINE,CHARACTER COUNTER IN C#


static void Main(string[] args)  {
  string str = "hello world\nmy name is sumair\n IV";
  int wordcount = 0,charcount = 0,linecount = 0;
  //calculating first line
  if (str != "")
  {
  linecount++;
  }
  for (int i = 0; i < 2; i++)
  {
  //calculating first and last word
  if ((str[0] >= 97 && str[0] <= 122) || (str[str.Length - 1] >= 97 && str[0] <= 122))
  {
  wordcount++;
  }
  }
  for (int i = 0; i < str.Length; i++)
  {
  if (str[i] == ' ')
  {
  wordcount++;
  }
  if ((str[i] >= 97 && str[i] <= 122) || (str[i] >= 65 && str[i] <= 91)) 
  {
  charcount++;
  }
  if (str[i] == '\n')
  {
  linecount++;
  }
  }
  Console.WriteLine("Total words are : "+wordcount+"\nTotal characters are : "+charcount+"\nTotal lines are : " + linecount);
  Console.ReadKey();
  }

Friday, April 17, 2009

EXTENSION METHODS

Extension methods allow developers to extends the functionality of an existing type without creating a new derived type.

Simple Extension Method Example:

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

namespace extmethods
{
  //This class Must be Public.
  // even sealed classes can extends by extension methods

  public sealed class human
  {
      public void eat()
    {
  Console.WriteLine("Eat Food");
   }
   
}
   
 ///


  /// This is my human Extensions class.This class must be static.
///

  public static class humanextension
  {
  /// This is our extension method for the human class.The first argument of a class extension should always be named "this" and should have the Type of the Type you want to extend.In this example class human is being Extend.Thats why argumentof the method contains this human objectname.This method must be static.
 
   
    public static void eatpkfood(this human h) 
   {
    Console.WriteLine("Eat Pak Food");
   }

}
  class Program
 {
  static void Main(string[] args)
    {
  human extmethod = new human();

 /// The following line used the "eatpkfood" extension method.You can see that object of human class acesses the method of humanextension  class.

 extmethod.eatpkfood();

//This line invokes the "eatpkfood" method of humanextension class.

humanextension.eatpkfood(extmethod);
 Console.Read();
    }
 }
}

OUTPUT:

Eat Pak Food

Eat Pak Food




ADO.NET (PART 7)


         HOW TO LOGIN THROUGH DATABASE 

DATABASE:
NAME = Northwind.

TABLE :
NAME = Login.

FIELDS:

username,password.


private void BtnLogin_Click(object sender, EventArgs e)
  {
  SqlConnection cn = new SqlConnection("Data Source=.;Initial Catalog=Northwind;Integrated Security=True");
  SqlDataAdapter da = new SqlDataAdapter("select * from login", cn);
  SqlCommand cmd = new SqlCommand();
  cmd.Connection= cn;
  cmd.CommandText = "select *from login where username = '" + txtUser.Text + " ' and password = '" + txtPwd.Text + "'";
  cmd.Connection.Open();
  SqlDataReader dr;
  dr=cmd.ExecuteReader();
  if(dr.Read())
  {
  Form1 f = new Form1();
  f.Show();
  this.Hide();
  }
  else
  {
  MessageBox.Show( "Invalid UserName or Password!!","invalid");
  }

}

Tuesday, April 14, 2009

ANONYMOUS TYPES

VAR keyword specifies a special anonymous type which can specifies all the types likeinteger,float,strings and even classes.Anonymous Types are the syntactic sugar basically.This Can also be done With Methods Then we Call it anonymous methods.

using System;
using System.Collections.Generic;
using System.Text;

namespace ANONYMOUSTYPES
{
  class Program
  {
  static void Main(string[] args)
  {
   
  // due to var keyword Compiler itself make classes of following objects.
   
  var student1 = new { name = "sumair", fathername = "irshad", age = 20 };
  var student2 = new { name = "andrew", fathername = "Hejisberg", age = 20 };
  var teacher = new { name = "BillGates", company = "Microsoft" };
  //now compiler will define myint as integer.
  var myint =4;
  //now compiler will define mystring as string.
  var mystring = "csharp";
  Console.WriteLine("STUDENTS:\n NAME = "+student1.name+" FATHERNAME = "+student1.fathername+"AGE ="+student1.age);
  Console.WriteLine(" NAME = "+student2.name+" FATHERNAME = "+student2.fathername+"AGE ="+student2.age);
  Console.WriteLine("\nTEACHER:\n NAME = " + teacher.name + "\n COMPANY = " + teacher.company);
  Console.WriteLine("\nSTRING = {0} \nINTEGER = {1}", mystring,myint);
  Console.ReadKey();
  }
  }
}
OutPut:

STUDENTS:

 NAME = sumair  FatherName = irshadAge= 20
 NAME = andrew FatherName = HejisbergAge= 20

TEACHER:

  NAME = BillGates

  Company = Microsoft

 STRING = csharp

INTEGER = 4

 

Monday, April 13, 2009

LINQ TO OBJECTS

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

namespace linq
{
public class student
{
public int id { get; set; }
public string name { get; set; }
public string fname { get; set; }
public List<int> scores;
}
class Program
{
static List<student> students = new List<student>
{
new student{id = 1,name = "sumair",fname ="irshad",scores = new List<int>{90,80,70,60}},
new student{id = 2,name = "JIMM",fname = "CARRY",scores = new List<int>{90,30,30,30}},
new student { id = 3 ,name = "ANDREW", fname = "HEJISBERG",scores = new List<int>{90,90,90,90}},
new student { id = 4 ,name = "BILL",fname = "GATES",scores = new List<int>{80,10,10,10}}

};


static void Main(string[] args)
{
var getscorequery = from student in students
where student.scores [0]>=90
select student;

foreach (student s in getscorequery)
{
Console.WriteLine("{0},{1}", s.id, s.name);
}
Console.ReadKey();
}

}
}

OUTPUT:

1, SUMAIR
2, JIMM
3, ANDREW

ADO.NET IN C# (PART 6)


NAVIGATION IN C#

DATABASE:
NAME = NORTHWIND.
TABLE :
NAME = PRODUCTS.
FIELDS:
productid,productname,unitprice,unitsinstock,categoryid,supplierid.


SqlConnection cn = new SqlConnection("Data Source=.;Initial Catalog=Northwind;Integrated Security=True");
DataSet ds = new DataSet();
private CurrencyManager cm;

public void NAVIGATIONFORM_LOAD(object sender, EventArgs e)
{
SqlDataAdapter da = new SqlDataAdapter("select *from products", cn);
cm = (CurrencyManager)BindingContext[ds.Tables["PRODUCTS"]];
da.Fill(ds, "products");
TextBox1.DataBindings.Add("text", ds.Tables["products"], "productid");
TextBox2.DataBindings.Add("text", ds.Tables["products"], "productname");
TextBox3.DataBindings.Add("text", ds.Tables["products"], "unitprice");
TextBox4.DataBindings.Add("text", ds.Tables["products"], "unitsinstock");
TextBox5.DataBindings.Add("text", ds.Tables["products"], "categoryid");
TextBox6.DataBindings.Add("text", ds.Tables["products"], "supplierid");
dg.DataSource = ds.Tables["products"];
}
private void BTNFIRST_Click(object sender, EventArgs e)
{
cm.Position = 0;
}
private void BTNNEXT_Click(object sender, EventArgs e)
{
cm.Position += 1;
}
private void BTNPREVIOUS_Click(object sender, EventArgs e)
{
cm.Position -= 1;
}
private void BTNLAST_Click(object sender, EventArgs e)
{
cm.Position = cm.Count - 1;
}

Saturday, April 11, 2009

ADO.NET IN C# (PART 5)

HOW TO INSERT UPDATE  and DELETE DATA IN A TABLE 

DataBase: 
NAME = empLoyee.

TABLE:
NAME = empinfo. 

FIELDS :
ID ( primary key ) ,Name ,FatherName,PhoneNo. 

FORM: 
4 TexBoxes 3 Buttons(insert ,update ,Delete).

INSERT:

We cannot insert data where primary key is set therefore for insertion we make textbox of id unvisible or leave .

 private void INSERTBUTTON_CLICK(object sender, EventArgs e)

 {
 SqlConnection cn = new SqlConnection("Data Source=.;Initial Catalog=employee;Integrated Security=True");
 SqlDataAdapter da = new SqlDataAdapter("select *from EmpInfo", cn);
  SqlCommand cmd = new SqlCommand();
  cmd.Connection = cn;
  cmd.CommandText = "Insert into EmpInfo(Name,FatherName,Phone no)VALUES( ' " + textBox1.Text + " ' , ' "+ textBox2.Text + " ' ," + textBox3.Text + " ) ";
  cmd.Connection.Open();
  cmd.ExecuteNonQuery();
  cmd.Connection.Close();
  MessageBox.Show("Record Saved");
}
ExecuteNonQuery Method:

The ExecuteNonQuery method of the SqlCommand class is used to execute commands that change a database. These commands include the Transact-SQL INSERT, UPDATE, DELETE, and SET statements. The method acts directly on a database connection and does not require a data set. It returns an integer that indicates the number of rows affected by the execution of a command. This method can also be used to perform catalog operations, such as querying the structure of a database or creating database objects.

UPDATE:

 private void UPDATEBUTTON_CLICK(object sender, EventArgs e)
  {

 SqlConnection cn = new SqlConnection("Data Source=.;Initial Catalog=employee;Integrated Security=True");
  SqlDataAdapter da = new SqlDataAdapter("select *from EMPINFO", cn);
  SqlCommand cmd = new SqlCommand();
  cmd.Connection = cn;
  cmd.CommandText = "update EMPINFO set Name = ' " + textBox2.Text + " ', Fathername = ' " + textBox3.Text + " ', phoneno = " + textBox4.Text + " where id = " + textBox1.Text + " ";
  cmd.Connection.Open();
  cmd.ExecuteNonQuery();
  cmd.Connection.Close();
  MessageBox.Show("Record Updated");
  }

DELETE:
 private void DELETEBUTTON_CLICK(object sender, EventArgs e)
  {
SqlConnection cn = new SqlConnection("Data Source=.;Initial Catalog=employee;Integrated Security=True");
 SqlDataAdapter da = new SqlDataAdapter("select *from empinfo", cn);
 SqlCommand cmd = new SqlCommand();
 cmd.Connection = cn;
 cmd.CommandText = "DELETE FROM EMPINFO WHERE STUID = " + textBox1.Text + " ";
 cmd.Connection.Open();
 cmd.ExecuteNonQuery();
 cmd.Connection.Close();
 MessageBox.Show("Record Deleted");
 }

Friday, April 10, 2009

ADO.NET IN C# (PART 4)

HOW TO DISPLAY COLUMN IN A COMBOBOX

Control OBJECTS:
1.
FORM : name = form1.
2.COMBOBOX:name = combobox1.
3. DATAGRID: name = datagridview1.

private void Form1_Load(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection("Data Source=.;Initial Catalog=Northwind;Integrated Security=True");
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("select *from products", cn);
da.Fill(ds,"products");
da.SelectCommand.CommandText = "select distinct product name from products";
dataGridView1.DataSource = ds.Tables["PRODUCTS"];
comboBox1.DataSource = ds.Tables["PRODUCTS"];
comboBox1.DisplayMember = "PRODUCTNAME";
comboBox1.ValueMember = "PRODUCTID";
comboBox1.SelectedIndex = 2; //Show product name in a combobox at index 2 when form load.
}

Wednesday, April 8, 2009

ADO.NET IN C# (PART3)

HOW TO SEARCH THROUGH CONTROL OBJECTS

Usually we search data by entering desired input in a control object liketextbox,comboboxetc.

After reading this post You will be able to use searching in yout project.

Drag Textbox(txtsearch) ,datagrid(dgsearch),and button named as btnsearch .Now paste below code into search buttonClick event.

private void btnsearch_Click(object sender, EventArgs e)

{

SqlConnection cnsearch = new SqlConnection("Data Source=.;Initial Catalog=Northwind;Integrated Security=True");

SqlDataAdapter dasearch = new SqlDataAdapter("select *from products", cnsearch);

DataSet dssearch = new DataSet();

Qsearch = "select *from products where productid = " + txtsearch.text+ "";

dasearch.SelectCommand.Connection = cnsearch;

dasearch.SelectCommand.CommandText = Qsearch;

dasearch.Fill(dssearch, "products");
dgsearch.DataSource = dssearch.Tables["products"];
}
NOTE:
if(textbox.text==integer)
{

"select *from products where productid = " + (textboxname).text + " "
//Dont forget to leave space between " + when giving name of textbox.
}
else
{
//only add single quotation at the end
select *from products where productid = ' " (textboxname).text + " ' "
}

ADO.NET IN C# (PART 2)

           HOW TO DISPLAY  DATA IN A DATA GRID

In the previous post i have discussed about the sqlclient classes,now i am going to make a project which will retrieve the datatable (products)  from the database(northwind).

Click FILE-> NEW PROJECT Drag datagridview on form from toolbox.Double Click the form so  that you can able to write code in FORMLOAD event.Dont forget to add System.data and System .data.sqlclient namespaces.

public void Form1_Load(object sender, EventArgs e)
  {
SqlConnection  myconnection  = new SqlConnection("Data Source=.;Initial Catalog=Northwind;Integrated Security=True");
DataSet mydataset  = new DataSet();

SqlDataAdapter myadapter = new
SqlDataAdapter("select *from products",myconnection);
myadapter.Fill(mydataset, "products");
Datagridview1.DataSource = ds.Tables["products"];
}

After debugging  you will see that all the columns of products  will display in a datagrid with its respective data.After execute it Try to display customers data.

Note: Here name of data grid is Datagridview1.                                                        

ADO.NET IN C# (PART 1)

ROLE OF ADO.NET MANAGED PROVIDER CLASSES :

ADO.NET allows you to interact with a database directly using objects of the managed provider classes. These objects allow you to connect to the database and execute SQL statements while directly connected to the database.

The Connection Classes:

1. SqlConnection.

we use an object of the SqlConnection class to connect to a SQL Server database.Firstly we connect to database by click tools on file menu of visual studio then connect to database then   choose database type as sqlclient after selecting it your server name is required .if you donot know your server name then enter . (dot)  it selects your local server.Choose database which you want.In this tutorial northwind database is selected.

e.g:-

connnection string = "Data Source=.;Initial Catalog=Northwind;Integrated Security=True"

To find connection string right click on  database in server explorer then select properties then  choose connection string 

sqlconnection cn as new sqlconnection(connection string);

2. OleDbConnection.

we  use an object of the OleDbConnection class to connect to any database that supports OLE DB, such as Access or Oracle

3. OdbcConnection.
we  use an object of the OdbcConnection class to connect to any database that supports ODBC.(opensource).

The DataSet Class:

we use an object of the DataSet class to represent a local copy of the information stored in the database. You can make changes to that local copy in your DataSet and then later synchronize those changes with the database through a managed provider DataAdapter object. A DataSet object can represent database structures such as tables, rows, and columns. You can even add constraints to your locally stored tables to enforce unique and foreign key constraints.

e.g:-

dataset ds as new dataset();


The DataAdapter Classes:

SqlDataAdapter :

 we use a DataAdapter object to move rows between a DataSet object and a database.In one of 

the overloaded method it takes select query and connection as parameters.

Query = "select*from products";

sqldataadapter da as new

sql dataadapt( SqlDataAdapter da = new SqlDataAdapte(query, cn);

The Command Classes:

we use a Command object to run a SQL statement, such as a SELECT, INSERT, UPDATE, or DELETE statement. we can also use a Command object to call a stored procedure or retrieve rows from a specific table. we run the command stored in a Command object using a Connection object.

e.g:-

SqlCommand cmd = new SqlCommand();
 
cmd.Connection = cn;
 cmd.CommandText = "select *from products";
 cmd.Connection.Open();
 cmd.ExecuteNonQuery();
 cmd.Connection.Close();


NOTE:

in this tutorial i use system.data.sqlclient(namespace)  classes.and ms sql server 2000 or later as dbms.Also i have connected to northwind database which is installed in a sqlserver by default.