Você está na página 1de 15

ADO.

NET using disconnected architecture


class DisconnectedDataform : Form { private SqlConnection conn; private SqlDataAdapter daCustomers; private DataSet dsCustomers; private DataGrid dgCustomers; private const string tableName = "Customers"; <span style="color: green;">// initialize form with DataGrid and Button <span style="color: blue;">public DisconnectedDataform() { // fill dataset Initdata(); // set up datagrid dgCustomers = new DataGrid(); dgCustomers.Location = new Point(5, 5); dgCustomers.Size = new Size( this.ClientRectangle.Size.Width - 10, this.ClientRectangle.Height - 50); dgCustomers.DataSource = dsCustomers; dgCustomers.DataMember = tableName; // create update button Button btnUpdate = new Button(); btnUpdate.Text = "Update"; btnUpdate.Location = <span style="color: blue;">new Point( <span style="color: blue;">this.ClientRectangle.Width/2 - btnUpdate.Width/2, this.ClientRectangle.Height - (btnUpdate.Height + 10)); btnUpdate.Click += new EventHandler(btnUpdateClicked); // make sure controls appear on form Controls.AddRange(new Control[] { dgCustomers, btnUpdate }); } // set up ADO.NET objects public void Initdata() { // instantiate the connection conn = new SqlConnection( "Server=(local);DataBase=Northwind;Integrated Security=SSPI"); // 1. instantiate a new DataSet dsCustomers = new DataSet(); // 2. init SqlDataAdapter with select command and connection daCustomers = new SqlDataAdapter( "select CustomerID, CompanyName from Customers", conn); // 3. fill in insert, update, and delete commands SqlCommandBuilder cmdBldr = new SqlCommandBuilder(daCustomers); // 4. fill the dataset daCustomers.Fill(dsCustomers, tableName); } // Update button was clicked public void btnUpdateClicked(object sender, EventArgs e)

{ // write changes back to DataBase daCustomers.Update(dsCustomers, tableName); } // start the Windows form static void Main() { Application.Run(new DisconnectedDataForm()); } }

ADO.NET
class SqlConnectionDemo { static void Main() { // 1. Instantiate the connection SqlConnection conn = new SqlConnection( "Data Source=(local);Initial Catalog=Northwind;Integrated Security=true"); SqlDataReader rdr = null; try { // 2. Open the connection conn.Open(); // 3. Pass the connection to a command object SqlCommand cmd = new SqlCommand("select * from Customers", conn); // // 4. Use the connection // // get query results rdr = cmd.ExecuteReader(); // print the CustomerID of each record while (rdr.Read()) { Console.WriteLine(rdr[0]); } } finally { // close the reader if (rdr != null) { rdr.Close();

} // 5. Close the connection if (conn != null) { conn.Close(); } } } }

AP USING IENUMERABLE
using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace IENUM_APGP { class Program { static IEnumerable<int> ap(int a , int d, int l) { for (int i = 1; i < l; i++) yield return a + d*(i - 1);

} static void Main(string[] args) { foreach(int a in ap(1,2,8)) Console.WriteLine(a); Console.ReadKey();

} } } output: 1 3 5 7 9 11

IEnumerable Interface
Although there are many different types of collections whose internal implementation and external characteristics may vary,the ability to traverse the contents of the collection is a universal need.The interfaces IEnumerable and IEnumerator support this need. The IEnumerator interface defines a protocol to enumerate a collection (in a forward only manner) using the foreach keyword. Also Collections do not implement enumerators.They provide enumerators via IEnumerable.IEnumerable provides the flexibility to implement the iteration logic in another class.

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

namespace ConsoleApplication1 { class coordinate { public int x, y; public coordinate(int x, int y) { this.x = x; this.y = y; }

public override string ToString() { return x + " , " + y; } } //Implementing the generic interface class coordinateCollection :IEnumerable<coordinate> { private coordinate[] cc; public int variablex; public coordinateCollection(int len) { Random r=new Random(); cc = new coordinate[len]; for(int i = 0; i<len;i++) { cc[i] = new coordinate(r.Next(10), r.Next(10)); } } /*The foreach statement is a convenient way to iterate over the elements of an array. It can also enumerate the elements of a collection, provided that the collection class has implemented the System.Collections.IEnumerator and System.Collections.IEnumerable interfaces.*/

public IEnumerator<coordinate> GetEnumerator() { foreach (coordinate c in cc) yield return c; //The yield keyword is used in an iterator block to provide a value to the enumerator object } /*Because IEnumerable<Type> implements IEnumerable, we need to implement both the generic and nongeneric versions of GetEnumerator.*/

System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()

{ return this.GetEnumerator(); } } /*Now we can simply call the generic GetEnumerator because IEnumerator<Type> implements IEnumerator*/

class Program { static void Main(string[] args) { coordinateCollection cctmp = new coordinateCollection(9); foreach (coordinate c in cctmp) Console.WriteLine(c); Console.ReadKey();

} } }

Joins in LINQ
A join in sql can be written as :

SELECT Customer.LastName, Customer.FirstName,Address.Street FROM Customer JOIN Address ON customer.name=address.name ORDER BY customer.LastName An equivalent join expression in LINQ would be: var result = from customer in customers join address in addresses on customer.FirstName equals address.Name orderby customer.LastName

select new{ Customer = customer, Address = address }; The select statement here returns a new anonymous class instance coz the new class is a joined class containing a join of a customer class and an address class. An alternate way could be first creating a new class as follows: class studentAddress { Student stud; Address addr; } and then the select statement wud be: select new studentAddress{ Customer = customer, Address = address };

The complete code for the above is given below: // Simple customer class; public class Customer { public string FirstName { get ; set; } public string LastName { get ;set } public string EmailAddress { get ; set ; } // overrides the Object.ToString( ) to provide a // string representation of the object properties. public override string ToString( ) { return string.Format("{0} {1}\nEmail: {2}", FirstName, LastName, EmailAddress); } } // Customer address class; public class Address { public string Name { get; set; } public string Street { get; set; } public string City { get; set; } // overrides the Object.ToString( ) to provide a // string representation of the object properties.

public override string ToString( ) { return string.Format("{0}, {1}", Street, City); } } // Main program public class Tester { static void Main( ) { List<Customer> customers = CreateCustomerList( ); List<Address> addresses = CreateAddressList( ); // Find all addresses of a customer var result = from customer in customers join address in addresses on string.Format("{0} {1}", customer.FirstName, customer.LastName) equals address.Name orderby customer.LastName, address.Street descending select new{ Customer = customer, Address = address }; foreach (var ca in result) { Console.WriteLine(string.Format("{0}\nAddress: {1}", ca.Customer, ca.Address)); } } // Create a customer list with sample data private static List<Customer> CreateCustomerList( ) { List<Customer> customers = new List<Customer> { new Customer { FirstName = "Utsav",LastName = "Beri",EmailAddress = " utsavberi@gmail.com"},</p> <p>new Customer { FirstName = "Nishant",LastName = "Kumar",EmailAddress = " kumar.nishant19@gmail.com" },

new Customer { FirstName = "Ankit",LastName = "Bhattacharjee",EmailAddress = " mail.tikna@gmail.com" }, new Customer { FirstName = "Anirudh",LastName = "Pandita",EmailAddress = " auroindia@gmail.com" }, new Customer { FirstName = "Pranav",LastName = "gautam",EmailAddress = " pranavgautam@gmx.com" } }; return customers; }

