Presentation is loading. Please wait.

Presentation is loading. Please wait.

C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. –It describes a particular type of object. –It specifies the properties.

Similar presentations


Presentation on theme: "C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. –It describes a particular type of object. –It specifies the properties."— Presentation transcript:

1 C# Classes ISYS 512

2 Introduction to Classes A class is the blueprint for an object. –It describes a particular type of object. –It specifies the properties (fields) and methods a particular type of object can have. –One or more object can be created from the class. –Each object created from a class is called an instance of the class.

3 Adding a Class to a Project Project/Add Class –Assigna meaningful name. Steps: –Adding properties Property procedures: Set / Get Or declare Public variables –Adding methods –Adding events, exceptions

4 Class Code Example: Properties defined using auto property { get; set; } public class emp { public string EID { get; set; } public string Ename{ get; set; } public double Salary { get; set; } public double empTax() { return Salary *.1; }

5 Using a Class: Creating an instance of the class using new emp myEmp = new emp(); protected void Page_Load(object sender, EventArgs e) { myEmp.EID = "e1"; myEmp.Ename = "Peter"; myEmp.Salary = 7500; } protected void Button1_Click(object sender, EventArgs e) { TextBox1.Text = myEmp.EID; TextBox2.Text = myEmp.empTax().ToString("c"); }

6 Creating Property with Property Procedures Implementing a property with a public variable the property value cannot be validated by the class. We can create read-only, write-only, or write-once properties with property procedure. Steps: –Declaring a private class variable to hold the property value. –Writing a property procedure to provide the interface to the property value.

7 class emp2 { private string pvEID; private string pvEname; private double pvSalary; public string EID { get { return pvEID; } set { pvEID = value; } public string Ename { get {return pvEname;} set {pvEname = value;} } public double Salary { get {return pvSalary;} set {pvSalary = value;} } public double empTax() { return Salary *.1; }

8 How the Property Procedure Works? When the program sets the property, the set property procedure is called and procedure code is executed. The value assigned to the property is passed in the value variable and is assigned to the hidden private variable. When the program reads the property, the get property procedure is called.

9 Anatomy of a Class Module Class Module Public Variables & Property Procedures Public Procedures & Functions Exposed Part Private Variables Private Procedures & Functions Hidden Part Private variables and procedures can be created for internal use. Encapsulation

10 Encapsulation is to hide the variables or something inside a class, preventing unauthorized parties to use. So methods like getter and setter access it and the other classes access it through property procedure.

11 Property Procedure Code Example: Enforcing a maximum value for salary public double Salary { get {return pvSalary;} set { if (value > 150000) { pvSalary = 150000; } else { pvSalary = value; }

12 Implementing a Read-Only Property: Declare the property with only the get procedure public DateTime DateHire { get { return pvDateHire; } set { pvDateHire = value; } } public int yearsEmployed { get { return DateTime.Today.Year - DateHire.Year; } Note: Cannot assign a value to yearsEmployed.

13 emp2 myEmp = new emp2(); protected void Page_Load(object sender, EventArgs e) { myEmp.EID = "e1"; myEmp.Ename = "Peter"; myEmp.Salary = 75000000; myEmp.DateHire = DateTime.Parse("1/1/2010"); } protected void Button1_Click(object sender, EventArgs e) { TextBox1.Text = myEmp.EID; TextBox2.Text = myEmp.empTax().ToString("c"); TextBox3.Text = myEmp.yearsEmployed.ToString(); }

14 Overloading A class may have more than one methods with the same name but a different argument list (with a different number of parameters or with parameters of different data type), different parameter signature.

15 Method Overloading Example public double empTax() { return Salary *.1; } public double empTax(double sal) { return sal *.1; }

16 Inheritance The process in which a new class can be based on an existing class, and will inherit that class’s interface and behaviors. The original class is known as the base class, super class, or parent class. The inherited class is called a subclass, a derived class, or a child class.

17 Employee Super Class with Three SubClasses All employee subtypes will have emp nbr, name, address, and date-hired Each employee subtype will also have its own attributes

18 Inheritance Example class emp2 { … …. } class secretary : emp2 { public double wordsPerMinute; }

19 Method Override class emp2 { ……. public virtual double empTax() { return Salary *.1; } public virtual double empTax(double sal) { return sal *.1; } } class secretary : emp2 { public double wordsPerMinute; public override double empTax() { return salary *.15; } Note: The keyword virtual allows a parent class method to be overridden. Example: public virtual double empTax()

20 Database Handling Classes Data Source ADO.Net Objects Database Classes Forms Reports

21 Single-Record-Handling Classes –Retrieves a single record from the database and makes it available to your application in the form of an object. –The fields in the record are exposed as the object’s properties. –Any actions performed by the data (updates, calculations, etc.) are exposed as the object’s methods.

22 Single-Record-Handling Customer Class public class Customer { private Boolean pvRecExist; public string CID { get; set; } public string Cname { get; set; } public string City { get; set; } public string Rating { get; set; } public Boolean RecExist { get { return pvRecExist ; }

23 public void getCustomerData(string searchCID) { string strConn = "Data Source=rkoq6ngwva.database.windows.net;Initial Catalog=CustomerOrders;Persist Security Info=True;User ID=dchaoDB;Password=dchao_Azure1"; SqlConnection objConn = new SqlConnection(strConn); string strSQL = "select * from customer where cid='" + searchCID + "'"; SqlCommand objComm = new SqlCommand(strSQL, objConn); objConn.Open(); SqlDataReader objDataReader; objDataReader = objComm.ExecuteReader(); if (objDataReader.Read() == false) { pvRecExist = false; } else { pvRecExist = true; CID = objDataReader["CID"].ToString(); Cname = objDataReader["Cname"].ToString(); City = objDataReader["City"].ToString(); Rating = objDataReader["Rating"].ToString(); }

24 string strConn = "Data Source=rkoq6ngwva.database.windows.net;Initial Catalog=CustomerOrders;Persist Security Info=True;User ID=dchaoDB;Password=dchao_Azure1"; SqlConnection objConn = new SqlConnection(strConn); string strSQLInsert; strSQLInsert = "Insert into Customer values ('"; strSQLInsert += CID + "','" + Cname + "','"; strSQLInsert += City + "','" + Rating + "')"; SqlCommand objCommInsert = new SqlCommand(strSQLInsert, objConn); objConn.Open(); objCommInsert.ExecuteNonQuery(); objConn.Close();

25 Using the Customer Class protected void Button1_Click(object sender, EventArgs e) { Customer myCust = new Customer(); myCust.CID = TextBox1.Text; myCust.getCustomerData(myCust.CID); if (myCust.RecExist) { TextBox2.Text = myCust.Cname; TextBox3.Text = myCust.Rating; } else Response.Write("record not exist"); }

26 Using the Customer Class to Add a New Customer

27 Using the SaveNewCustomer Method to Add A New Customer protected void Button1_Click(object sender, EventArgs e) { Customer newCust = new Customer(); newCust.CID = TextBox1.Text; newCust.Cname = TextBox2.Text; newCust.City = TextBox3.Text; newCust.Rating = TextBox4.Text; newCust.SaveNewCustomer(); TextBox1.Text = ""; TextBox2.Text = ""; TextBox3.Text = ""; TextBox4.Text = ""; }

28 How to insure the insertion is successful? Add a Boolean property private Boolean pvInsertSuccess; public Boolean InsertSuccess { get { return pvInsertSuccess ; }

29 How to insure the insertion is successful? public void SaveNewCustomer() { string strConn = "Data Source=rkoq6ngwva.database.windows.net;Initial Catalog=CustomerOrders;Persist Security Info=True;User ID=dchaoDB;Password=dchao_Azure1"; SqlConnection objConn = new SqlConnection(strConn); string strSQLInsert; strSQLInsert = "Insert into Customer values ('"; strSQLInsert += CID + "','" + Cname + "','"; strSQLInsert += City + "','" + Rating + "')"; SqlCommand objCommInsert = new SqlCommand(strSQLInsert, objConn); try { objConn.Open(); if (objCommInsert.ExecuteNonQuery() == 1) pvInsertSuccess = true; else pvInsertSuccess = false; } catch { pvInsertSuccess = false; } objConn.Close(); }

30 Other Methods Updating a record Deleting a record Note: CRUD –Create or add new entries – Read, retrieve, search, or view existing entries – Update or edit existing entries – Delete/deactivate existing entries

31 Modeling 1:M Relation with Classes Employee –EID –Ename –Dependents Department –DID –Dname –Employees Customer –CID –Cname –Orders

32 List Class Represents a strongly typed list of objects that can be accessed by index where T is the type of objects in the list. T can be an entity class so that List represents a collection of T-class objects.

33 Implementing a 1:M Relationship With List CID Cname City Rating Orders --- a List of order Methods: GetOrders OID Odate SalesPerson Class Customer Class Order

34 Customer Class private Boolean pvRecExist; private Boolean pvInsertSuccess; public string CID { get; set; } public string Cname { get; set; } public string City { get; set; } public string Rating { get; set; } public Boolean RecExist { get { return pvRecExist ; } public Boolean InsertSuccess { get { return pvInsertSuccess ; } public List orders = new List ();

35 GetOrders Method public void getOrders(string searchCID) { string strConn = "Data Source=rkoq6ngwva.database.windows.net;Initial Catalog=CustomerOrders;Persist Security Info=True;User ID=dchaoDB;Password=dchao_Azure1"; SqlConnection objConn = new SqlConnection(strConn); string strSQL = "select * from orders where cid='" + searchCID + "'"; SqlCommand objComm = new SqlCommand(strSQL, objConn); objConn.Open(); SqlDataReader objDataReader; objDataReader = objComm.ExecuteReader(); while (objDataReader.Read()) { Order ord = new Order(); ord.OID = objDataReader["OID"].ToString(); ord.Odate = (DateTime)objDataReader["odate"]; ord.CID = objDataReader["CID"].ToString(); ord.SalesPerson = objDataReader["SalesPerson"].ToString(); ord.Amount =double.Parse(objDataReader["Amount"].ToString()); orders.Add(ord); }

36 Order Class public class Order { public string OID {get;set;} public DateTime Odate {get;set;} public string CID { get; set; } public string SalesPerson {get;set;} public double Amount { get; set; } }

37 Binding Datagrid to a List GridView1.DataSource = myCust.orders; GridView1.DataBind();

38 Example

39 protected void Page_Load(object sender, EventArgs e) { if (!(Page.IsPostBack)) { string strConn = "Data Source=rkoq6ngwva.database.windows.net;Initial Catalog=CustomerOrders;Persist Security Info=True;User ID=dchaoDB;Password=dchao_Azure1"; SqlConnection objConn = new SqlConnection(strConn); string strSQL = "select CID from customer;"; SqlCommand objComm = new SqlCommand(strSQL, objConn); objConn.Open(); SqlDataReader objDataReader; objDataReader = objComm.ExecuteReader(); ListBox1.DataSource=objDataReader; ListBox1.DataTextField = "CID"; ListBox1.DataValueField = "CID"; ListBox1.DataBind(); }

40 protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e) { Customer myCust = new Customer(); myCust.getCustomerData(ListBox1.SelectedItem.ToString()); if (myCust.RecExist) { TextBox1.Text = myCust.Cname; TextBox2.Text = myCust.Rating; myCust.getOrders(myCust.CID); GridView1.DataSource = myCust.orders; GridView1.DataBind(); }

41 Assembly An assembly is a compiled code library used for deployment, versioning.

42 Difference between Assembly and Class A class defined in a project is available to that project only. Once a class is compiled in an assembly it can be used by any projects. To create an assembly: –Start a Class Library project

43 Steps to Create An Assembly Start a Class Library project Create classes –You can also use existing classes defined in other projects by Project/Add Existing Item Note 1: Change the class to a public class ** very important Example: public class Customer Note 2: You may need to rename the namespace Save project Select Build/Build to compile the code. –When the class library is compiled successfully, an assembly is created and stored in the project’s Bin/Debug folder. –Example: A testClassLib project is created in C:\CSharpExamples, then the assembly is found in: –C:\CSharpExamples\testClassLib\testClassLib\bin\Debug

44 Using the Assembly Reference the assembly: Project/Add Reference and use the Browse button to select the assembly. Import the namespace. using CustOrders;

45 Code Using Assembly Customer myCust = new Customer(); myCust.CID = TextBox1.Text; myCust.getCustomerData(myCust.CID); if (myCust.RecExist) { TextBox2.Text = myCust.Cname; TextBox3.Text = myCust.Rating; } else Response.Write("Record does not exist!");

46 Assembly with Customer and Order classes Customer myCust = new Customer(); myCust.CID = TextBox1.Text; myCust.getCustomerData(myCust.CID); if (myCust.RecExist) { TextBox2.Text = myCust.Cname; TextBox3.Text = myCust.Rating; myCust.getOrders(myCust.CID); GridView1.DataSource = myCust.orders; GridView1.DataBind(); } else Response.Write("Record does not exist!");

47 Class that Returns DataSet public class GetDataSet { public DataSet getCustomerOrders() { string strConn = "Data Source=rkoq6ngwva.database.windows.net;Initial Catalog=CustomerOrders;Persist Security Info=True;User ID=dchaoDB;Password=dchao_Azure1"; SqlConnection objConn = new SqlConnection(strConn); string strSQL = "select * from customer;"; SqlDataAdapter objAdapter = new SqlDataAdapter(strSQL, objConn); DataSet objDataSet = new DataSet(); objAdapter.Fill(objDataSet, "Customer"); string strSQL2 = "select * from orders;"; objAdapter.SelectCommand.CommandText = strSQL2; objAdapter.Fill(objDataSet, "orders"); return objDataSet; }

48 Class that Represents a Collection of All Customers public class AllCustomers { public List CustomerList = new List (); public void getAllCustomers() { string strConn = "Data Source=rkoq6ngwva.database.windows.net;Initial Catalog=CustomerOrders;Persist Security Info=True;User ID=dchaoDB;Password=dchao_Azure1"; SqlConnection objConn = new SqlConnection(strConn); string strSQL = "select * from customer"; SqlCommand objComm = new SqlCommand(strSQL, objConn); objConn.Open(); SqlDataReader objDataReader; objDataReader = objComm.ExecuteReader(); while (objDataReader.Read() == true) { Customer cust = new Customer(); cust.CID = objDataReader["CID"].ToString(); cust.Cname = objDataReader["Cname"].ToString(); cust.City = objDataReader["City"].ToString(); cust.Rating = objDataReader["Rating"].ToString(); CustomerList.Add(cust); }

49 Changes to Assembly Old projects referencing the assembly will get the latest version of the assembly. Compatible changes: –Changes to assembly that will not break the older projects. –Examples: Adding a property, adding a method Incompatible changes –Changes to assembly that will break the older projects. –Examples: Deleting or renaming a property or a method

50 ArrayList vs List ArrayList is a data structure used to store a set of values. –Its capacity is automatically expanded as needed. –Values stored in an arraylist do not have to be the same data type. –Flexibility when inserting/deleting elements.


Download ppt "C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. –It describes a particular type of object. –It specifies the properties."

Similar presentations


Ads by Google