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.

Slides:



Advertisements
Similar presentations
Java Classes ISYS 350. Introduction to Classes A class is the blueprint for an object. – It describes a particular type of object. – It specifies the.
Advertisements

VB Classes ISYS 573. Object-Oriented Concepts Abstraction: –To create a model of an object, for the purpose of determining the characteristics (properties)
Creating Custom Controls ISYS 512/812. Inheritance The process in which a new class can be based on an existing class, and will inherit that class’s interface.
VB Classes - 2 ISYS 573. Creating an Array of Objects Dim emps(2) As emp Dim i As Integer For i = 0 To emps.GetUpperBound(0) emps(i) = New emp() Next.
Authenticating Users in an ASP.NET Application. Web Site Administration Tool From VS 2008, click Website/ ASP.Net Configuration to open Web Site Administration.
ASP.NET and ADO.NET. ASP.NET Server Controls Intrinsic Controls: These controls correspond to their HTML counterparts. –Ex. Textbox, listbox, button,
VB.NET Database Tools ISYS Net Applications OLE DB Provider OLE DB Data Source OLE DB Provider ODBC Data Source SQL Server Data Source SQL Server.Net.
Coding ADO.NET Objects: Connection, Command, DataReader.
ASP.NET and ADO.NET. ADO.NET Objects Data Set.NET Applications Data Reader Command Object Connection Object Managed Data Provider (OLEDB) Database.
Web Site Security ISYS 512/812. Authentication Authentication is the process that determines the identity of a user. Web.config file – node Options: –Windows:
Coding ADO.NET Objects: Connection, Command, DataReader.
Working with Session and Application Objects. Postback and Variables Variables declared in a web page including ADO.Net objects may be reinitialized and.
VB.NET Database Tools ISYS 573. Microsoft Universal Data Access ODBC: Open Database Connectivity –A driver manager –Used for relational databases OLE.
Introduction to Web Application Development with.Net and Web Service ISYS 350.
ASP.NET and ADO.NET. Bind the DataReader to a DataGrid Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\sales2k.mdb" Dim objConn.
VB Classes BICS546. Adding a Class to a Project Project/Add Class Class will be saved in a.CLS file Steps: –Adding properties Declare Public variables.
Coding ADO.NET Objects: Connection, Command, DataReader.
Inheritance and User-Defined Controls. Inheritance The process in which a new class can be based on an existing class, and will inherit that class’s interface.
VB.NET Classes ISYS 812. Object-Oriented Concepts Abstraction: –To create a model of an object, for the purpose of determining the characteristics (properties)
Working with Session. Postback and Variables Variables declared in a web page including ADO.Net objects may be reinitialized and lose their values.
VB Classes ISYS 573. Object-Oriented Concepts Abstraction: –To create a model of an object, for the purpose of determining the characteristics (properties)
Introduction to ADO.Net, VB.Net Database Tools and Data Binding ISYS 512.
VB.NET Classes ISYS 546. Classes A class is program structure that defines a user-defined data type that are used to create objects. An instance of a.
Coding ADO.Net DataSet Objects. DataSet Object A DataSet object can hold several tables and relationships between tables. A DataSet is a set of disconnedted.
VB Classes ISYS 512. Adding a Class to a Project Project/Add Class –*** MyClass is a VB keyword. Steps: –Adding properties Declare Public variables in.
Introduction to Web Service ISYS 512. Web Service XML Web Service Web services are classes that are stored on the web which can instantiate and use in.
OOP Languages: Java vs C++
Object Based Programming. Summary Slide  Instantiating An Object  Encapsulation  Inheritance  Polymorphism –Overriding Methods –Overloading vs. Overriding.
Introduction to ADO.Net and Visual Studio Database Tools ISYS 512.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
C# Programming Fundamentals of Object-Oriented Programming Fundamentals of Object-Oriented Programming Introducing Microsoft.NET Introducing Microsoft.NET.
Java Classes ISYS 350. Introduction to Classes Two basic uses of class: – 1. A class is a way to organize functions (methods) to perform calculations.
C#/Java Classes ISYS 350. Introduction to Classes A class is the blueprint for an object. – It describes a particular type of object. – It specifies the.
Sample Application Multi Layered Architecture (n-tier): –Graphical User Interface (GUI): Forms, components, controls The Visual Designer in Visual Studio.
Working with the Application Object. Session VS Application Object The Session object helps to preserve data on a per user basis. What if we want to initialize.
Database Handling Classes ISYS 475. Introduction to Classes A class is the blueprint for an object. –It describes a particular type of object. –It specifies.
Website Security ISYS 512. Authentication Authentication is the process that determines the identity of a user.
Copyright © 2012 Pearson Education, Inc. Chapter 9 Classes and Multiform Projects.
Introduction to Web Service ISYS 512. Web Service XML Web Service Web services are classes that are stored on the web which can instantiate and use in.
Java Classes ISYS 350. Introduction to Classes A class is the blueprint for an object. – It describes a particular type of object. – It specifies the.
Command Object’s ExecuteNonQuery Method ISYS 512.
Objects andVB Classes ISYS 350. What Is an Object? Objects are key to understanding object-oriented technology. There are many examples of real-world.
Introduction to ADO.Net and VS Database Tools and Data Binding ISYS 350.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
VB Classes ISYS 512/812. Object-Oriented Concepts Abstraction: –To create a model of an object, for the purpose of determining the characteristics (properties)
Chapter 10: Introduction to Inheritance. Objectives Learn about the concept of inheritance Extend classes Override superclass methods Call constructors.
C# Classes ISYS 350. Introduction to Classes A class is the blueprint for an object. – It describes a particular type of object. – It specifies the properties.
Coding ADO.NET Objects: Connection, Command, DataReader.
Architecture Multi Layered Architecture (n-tier): Application: Model Controllers Database Access Graphical User Interface (GUI): Forms, components, controls.
Objects andVB Classes ISYS 350. What Is an Object? Objects are key to understanding object-oriented technology. There are many examples of real-world.
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.
5.1 Basics of defining and using classes A review of class and object definitions A class is a template or blueprint for an object A class defines.
Coding ADO.Net DataSet Objects ISYS 512. DataSet Object A DataSet object can hold several tables and relationships between tables. A DataSet is a set.
COMPUTER SCIENCE & TECHNOLOGY DEGREE PROGRAMME FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UVA WELLASSA ‏ Properties of Object Oriented Programming.
Shopping Cart Demo. Shopping Cart Search and display product information Add item to cart View cart contents Check out.
Coding ADO.NET Objects: Connection, Command, DataReader.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Object Oriented Programming. Constructors  Constructors are like special methods that are called implicitly as soon as an object is instantiated (i.e.
Coding ADO.NET Objects: Connection, Command, DataReader
ASP.NET and ADO.NET.
Coding ADO.NET Objects: Connection, Command, DataReader
CIS 199 Final Review.
Database Handling Class and Service
ASP.NET and ADO.NET.
VB Classes ISYS 512.
Working with Session and Application Objects
Shopping Cart Demo.
Command Object’s ExecuteNonQuery Method
Introduction to ADO.Net and Visual Studio Database Tools.
Presentation transcript:

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 (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.

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

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; }

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"); }

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.

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; }

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.

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

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.

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

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.

emp2 myEmp = new emp2(); protected void Page_Load(object sender, EventArgs e) { myEmp.EID = "e1"; myEmp.Ename = "Peter"; myEmp.Salary = ; 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(); }

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.

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

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.

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

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

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()

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

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.

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 ; }

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(); }

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();

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"); }

Using the Customer Class to Add a New Customer

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 = ""; }

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

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(); }

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

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

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.

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

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 ();

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); }

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; } }

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

Example

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(); }

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(); }

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

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

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

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

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!");

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!");

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; }

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); }

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

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.