// Create a customer list with sample data private static List<Address> CreateAddressList( ) { List<Address> addresses = new List<Address> { new Address { Name = "Utsav",Street = "munirka apartment",City = "New Delhi" }, new Address { Name = Nishant",Street = "plot-41,amberai extn",City = "New Delhi" }, new Address { Name = "Ankit",Street = "C.R Park.",City = "New Delhi" }, new Address { Name = "Anirudh",Street = "Dwaraka",City = "New Delhi" }, new Address { Name = "PPS",Street = "sec-22,Dwarka",City = "New Delhi" } }; return addresses; } }

Introduction to LINQ
Language Integrated Query (LINQ) is a Microsoft .NET Framework component that adds native data querying capabilities to .NET languages. LINQ has a great power of querying on any source of data,
data source could be the collections of objects, database or XML files. We can easily retrieve data from any object that implements the IEnumerable<T> interface.

Below is a simple example on using LINQ in your applications:

public class Student { //Auto implemented properties public string FirstName { get; set; }

public string LastName { get; set; } public string EmailAddress { get; set; }

//Constructor public Student(string firstName, string lastName, string emailAddress) { this.FirstName = firstName; this.LastName = lastName; this.EmailAddress = emailAddress; }

// Overrides the Object.ToString( ) to provide a string representation of the object properties. public override string ToString() { return string.Format("{0} {1}\nEmail:{2}", FirstName, LastName, EmailAddress); } }

class Program { static void Main(string[] args) { //Initializing of a student array with 7 elements Student[] custArray = new Student[]{ new Student("Utsav","Beri"," utsavberi@gmail.com"), new Student("Nishant","Kumar"," nishantk@yahoo.com"), new Student("Anirudh","Pandita"," auro@auro.com"), new Student("Ankit","Bhattacharjee"," mail.tikna@gmail.com"), new Student("Piyush","Pandey"," piyush@gmail.com"), new Student("Pranav","P.Singh"," Pranav@gmail.com"), new Student("Rekha","Kumar"," rekhak@rediff.com") };

//Linq code starts here // Find customer by last name var result = from customer in custArray where customer.LastName == "Kumar" select customer;

Console.WriteLine ("All records with last name = kumar :"); foreach (Student customer in result) //Display the result Console.WriteLine (customer.ToString ()); Console.Read(); } }

Extension Methods
Extension methods enable you to "add" methods to existing classes without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. This can be illustrated with the help of the code below : //This class will contain the extension method static class abc { //extension method #1 public static bool isTooLong(this String str) //the parameter type ie 'String' adds this function to the string class { if (str.Length > 15) return true; //returns true if the strings length is > 15 else false else return false; } //Extension method #2 public static String toFunkyCase(this String str) { char[] arr = str.ToUpper().ToCharArray(); for (int i = 0; i < arr.Length;i = i+2 ) arr[i] = Convert.ToChar(Convert.ToInt16(arr[i]) + (Convert.ToInt16('a')-Convert.ToInt16('A'))); return new string(arr); } } class Program { static void Main(string[] args) { string str = "Hello World"; Console.WriteLine(str.toFunkyCase()); //will output : hElLo wOrLd Console.WriteLine("Is string too long ?? : {0}",str.isTooLong()); // will output "Is string too long ?? : False " Console.ReadKey();

} }

C#-Delegates and EventHandling


C# supports the event handling model which allows a publisher object to publish an event which notifies the subscriber class whenever that event occurs. For eg whenever you click on a button an event is generated which is notified to the form class which contains the button object and subscribes to the buttons on_click event. To understand event handling we first need to have a basic understanding of delegates. A delegate is basically a pointer to a function. A delegate can only point to functions with the same signature as it's. The following code explains how delegates works: class Program { public delegate int transform(int a); //a delegate which will point to a function of the form 'int func(int)' //function of the form int func(int) static public int square(int a) { return a * a; }

//function of the form int func(int) static public int half(int a) { return a / 2; }

static void transArr(int[] ar, transform trans) { for (int i = 0; i < ar.Length; i++) ar[i] = trans(ar[i]); //performs the operation defined by the trans delegate given as an argument while calling the function on all the element of the array

static void Main(string[] args)

{ int x = 54; transform t = square; //the transform delegate now points to the square function defined above Console.WriteLine(t(x));//the delegate is now called which inturn calls the square function & outputs the square of 54

t = half;//now the delegate points to the half function ddefined above Console.WriteLine(t(x));//will now output half of 54

//another application of delegates int[] arr = { 3, 5, 1, 8, 3, 65, 97, 4, 78 };

transArr(arr, half);//transArr function defined below foreach (int i in arr) Console.WriteLine(i);

transArr(arr, square); foreach (int i in arr) Console.WriteLine(i); Console.ReadKey();

//A function which takes a delegate as a parameter static void transArr(int[] ar, transform t) { for (int i = 0; i < ar.Length; i++) ar[i] = t(ar[i]); } }

Now that we have a basic understanding of delegates lets move on to Event handling. In the following code we create two classes: A "stock" class which is the publisher class and publishes the stockChanged event. The other class ie "Program" is a subscriber class and subscribes to the stockChanged event. In the Stock

class whenever the value of the stock change it generated an event and notifies all its subscribers. Here the subscriber ie the "Program" class simply prints the before and after value of the stock. 1. using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace StockEvent {

class stock //the publisher class { public delegate void stockChangeHandler(int bf, int aftr); //Create a delegate class which can point to functions of the form void foo(int,int) public event stockChangeHandler stockChanged=null;//Creates a referrence of the above delegate initialized to null int stockval; public int StockVal { set { if (stockChanged != null) //if a subscriber has subscribed to the event { if (value != stockval) //if the new value is different from the old stockval { int tmp = stockval; stockval = value; stockChanged(tmp, value); //call the function pointed by the stockChanged event } } } get { return stockval ; } }

} class Program //the subscriber class

{ static void Main(string[] args) { stock st1=new stock();

st1.stockChanged += on_stock_changed; //subscribing to the event st1.StockVal = 25; //on_stock_changed will be called st1.StockVal = 7; //on_stock_changed will be called st1.StockVal = 55; //on_stock_changed will be called st1.StockVal = 22; //on_stock_changed will be called Console.Read();

static void on_stock_changed(int bf, int af) { Console.WriteLine("before : {0}, After : {1}", bf, af); } } } In the publisher class (ie. StockEvent) we create a new event called 'stockChanged' which is actually an object referrence of the delegate declared above. In the setter method we call the event which in turn executes the functions it points to which is generally situated in the client class. In the client class (ie. Program) we create a new stock object st1 and point its stockChanged event to the on_stock_Changed method. So, whenever we try to set a value in the StockVal Field of the st1 object the on_stock_Changed will be called.

Você também pode gostar