Advance Web Programming Chalaivate Pipatpannawong อ.ชไลเวท พิพัฒพรรณวงศ์ Computer Instructor
Download ReportTranscript Advance Web Programming Chalaivate Pipatpannawong อ.ชไลเวท พิพัฒพรรณวงศ์ Computer Instructor
ITEC5620 - Advance Web Programming Advance Web Programming อ.ชไลเวท พิพฒ ั พรรณวงศ ์ Chalaivate Pipatpannawong Computer Instructor Microsoft Certificate Professional Web : www.9Expert.co.th ; Thaiwebdev.com E-Mail: [email protected] ปริญญาโท สาขาวิชา เทคโนโลยีสารสนเทศ Chalaivate Pipatpannawong Current ITEC5620 - Advance Web Programming:: Rangsit University instructor Ramkhamhange Unversity instructor Contact Info. E-mail : [email protected] MSN: [email protected] Mobile: 08-1850-3286 Web Site : http://www.chalaivate.com Community : http://www.thaiwebdev.com Microsoft Certify Professional (MCP) 2 ปริญญาโท สาขาวิชา เทคโนโลยีสารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Course Outline Review Web Programming Review ASP.NET Introduction to Web Services XML and XML Schema for WSDL Introducing SOAP Consuming a Web Service Implement an XML Web service consumer by using Microsoft Visual Studio .NET Implement a simple XML Web service by using Visual Studio .NET. Publish and deploy an XML Web service. Web Services Enhancements 3.0 .NET Web Services Security Deploying and Publishing an XML Web Service XML Security Implement WS-Security3 ปริญญาโท สาขาวิชา เทคโนโลยีสารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Course Outline Design Patterns for Building MessageOriented Web Services Design Patterns for Building Service-Oriented Web Services Addressing, Messaging, and Routing Web Services Interoperability Issues Designing for flexible computing Service-Oriented Architecture Benefits of Service-Oriented Architecture (SOA) Advantages of contract-based design for interoperability Creating and Consuming a Service Building a service Configuring the client with service details Generating the client 4proxy and consuming ปริญญาโท สาขาวิชา เทคโนโลยีสารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: EVALUATION Class Attendance 10% Mid Term 30% Final 40% Individual Project 20% ปริญญาโท สาขาวิชา เทคโนโลยี 5 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Today’s Agenda Review Web Programming Review ASP.NET Review ADO.NET LAB ปริญญาโท สาขาวิชา เทคโนโลยี 6 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Agenda Introduction to OOP using C# Intermediate C# XML Web Service What’s new in ASP.NET 2.0 Hand on Labs ปริญญาโท สาขาวิชา เทคโนโลยี 7 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร Intro to OOP using C# ITEC5620 - Advance Web Programming:: Classes & Objects Attributes Methods Objects in memory Visibility Properties (get & set) Constructors ปริญญาโท สาขาวิชา เทคโนโลยี 8 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Classes Encapsulate data and functions Enable more complex programming Requires “Object think” Security/reliability ปริญญาโท สาขาวิชา เทคโนโลยี 9 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Defining a Class class NAME { ATTRIBUTES (i.e. data) METHODS (i.e. functions) } ปริญญาโท สาขาวิชา เทคโนโลยี 10 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร Class Example ITEC5620 - Advance Web Programming:: class BMW_Z4 { int ModelYear; string LicensePlate; Attributes (data) bool TopUp; void Drive() { Console.WriteLine(“Roadin’ and Rockin’“); } void OpenTop() Methods (functions) { TopUp = false; } } ปริญญาโท สาขาวิชา เทคโนโลยี 11 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Instantiating Classes Defining the class is akin to defining a type An object is an instance of a class Class:Object::Type:Variable Use new to instantiate the class ปริญญาโท สาขาวิชา เทคโนโลยี 12 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร Instantiating Class & Using Object ITEC5620 - Advance Web Programming:: BMW_Z4 myCar; myCar = new BMW_Z4(); myCar.LicensePlate = "BMR4ME"; myCar.ModelYear = 2004; myCar.Drive(); myCar.OpenTop(); myCar.Drive(); ปริญญาโท สาขาวิชา เทคโนโลยี 13 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Memory Trace Dog d1, d2; null d1 = new Dog (5, “bob”); d2 = new Dog (3, “ethel”); d1 = d2; ปริญญาโท สาขาวิชา เทคโนโลยี 14 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร Memory Trace ITEC5620 - Advance Web Programming:: (declare the variables; they are dead) Dog d1, d2; null d1 = new Dog (5, “bob”); d2 d1 d2 = new Dog (3, “ethel”); d1 = d2; ปริญญาโท สาขาวิชา เทคโนโลยี 15 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Memory Trace (bring d1 to life) Dog d1, d2; null d1 = new Dog (5, “bob”); d1 d2 = new Dog (3, “ethel”); d1 = d2; // Remember, new opens up // space and … ปริญญาโท สาขาวิชา เทคโนโลยี 16 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร d2 Memory Trace ITEC5620 - Advance Web Programming:: (bring d1 to life) Dog d1, d2; d1 = new Dog (5, “bob”); null d2 = new Dog (3, “ethel”); d2 d1 rabid=false d1 = d2; // Remember, new opens up // space and calls the class weight=5 name=“bob” ปริญญาโท สาขาวิชา เทคโนโลยี 17 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Memory Trace (bring d2 to life) Dog d1, d2; d1 = new Dog (5, “bob”); null d2 = new Dog (3, “ethel”); d1 d2 rabid=false d1 = d2; // Remember, new opens up // space and… weight=5 name=“bob” ปริญญาโท สาขาวิชา เทคโนโลยี 18 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร Memory Trace ITEC5620 - Advance Web Programming:: (bring d2 to life) Dog d1, d2; d1 = new Dog (5, “bob”); null d2 = new Dog (3, “ethel”); d1 d2 rabid=false rabid=false weight=5 weight=3 d1 = d2; // Remember, new opens up // space and calls the class name=“bob” ปริญญาโท สาขาวิชา เทคโนโลยี 19 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร name=“ethel” ITEC5620 - Advance Web Programming:: Memory Trace (comparison) d1 and d2 do NOT occupy null the same space in memory, d1 so they are NOT == Example: d1 == d2 evaluates to false d2 rabid=false rabid=false weight=5 weight=3 name=“bob” ปริญญาโท สาขาวิชา เทคโนโลยี 20 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร name=“ethel” Memory Trace ITEC5620 - Advance Web Programming:: (have d1 point to d2) Dog d1, d2; d1 = new Dog (5, “bob”); null d2 = new Dog (3, “ethel”); d1 d2 rabid=false rabid=false weight=5 weight=3 d1 = d2; // See the result in next slide name=“bob” ปริญญาโท สาขาวิชา เทคโนโลยี 21 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร name=“ethel” Memory Trace ITEC5620 - Advance Web Programming:: (have d1 point to d2) Dog d1, d2; d1 = new Dog (5, “bob”); null d2 = new Dog (3, “ethel”); d1 d2 d1 = d2; rabid=false rabid=false weight=5 weight=3 name=“bob” ปริญญาโท สาขาวิชา เทคโนโลยี 22 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร name=“ethel” Memory Trace ITEC5620 - Advance Web Programming:: (have d1 point to d2) Now, d1 and d2 are == null d1 But no one is pointing to this d2 rabid=false rabid=false weight=5 weight=3 name=“bob” name=“ethel” Because no one is pointing to it, we can no longer reference it. ปริญญาโท สาขาวิชา เทคโนโลยี 23 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Visibility OO motivation: protection/security We need a way of selectively “publishing” parts of a class and “hiding” other parts of the class Public & private ปริญญาโท สาขาวิชา เทคโนโลยี 24 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Visilibity Example class BMW_Z4 { private int ModelYear; Note the visibility change (most attributes will be public string LicensePlate; private) private bool TopUp; public void Drive() { Methods are and Console.WriteLine(“Roadin’ typically public Rockin’“); } public void OpenTop() ปริญญาโท สาขาวิชา เทคโนโลยี 25 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร Object Method & Attribute Visibility ITEC5620 - Advance Web Programming:: BMW_Z4 myCar; myCar = new BMW_Z4(); myCar.LicensePlate = "BMR4ME"; myCar.ModelYear = 2004; Illegal b/c private myCar.Drive(); myCar.OpenTop(); myCar.Drive(); ปริญญาโท สาขาวิชา เทคโนโลยี 26 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Properties Combines field/attribute with method Standard: Make attributes private Lower-case first letter of attribute Make properties public Upper-case first letter of properties Define “get” and “set” for each ปริญญาโท สาขาวิชา เทคโนโลยี 27 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Properties Example class BMW_Z4 { private int modelYear; Attributes: Lower-case first letter of attribute private string licensePlate; private bool topUp; public int ModelYear { get { return modelYear; } set { if (value >= 2003) modelYear = value; } } ปริญญาโท สาขาวิชา เทคโนโลยี 28 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร Properties: Upper-case first letter of properties ITEC5620 - Advance Web Programming:: Constructors So far, we’ve seen attributes and methods Constructor is a unique method Named same as the class name Automatically called when class is instantiated Useful for setting attributes & initializing the instance No return type (not even void) ปริญญาโท สาขาวิชา เทคโนโลยี 29 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Constructor Example class BMW_Z4 { private int modelYear; private string licensePlate; private bool topUp; public BMW_Z4 () { ModelYear = 2004; TopUp = false; LicensePlate = "DEALER"; } ปริญญาโท สาขาวิชา เทคโนโลยี 30 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Intermediate C# Parameter passing (ref, out, & value) Keywords: static, const, read-only Overloading Inheritance Polymorphism ปริญญาโท สาขาวิชา เทคโนโลยี 31 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Parameter Passing By default, parameters are passed by value A copy of the value is passed The original is not modifiable “ref” to create by-reference parameter passing Use A reference to the value is passed (akin to a pointer) The original (actual) parameter is modifiable ปริญญาโท สาขาวิชา เทคโนโลยี 32 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร By Value Parameter Example ITEC5620 - Advance Web Programming:: float CalculateCost (float unit_cost, int how_many) { return unit_cost * how_many; } static void Main() Even if you change these locally, they won’t { change in Main. ... line_cost = CalculateCost(uc, hm); ... } ปริญญาโท สาขาวิชา เทคโนโลยี 33 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร By Reference Parameter Example ITEC5620 - Advance Web Programming:: void UpdateGrade (ref float grade, float factor) { grade += factor; } static void Main() { ... for(i=0; i < grades.Count(); i++) UpdateGrade(grades[i], 0.05); ... Grade will be updated; } information is taken in and modifies the original ปริญญาโท สาขาวิชา เทคโนโลยี 34 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Out Parameter Example void ReadChoice (out int choice) { do { Console.WriteLine("Please enter a choice 1-4: "); choice = Int32.Parse(Console.ReadLine()); } while ((choice < 1) || (choice > 4)) } static void Main() { ... ReadChoice(c); ... } Choice is generated in the module and then returned to Main ปริญญาโท สาขาวิชา เทคโนโลยี 35 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Static Each instance of a class (called an object) has a copy of the attributes Changing an attribute in one object doesn’t affect the attribute of another object But what if we want persistence ปริญญาโท สาขาวิชา เทคโนโลยี 36 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Static Variables void PrintNumbers () { static int count = 0; Console.WriteLine(count); count++; } static void Main() { ... for(i=0; i < 50; i++) PrintNumbers(); ... } ปริญญาโท สาขาวิชา เทคโนโลยี 37 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Static Attributes class BMW_Z4 { public static int VehicleId = 0; ... } static void Main() { ... BMW_Z4 my_z4 = new BMW_Z4(); // has VehicleId of 0 BMW_Z4 your_z4 = new BMW_Z4(); // has VehicleId of 1 ... } ปริญญาโท สาขาวิชา เทคโนโลยี 38 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Const are just that – variable They can be changed programmatically via the assignment operator (=) But there are times when some values should be immutable Preface the declaration with “const” Variables ปริญญาโท สาขาวิชา เทคโนโลยี 39 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Const Example class BMW_Z4 { public const int MaxSpeed = 185; private int currentSpeed; public void Accelerate() { currentSpeed += 5; if (currentSpeed > MaxSpeed) currentSpeed = MaxSpeed; } ... } ปริญญาโท สาขาวิชา เทคโนโลยี 40 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Read-Only Fields const only works if the initial value is known at compile time. The readonly keyword allows a field to be initialized by the constructor, but not subsequently modified. class Foo { public readonly int numUsers; Foo() { numUsers = 10; } 41 ปริญญาโท สาขาวิชา เทคโนโลยีสารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Overloading Overloading involves using the same method/function name Vary the number of parameters Vary the type of parameters Cannot just change return type (ambiguity in invocation) Useful to keep things simple Squaring a number… ปริญญาโท สาขาวิชา เทคโนโลยี 42 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Overloading Example int Square (int i) { return i * i; } Same function name the different types of parameters float Square (float i) { return i * i; } static void Main() { 43 ปริญญาโท สาขาวิชา เทคโนโลยีสารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Operator Overloading class BMW_Z4 { ... public BMW_Z4 () { Initialize(0, 2004, false); } public BMW_Z4 (int my) { Initialize(0, my, false); } Notice same method name, different parameters private void Initialize(int cs, int my, bool tu) { Place common currentSpeed = cs; initialization in a ModelYear = my; separate function TopUp = tu; } ... ปริญญาโท สาขาวิชา เทคโนโลยีสารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร 44 Inheritance ITEC5620 - Advance Web Programming:: Inheritance allows one class to take on the properties of another Super class-subclass relationship Sometimes called parent-child relationship Use the keyword extends to express this relationship will “inherit” certain attributes and methods Subclass ปริญญาโท สาขาวิชา เทคโนโลยี 45 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Class Hierarchy Mammal int weight giveBirth( ) Answer: • Dog has three attributes • weight, numLegs, rabid • Two from inheritance, one it declared itself NOTE: Land-Mammal is a superclass to Dog, but a subclass to Mammal Land-Mammal int numLegs Dog boolean rabid Chihuahua Question: how many attributes does Dog have? SheepDog ปริญญาโท สาขาวิชา เทคโนโลยี 46 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร Visibility and Inheritance ITEC5620 - Advance Web Programming:: – allows all to see private – allows only class in which defined to see protected – allows class and all subclasses that inherit to see public Consequently, we’ll now use protected instead of private by default… (common) ปริญญาโท สาขาวิชา เทคโนโลยี 47 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร Class Access public ITEC5620 - Advance Web Programming:: Access not limited Protected Access limited to the containing class or type derived from the containing class (i.e. subclasses) internal Access limited to this program protected internal Access limited to this program ปริญญาโท สาขาวิชา เทคโนโลยี 48 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: C# Syntax class Person { ... } Person Student class Student : Person { ... } Professor Notice the use of “:” class Professor : Person { ... } ปริญญาโท สาขาวิชา เทคโนโลยี 49 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Polymorphism Virtual methods must be declared as such or they are statically bound at compile time. The use of the virtual keyword differs from C++. virtual is used only in the base class. Derived classes must use the ปริญญาโท สาขาวิชา เทคโนโลยี 50 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Polymorphism - contd. public class Animal { virtual public bool canFly() { return false; } } public class Bird: Animal { override public bool canFly() { return true; } } public class Penguin: Bird { override public bool canFly() { return false; } } ปริญญาโท สาขาวิชา เทคโนโลยี 51 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร The Base Class: “Object” ITEC5620 - Advance Web Programming:: All classes in C# inherit (sometimes implicitly) from Object Includes common set: • See next slide Often useful to override (implement) these virtual functions ปริญญาโท สาขาวิชา เทคโนโลยี 52 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Predefined Types object Public Methods public bool Equals(object) protected void Finalize() public int GetHashCode() public System.Type GetType() protected object MemberwiseClone() public void Object() public string ToString() ปริญญาโท สาขาวิชา เทคโนโลยี 53 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Abstract Classes These work somewhat like they do in C++ A class with at least one abstract method can't be instantiated. Derived classes must implement the abstract ปริญญาโท สาขาวิชา เทคโนโลยี 54 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร Abstract Classes: Example abstract public class Shape { } ITEC5620 - Advance Web Programming:: Shape Shape abstract public double area(); public class Rectangle: Shape { Rectangle private double sideX, sideY; … public override double area() {......} } public class Circle: Shape { private double radius; … public override double area() {......} } -----Rectangle rec = new Rectangle(4.0, 3.5); double aRec = rec.area(); //? Circle cir = new Cirle(21.5); double aCir = cir.area(); //? ปริญญาโท สาขาวิชา เทคโนโลยี 55 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร Circle More Features in C# ITEC5620 - Advance Web Programming:: Boxing and Unboxing int i = 123; i object o = i; o int j = (int)o; Benefits 123 System.Int32 123 j 123 of boxing Enables polymorphism across all types Collection classes work with all types ปริญญาโท สาขาวิชา เทคโนโลยี 57 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Types: Enums An enum defines a type name for a related group of symbolic constants Choices must be known at compile-time Strongly typed • No implicit conversions to/from int ปริญญาโท สาขาวิชา เทคโนโลยี 58 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร Types: enum Example ITEC5620 - Advance Web Programming:: enum Color: byte { Red = 1, Green = 2, Blue = 4, Black = 0, White = Red | Green | Blue } Color c = Color.Black; Console.WriteLine(c); Console.WriteLine(c.Format()); // 0 // Black ปริญญาโท สาขาวิชา เทคโนโลยี 59 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Types: Enums All enums derive from System.Enum Provides methods to • determine underlying type • test if a value is supported • initialize from string constant • retrieve all values in enum •… ปริญญาโท สาขาวิชา เทคโนโลยี 60 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Program Structure Namespaces Namespaces provide a way to uniquely identify a type Provides logical organization of types Namespaces can span assemblies Can nest namespaces There is no relationship ปริญญาโท สาขาวิชา เทคโนโลยี 61 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Program Structure Namespaces namespace N1 { class C1 { class C2 { } } namespace N2 { class C2 { } } } // N1 // N1.C1 // N1.C1.C2 // N1.N2 // N1.N2.C2 ปริญญาโท สาขาวิชา เทคโนโลยี 62 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Program Structure Namespaces The using statement lets you use types without typing the fully qualified name Can always use a fully using N1; C1 a; qualified //name The N1. is implicit N1.C1 b; // Fully qualified name C2 c; N1.N2.C2 d; C1.C2 e; // Error! C2 is undefined // One of the C2 classes // The other one ปริญญาโท สาขาวิชา เทคโนโลยี 63 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Program Structure Namespaces using statement also lets you create aliases The using C1 = N1.N2.C1; using N2 = N1.N2; C1 a; N2.C1 b; // Refers to N1.N2.C1 // Refers to N1.N2.C1 ปริญญาโท สาขาวิชา เทคโนโลยี 64 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Program Structure Namespaces Best practice: Put all of your types in a unique namespace Have a namespace for your company, project, product, etc. Look at how the .NET ปริญญาโท สาขาวิชา เทคโนโลยี 65 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Program Structure Main Method Execution begins at the static Main() method Can have only one method with one of the following signatures in an assembly static void Main() static int Main() static void Main(string[] args) static int Main(string[] args) ปริญญาโท สาขาวิชา เทคโนโลยี 66 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: THE END ปริญญาโท สาขาวิชา เทคโนโลยี 67 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming Review ASP.NET using Visual Studio.NET 2005 อ.ชไลเวท พิพฒ ั พรรณวงศ ์ Chalaivate Pipatpannawong Computer Instructor Microsoft Certificate Professional Web : www.9Expert.co.th ; Thaiwebdev.com E-Mail: [email protected] ปริญญาโท สาขาวิชา เทคโนโลยีสารสนเทศ Managing State What is State Management? Without State Management ITEC5620 - Advance Web Programming:: With State Management Login.aspx Login.aspx Please enter your logon information: First Name Please enter your logon information: First Name John Last Name John Last Name Chen Chen Submit Greetings.aspx Hello Web Server Submit Greetings.aspx Hello John Chen I forget who you are!! ปริญญาโท สาขาวิชา เทคโนโลยี 70 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร Web Server Types of State Management Server-Side State Client-Side State ITEC5620 - Advance Web Programming:: Management Management Application state Cookies Information is Text file stores available to all users information to of a Web application maintain state application Session state The ViewState property Information is Retains values available only to a between multiple user of a specific requests for the same session page Database 71 ปริญญาโท สาขาวิชา เทคโนโลยีสารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร Server-Side State Management Application state is a global ITEC5620 - Advance Web Programming:: storage mechanism accessible from all pages in the Web application Session state is limited to the current browser session Web Server are preserved through Client Computer the use of application and Application and Session variables session variables SessionID Values Scalability ปริญญาโท สาขาวิชา เทคโนโลยี 72 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร Client-Side State Management Uses cookies to maintain state ITEC5620 - Advance Web Programming:: Persistent cookies Temporary/ Non-persistent cookies Less reliable than server-side state management options User can delete cookies Less secure than server-side state management options Client Computer Limited amount of information Cookies Client-side Web Server restrictions on file sizes ปริญญาโท สาขาวิชา เทคโนโลยี 73 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Initializing Application and Session Variables Variables are initialized in Global.asax The Application object shares information among all users of a Sub Application_Start(s Web application As Object,e As EventArgs) Application("NumberofVisitors") = 0 End Sub protected void Application_Start(Object sender,EventArgs e) { Application["NumberofVisitors"] = 0; } ปริญญาโท สาขาวิชา เทคโนโลยี 74 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร Using Application and Session Variables Set session and application ITEC5620 - Advance Web Programming:: Session("BackColor") = "blue" Application.Lock() Application("NumberOfVisitors") += 1 Application.UnLock() variables Session["BackColor"] = "blue"; Application.Lock(); Application["NumberOfVisitors"] = (int)Application["NumberOfVisitors"] Application.UnLock(); Read + 1; session and application strBgColor = Session("BackColor") variables= Application("NumberOfVisitors") lblNbVisitor.Text strBgColor = (string)Session["BackColor"]; lblNbVisitor.Text = Application["NumberOfVisitors"].ToString(); ปริญญาโท สาขาวิชา เทคโนโลยี 75 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร Application and Session Variable Duration ITEC5620 - Advance Web Programming:: Session variables have a set duration after last access Default is 20 minutes Session duration can be <configuration> changed in Web.config: <system.web> <sessionState timeout="10" /> </system.web> </configuration> ปริญญาโท สาขาวิชา เทคโนโลยี 76 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Scalable Storage of Application and Session Variables By default, the session state is managed in process Disadvantage of in process storage: Not Scalable ASP.NET provides out of process storage of session state Web farm State server State can be stored in aSession SQL and Application variables Server database or a state -Orserver SQL Client Advantages storage: of out of process Session and Application variables ปริญญาโท สาขาวิชา เทคโนโลยี 77 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Saving Application and Session Variables in a Database 1 Configure the session state in Web.config Mode is set to sqlserver or stateserver <sessionState mode="SQLServer" sqlConnectionString="data source=SQLServerName; Integrated security=true" /> Then, configure the SQL server 2 OSQL creates several stored procedures and temporary databases for storing the variables c:\> OSQL –S SQLServerName –E <InstallSqlState.sql ปริญญาโท สาขาวิชา เทคโนโลยี 78 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร Using Cookies to Store Session Data Creating a cookie: ITEC5620 - Advance Web Programming:: HttpCookie objCookie = new HttpCookie("myCookie"); HttpCookie DateTime now objCookie = DateTime.Now; = new HttpCookie("myCookie"); DateTime now = DateTime.Now; objCookie.Values.Add("Time", now.ToString()); objCookie.Values.Add("Time", now.ToString()); objCookie.Values.Add("ForeColor", "White"); objCookie.Values.Add("ForeColor", "Blue"); objCookie.Values.Add("BackColor", "White"); objCookie.Values.Add("BackColor", "Blue"); objCookie.Expires = now.AddHours(1); To create a persistent Response.Cookies.Add(objCookie); cookie, specify the Response.Cookies.Add(objCookie); expiration time Set-Cookie: Username=John+Chen; path=/; domain=microsoft.com; Expires=Tuesday, 01-Feb-05 00.00.01 GMT Cookie contains information about the domain name ปริญญาโท สาขาวิชา เทคโนโลยี 79 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร Retrieving Information from a Cookie ITEC5620 - Advance Web Programming:: Read the cookie Dim objCookie As HttpCookie = Request.Cookies("myCookie") HttpCookie objCookie = Request.Cookies["myCookie"]; Retrieve values from the lblTime.Text = objCookie.Values("Time") lblTime.ForeColor = System.Drawing.Color.FromName _ (objCookie.Values("ForeColor")) lblTime.BackColor = System.Drawing.Color.FromName _ (objCookie.Values("BackColor")) cookie lblTime.Text = objCookie.Values["Time"]; lblTime.ForeColor = System.Drawing.Color.FromName (objCookie.Values["ForeColor"]); lblTime.BackColor = System.Drawing.Color.FromName (objCookie.Values["BackColor"]); ปริญญาโท สาขาวิชา เทคโนโลยี 80 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร Using Cookieless Sessions Each active session is identified and tracked ITEC5620 - Advance Web Programming:: using session IDs Session IDs are communicated across clientserver requests using an HTTP cookie or included in the URL Cookieless sessions http://server/(h44a1e55c0breu552yrecobl)/page.aspx Session ID information is encoded into URLs Cannot use absolute URLs Most browsers limit the URL size to 255 characters, which 81limits use of ปริญญาโท สาขาวิชา เทคโนโลยีสารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร Setting Up Cookieless Sessions ITEC5620 - Advance Web Programming:: Session state is configured in the <SessionState> section of Web.config Set cookieless = true <sessionState cookieless="true" /> ปริญญาโท สาขาวิชา เทคโนโลยี 82 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร Configuring, Optimizing, and Deploying a Microsoft ASP.NET Web Application What Is the Cache Object? An object used to store information ITEC5620 - Advance Web Programming:: One Cache object per Web Application An alternative to application variables Not used to store information in Cache("myKey") = myValue session variables Cache["myKey"] = myValue; Uses key-value pairs to store and retrieve items ปริญญาโท สาขาวิชา เทคโนโลยี 84 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Advantages of Using the Cache Object Faster than creating a new object for each request Automatic cache resource management Supports callback functions Supports removal based on dependencies ปริญญาโท สาขาวิชา เทคโนโลยี 85 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร How to Use the Cache Object Writing to the Cache object: ITEC5620 - Advance Web Programming:: 'Implicit method Cache("myKey") = myValue 'Explicit method Cache.Insert("myKey", myValue, Dependency, AbsoluteExpiration, _ SlidingExpiration, CacheItemPriority, CacheItemRemovedCallBack) //Implicit method Cache["myKey"] = myValue; //Explicit method Cache.Insert("myKey", myValue, Dependency, AbsoluteExpiration, SlidingExpiration, CacheItemPriority, CacheItemRemovedCallBack); ปริญญาโท สาขาวิชา เทคโนโลยี 86 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: How to Use the Cache Object • Retrieving values from the Cache object: myValue = Cache("myKey") myValue = Cache["myKey"]; ปริญญาโท สาขาวิชา เทคโนโลยี 87 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร Removing Items from the Cache Object AbsoluteExpiration time ITEC5620 - Advance Web Programming:: Cache.Insert(“myKey”, myValue,null, DateTime.Now.AddMinute(5), null); SlidingExpiration time Cache.Insert(“myKey”, myValue, null, null, TimeSpan.FromSeconds(20)); Dependent on a changed value Cache.Insert(“myKey”, myValue, new CacheDependency(Server.MapPath(“myDoc.xml”))); ปริญญาโท สาขาวิชา เทคโนโลยี 88 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Removing Items from the Cache Object(continued) Cache item priority Cache.Insert(“myKey”, myValue, null, null, Cache.NoSlidingExpiration, CacheItemPriority.High, onRemove); ปริญญาโท สาขาวิชา เทคโนโลยี 89 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร How to Use Page Output Caches ITEC5620 - Advance Web Programming:: Cache content is generated from dynamic pages Entire Web page is available in cache Set cache duration in seconds <%@the OutputCache Set VaryByParam property Duration="900" to control the number VaryByParam="none" %> of page variations in the cache ปริญญาโท สาขาวิชา เทคโนโลยี 90 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร How to Use Fragment Caching ITEC5620 - Advance Web Programming:: Convert the page fragment into a user control Set the Duration and varyByParam properties <%@ OutputCache Duration="120" VaryByParam="none" %> ปริญญาโท สาขาวิชา เทคโนโลยี 91 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร Overview of Configuration Methods ITEC5620 - Advance Web Programming:: Machine.config file Machine-level settings Web.config files Application and directory-level settings Both Machine.config and Web.config files are: Well-formed XML ปริญญาโท สาขาวิชา เทคโนโลยี 92 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร Storing and Retrieving Data in Web.config ITEC5620 - Advance Web Programming:: Storing application settings in a Web.config file <configuration> <appSettings> <add key="pubs" value="server=localhost; integrated security=true; database=pubs"/> </appSettings> </configuration> ปริญญาโท สาขาวิชา เทคโนโลยี 93 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร Retrieving application settings from a Web.config file ITEC5620 - Advance Web Programming:: Dim strPubs As String = _ ConfigurationSettings.AppS ettings("pubs") AppSettingsReader App = new AppSettingsReader(); string strPubs = (string)App.GetValue("pubs", typeof(string)); ปริญญาโท สาขาวิชา เทคโนโลยี 94 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร Using Dynamic Properties ITEC5620 - Advance Web Programming:: Store property values in Web.config files rather than in the application's compiled code Allows easy updates without recompiling the application Enable and configure ปริญญาโท สาขาวิชา เทคโนโลยี 95 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร Web Application Deployment ITEC5620 - Advance Web Programming:: Copy files locally or FTP files remotely Configure the target folder as a virtual directory in IIS Copy all necessary files, including the \bin directory and content No need to register components ปริญญาโท สาขาวิชา เทคโนโลยี 96 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร Preparing a Web Application for Deployment 1. Build the Web application ITEC5620 - Advance Web Programming:: 2. Do not select unnecessary files 3. Visual Studio .NET solution files (.vbproj, .vbproj.webinfo, .csproj, .csproj.webinfo, etc.) Resource (.resx) files Code-behind pages (.vb, .cs) Copy or FTP necessary files to the production directory 97 ปริญญาโท สาขาวิชา เทคโนโลยีสารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร Updating Your Web Application ITEC5620 - Advance Web Programming:: Copy or FTP files to update the Web application Do not need to stop and restart IIS .dll files can be updated while the site is still running Output cache protects existing users ปริญญาโท สาขาวิชา เทคโนโลยี 98 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร Consuming and Creating XML Web Services What is an XML Web Service? Programmable logic accessible ITEC5620 - Advance Web Programming:: by standard Web protocols Allows applications to send and receive information across the Internet Language, protocol, and platform independent Stateless architecture Can be asynchronous Based on an 100 evolving W3C ปริญญาโท สาขาวิชา เทคโนโลยีสารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Why Use XML Web Services? Northwind Traders Travel Site Weather XML Web Service Pick your destination: Redmond The weather Forecast calls for: Rain Internet The exchange rate is: $1.56 Exchange Rate XML Web Service We can fly you there for only: $1,999.98 Airfare XML Web Service Airfare Database ปริญญาโท สาขาวิชา เทคโนโลยี 101 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร How to Call an XML Web Service Using HTTP ITEC5620 - Advance Web Programming:: 1 2 3 Navigate to the XML Web service URL Select and XMLWeb Servicemethod 4 Call the XML Web service method View the XML ปริญญาโท สาขาวิชา เทคโนโลยี 102 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร Using Proxies to Call XML ITEC5620 - Advance Web Programming:: Web Services Appear the same as the original class, but do not contain application logic Use SOAP to interact with the XML Web Service Created from the ServiceName.asmx.wsdl file Web Internet XML Web Form Add members to manage Service Proxy interactions with the XML Web SOAP service and support ปริญญาโท สาขาวิชา เทคโนโลยี 103 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: How to Use a Proxy to Call an XML Web Service Create a Web reference for the XML Web Service 2 3 Create an instance of the XML 2. 4 Web Service 3. Call the methods of thesender, XML private void Web Button1_Click(object System.EventArgs e) Web Service { 4. Build the ASP.NET Web GetStocks.localhost.service1 Application ProxyGetStocks = new 1 1. GetStocks.localhost.Service1(); lblResults.Text = 104 ปริญญาโท สาขาวิชา เทคโนโลยีสารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร How to Create an XML Web Service Create a new XML Web Service project ITEC5620 - Advance Web Programming:: 1 1. in Visual Studio .NET 1. 2 Declare the WebMethod functions 1. 3 Build the XML Web Service project 1. 4 Test with a browser ปริญญาโท สาขาวิชา เทคโนโลยี 105 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: XML Web Service Code .asmx page <%@ WebService Language="c#" Codebehind="Service1.asmx.cs" Class="XMLWebServiceName.Service1" %> using System; using System.Web.Services; class Service1 { [WebMethod] public type function1() { //function_here } } .asmx.vb page ปริญญาโท สาขาวิชา เทคโนโลยี 106 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ADO.NET ITEC5620 - Advance Web Programming:: What Is a Connected Environment? A connected environment is one in which users are constantly connected to a data source Advantages: Environment is easier to secure Concurrency is more easily controlled Data is more likely to be current than in other scenarios Disadvantages: Must have a constant network connection Scalability ปริญญาโท สาขาวิชา เทคโนโลยี 108 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: What Is a Disconnected Environment? In a disconnected environment, a subset of data from a central data store can be copied and modified independently, and the changes merged back into the central data store Advantages You can work at any time that is convenient for you, and can connect to a data source at any ปริญญาโท สาขาวิชา เทคโนโลยี 109 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Other users can use the connection A disconnected environment improves the scalability and performance of applications Disadvantages Data is not always up to date Change conflicts can occur ปริญญาโท สาขาวิชา เทคโนโลยี 110 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: What Is ADO .NET? ADO.NET is a set of classes for working with data. It provides: An evolutionary, more flexible successor to ADO A system designed for disconnected environments A programming model with advanced XML support A set of classes, interfaces, structures, and enumerations that manage data access from within the .NET Framework ปริญญาโท สาขาวิชา เทคโนโลยี 111 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: What Are the DataRelated Namespaces? The data-related namespaces include: System.Data System.Data.Common System.Data.SqlClient System.Data.OleDb System.Data.SqlTypes ปริญญาโท สาขาวิชา เทคโนโลยี 112 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: The ADO .NET Object Model DataSet SQL Server .NET Data Provider OLE DB .NET Data Provider SQL Server 7.0 (and later) OLEDB sources (SQL Server 6.5) ปริญญาโท สาขาวิชา เทคโนโลยี 113 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Using ADO.NET Classes in a Connected Scenario SqlDataReader In a connected SqlCommand SqlConnection SQL Server 7.0 (and later) scenario, resources are held on the server until the connection is closed 1. Open connection ปริญญาโท สาขาวิชา เทคโนโลยี 114 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Using ADO.NET Classes in a DisconnectedScenario In a disconnected DataSet SqlDataAdapter SqlConnection scenario, resources are not held on the server while the data is processed 1. Open SQL Server 7.0 (and later) connection 2. Fill the DataSet 3. Close connection 4. Process the ปริญญาโท สาขาวิชา เทคโนโลยี 115 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร Connecting to Data Sources What Are .NET Data Providers? ITEC5620 - Advance Web Programming:: Definition A .NET data provider is a set of classes that you use to connect to a data source, and retrieve and update data Types of .NET data providers ปริญญาโท สาขาวิชา เทคโนโลยี 117 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร The .NET Data Provider Classes XxxConnection – for example, ITEC5620 - Advance Web Programming:: SqlConnection • XxxTransaction – for example, SqlTransaction • XxxException – for example, SqlException • XxxError – for example, SqlError XxxCommand – for example, SqlCommand ปริญญาโท สาขาวิชา เทคโนโลยี 118 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร The .NET Data Provider Classes ITEC5620 - Advance Web Programming:: XxxDataReader – for example, SqlDataReader XxxDataAdapter – for example, SqlDataAdapter – for example, SqlClientPermission XxxPermission ปริญญาโท สาขาวิชา เทคโนโลยี 119 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร Which .NET Data Provider Should You Use? SQL Server .NET Data Provider ITEC5620 - Advance Web Programming:: SQL OLE Server version 7.0 or later DB .NET Data Provider SQL Server 6.5, Microsoft Access, Oracle, other data sources with OLE DB providers ปริญญาโท สาขาวิชา เทคโนโลยี 120 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Database Security Using SQL Server security Windows Authentication Mixed Mode (Windows Authentication and SQL Server authentication) ปริญญาโท สาขาวิชา เทคโนโลยี 121 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร What Is a Connection String? A connection string defines the parameters ITEC5620 - Advance Web Programming:: required to make a connection to a data source Connection string parameters Provider (OLE DB only) Data Source Initial Catalog Integrated Security User ID/Password ปริญญาโท สาขาวิชา เทคโนโลยี 122 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร How to Set a Connection String You can set the ConnectionString property ITEC5620 - Advance Web Programming:: only when the connection is closed To reset a connection string, you must close and reopen the connection Microsoft Access connection OleDb.OleDbConnection cnNorthwind = new OleDb.OleDbConnection(); cnNorthwind.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=\Samples\Northwind.mdb;“; ปริญญาโท สาขาวิชา เทคโนโลยี 123 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Opening and Closing a Connection Opening and closing connections explicitly Open and Close methods Opening and closing connections implicitly Data adapters can open and ปริญญาโท สาขาวิชา เทคโนโลยี 124 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร How to Handle SqlExceptions Write the code to execute inside a Try block ITEC5620 - Advance Web Programming:: Write a Catch statement for each specific exception that you want to catch System.Data.SqlClient.SqlException Errors collection SqlError properties (Class, Number) Write a generic Catch statement for all other exceptions Write a Finally statement to run the code no matter what happens ปริญญาโท สาขาวิชา เทคโนโลยี 125 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร Performing Connected Database Operations Object Model for Connected Applications Classes in a Connected Application ITEC5620 - Advance Web Programming:: Data Source XxxDataReader XxxCommand XxxConnection XmlReader XxxParameter XxxParameter XxxParameter ปริญญาโท สาขาวิชา เทคโนโลยี 127 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร What Is a Command Object? ITEC5620 - Advance Web Programming:: A command object is a reference to a SQL statement or stored procedure Properties (Name), Connection, CommandType, CommandText, Parameters Methods ExecuteScalar, ExecuteReader, ExecuteNonQuery 128 ปริญญาโท สาขาวิชา เทคโนโลยีสารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: How to Create a Stored Procedure Server Explorer On the View menu, click Server Explorer, or press Ctrl+Alt+S Create a data connection Click New Stored Procedure Insert SQL ปริญญาโท สาขาวิชา เทคโนโลยี 129 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: How to Create a Command Object Programmatically Server Explorer On the View menu, click Server Explorer, or press Ctrl+Alt+S Drag stored procedure onto form or component Toolbox Use SqlConnection or OleDbConnection ปริญญาโท สาขาวิชา เทคโนโลยี 130 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร What Are Command Parameters? ITEC5620 - Advance Web Programming:: Introduction SQL statements and stored procedures can have input and output parameters, and a return value Command parameters allow these parameters to be set and retrieved SqlParameter, OleDbParameter Properties ปริญญาโท สาขาวิชา เทคโนโลยี 131 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร How to Create Parameters for a Command Programmatically Object ITEC5620 - Advance Web Programming:: Code example SqlParameter prmName = new SqlParameter ("@CatName", SqlDbType.NChar, 15); prmName.Direction = ParameterDirection.Output; cmdCountProds.Parameters.Add(prmName) Using the Visual Studio .NET graphical tools ปริญญาโท สาขาวิชา เทคโนโลยี 132 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Why Return a Single Value in a Command? ADO.NET is more efficient than ADO, where a complete record set is returned Examples Units in stock for a particular product How many products? ปริญญาโท สาขาวิชา เทคโนโลยี 133 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร How to Execute a Command That Returns a Single Value Call the ExecuteScalar method ITEC5620 - Advance Web Programming:: ExecuteScalar returns a value of the type Object Use CType or a cast, to convert into appropriate type cmProducts.Parameters("@ProdID").Value = Microsoft Visual Basic® code example: 42; cnNorthwind.Open(); int qty = (int)cmProducts.ExecuteScalar(); cnNorthwind.Close(); ปริญญาโท สาขาวิชา เทคโนโลยี 134 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: How to Retrieve Output and Return Values How to get output parameters from a command cmProducts.Parameters("@CatName").Value; How to get the return value from a stored procedure cmProducts.Parameters("@RETURN_VALUE").Value ปริญญาโท สาขาวิชา เทคโนโลยี 135 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: Returning Rows DataReader Read-only, forward-only, stream of rows The ExecuteReader method Returns a DataReader For example, SqlDataReader, OleDbDataReader ปริญญาโท สาขาวิชา เทคโนโลยี 136 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: DataReader Properties and Methods Read method Loads the next row Returns true if a row exists, false if at end of rows methods – for example, GetString, GetInt32 GetValues method IsDbNull method GetXxx ปริญญาโท สาขาวิชา เทคโนโลยี 137 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: How to Use a DataReader to Process Rows Using a DataReader object to process a result set Code example SqlCommand cmProducts = New SqlCommand( _ "SELECT ProductName, UnitsInStock " & _ "FROM Products", cnNorthwind); cnNorthwind.Open(); SqlDataReader rdrProducts; rdrProducts = cmProducts.ExecuteReader(); while (rdrProducts.Read()) { ListBox1.Items.Add(rdrProducts.GetString(0)) } rdrProducts.Close(); ปริญญาโท สาขาวิชา เทคโนโลยี 138 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร What Are DDL and DCL Statements? Definition ITEC5620 - Advance Web Programming:: Automate database administration tasks DDL and DCL statements CREATE, ALTER, DROP, GRANT, DENY, REVOKE Code example dbo.SummarizeProducts CREATE PROCEDUREAS CREATE TABLE ProductSummary ( ProductName nvarchar(40), CategoryName nvarchar(15) ) ปริญญาโท สาขาวิชา เทคโนโลยี 139 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: How to Execute DDL and DCL Statements ExecuteNonQuery method Returns count of rows affected Code example cnNorthwind.Open(); int affected = _ cmSummarizeProducts.ExecuteNonQuery(); cnNorthwind.Close(); MessageBox.Show("Records affected: " + affected); ปริญญาโท สาขาวิชา เทคโนโลยี 140 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: What Are DML Modification Statements? Definition Modify DML data in the database Statements INSERT, UPDATE, DELETE CREATE PROCEDURE dbo.InsertRegion Code example ( @RegID int, @RegName nchar(50) ) ASINSERT INTO Region VALUES (@RegID, @RegName) ปริญญาโท สาขาวิชา เทคโนโลยี 141 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: How to Execute DML Modification Statements To execute a DML statement ExecuteNonQuery method Code example cnNorthwind.Open(); int affected = cmPrices.ExecuteNonQuery(); cnNorthwind.Close(); MessageBox.Show("Records affected: " & _ affected); ปริญญาโท สาขาวิชา เทคโนโลยี 142 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร Building DataSets Disconnected Architecture SQL Server 2000 Categories SQL Server 6.5 Products Customers SqlDataAdapter DataSet Categories Products ITEC5620 - Advance Web Programming:: Orders OleDbDataAdapter Employees XML File Customers Orders XmlDataDocument XML Web service ปริญญาโท สาขาวิชา เทคโนโลยี 144 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร What Are DataSets, DataTables, and DataColumns? DataS ITEC5620 - Advance Web Programming:: et DataTa DataTa ble ble Server Conn Store d ecti Databas Proce on e dure Data Store ปริญญาโท สาขาวิชา เทคโนโลยี 145 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: The DataSet Object Model Common collections Tables (collection of DataTable objects) Relations (collection of DataRelation objects) Data binding to Web and Windows controls supported DataColumn DataTable Schema can be defined DataRow programmatically or using XSD DataRelation Constraints ปริญญาโท สาขาวิชา เทคโนโลยี 146 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร How to Create a DataSet, a DataTable, and a DataColumn Creating a DataSet ITEC5620 - Advance Web Programming:: Drag and drop a DataSet control from the Toolbox Creating a DataTable Edit the Tables collection of a DataSet by using the Properties window Creating a DataColumn and adding it to a DataTable 147 ปริญญาโท สาขาวิชา เทคโนโลยีสารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร Creating Custom Expressions ITEC5620 - Advance Web Programming:: Definition Custom expressions are columns derived from calculations, rather than stored values Using the DataColumn Expression property Sum([Unit Price] * [Quantity]) Aggregate functions can use parent/child relationships ปริญญาโท สาขาวิชา เทคโนโลยี 148 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: How to Bind Data to a Windows Control Simple data binding Binding to a simple control that can only display a single value – for example, a text box Complex data binding Binding to a more complex control that can display multiple values – for example, ปริญญาโท สาขาวิชา เทคโนโลยี 149 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: How to Bind a DataSet to a DataGrid DataSource property Can be a DataSet, DataTable, or DataView DataMember Can be a DataTable if the DataSource is a DataSet ปริญญาโท สาขาวิชา เทคโนโลยี 150 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: How to Save and Open a DataSet Two DataSet methods ReadXml WriteXml Pass the path and filename as a string parameter ReadXml raises an exception if the file does not exist WriteXml overwrites existing files ปริญญาโท สาขาวิชา เทคโนโลยี 151 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร What Is a DataView Object? ITEC5620 - Advance Web Programming:: DataS DataTa et DataTa ble ble DataVi ew Windows and Web controls Server Conn Store d ecti Proce on Databas edure Data ปริญญาโท สาขาวิชา เทคโนโลยี 152 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร How to Define a DataView ITEC5620 - Advance Web Programming:: Creating a DataView by using form controls Creating a DataView DataView dvProducts = New DataView(dsNorthwind.Tables("Products") programmatically ); dvProducts.Sort = "UnitPrice“; dvProducts.RowFilter = "CategoryID > 4“; grdProducts.DataSource = dvProducts; dvProducts.Table = dsNorthwind.Tables("Products") ; ปริญญาโท สาขาวิชา เทคโนโลยี 153 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร What Is a DataAdapter? ITEC5620 - Advance Web Programming:: DataSet Data source DataAdapter DataTable Fill Update DataAdapter DataTable Fill Update ปริญญาโท สาขาวิชา เทคโนโลยี 154 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร The XxxDataAdapter Object Model ITEC5620 - Advance Web Programming:: XxxDataAdapter SelectCommand UpdateCommand InsertCommand DeleteCommand XxxCommand XxxCommand XxxCommand XxxDataReader XxxCommand XxxConnection sp_SELECT sp_UPDATE sp_INSERT sp_DELETE ปริญญาโท สาขาวิชา เทคโนโลยี 155 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: DataAdapter Properties and Methods DataAdapter properties SelectCommand InsertCommand UpdateCommand DeleteCommand Methods used by DataAdapters Fill Update ปริญญาโท สาขาวิชา เทคโนโลยี 156 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร How to Create a DataAdapter That Uses a New SELECT Statement You can create a DataAdapter to execute a ITEC5620 - Advance Web Programming:: new SELECT statement Read-only data access for disconnected applications Two ways to create the DataAdapter Use the Data Adapter Configuration Wizard Write the code yourself You must specify A new or existing connection ปริญญาโท สาขาวิชา เทคโนโลยี 157 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร How to Create a Data Adapter That Uses an Existing You can create a DataAdapter Stored Procedure ITEC5620 - Advance Web Programming:: programmatically to execute an existing stored procedure by: Specifying a stored procedure for SelectCommand Specifying stored procedures for InsertCommand, UpdateCommand, and DeleteCommand if required Create the DataAdapter by using the wizard, or in code You must specify: ปริญญาโท สาขาวิชา เทคโนโลยี 158 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร How to Fill a Dataset Efficiently ITEC5620 - Advance Web Programming:: Define an explicit schema before you fill the DataSet DataTables, DataColumns, and DataRelations are known before the data is loaded Visual C# Example the data to be loaded more efficiently Enables ปริญญาโท สาขาวิชา เทคโนโลยี 159 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร How to Create a Data Adapter That Uses an Existing Stored Procedure To define an explicit DataSet schema ITEC5620 - Advance Web Programming:: Create a typed DataSet class: dsCustomers.Customers.BeginLoadData(); daCustomers.Fill(dsCustomers.Customers); dsCustomers.Customers.EndLoadData(); DataGrid1.DataSource = dsCustomers.Customers.DefaultView; Or, create the DataTables, DataColumns, and DataRelations programmatically ปริญญาโท สาขาวิชา เทคโนโลยี 160 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร ITEC5620 - Advance Web Programming:: How to Fill a DataSet from Multiple DataAdapters You can use multiple DataAdapters to fill a DataSet Each DataAdapter fills a separate table in the DataSet daCustomers.Fill (dsCustomerOrders.Customers); daOrders.Fill(dsCustomerOrders.Orders); DataGrid1.DataSource = dsCustomerOrders.Customers; Call the Fill method on each DataAdapter Specify the table to fill in ปริญญาโท สาขาวิชา เทคโนโลยี 161 สารสนเทศ มหาวิทยาลัยเทคโนโลยีมหานคร