1 / 54

Introduction to Web Application

Introduction to Web Application. Introduction to C#. Topics. C# Basics The type system Components. C#.

dlechner
Download Presentation

Introduction to Web Application

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to Web Application Introduction to C#

  2. Topics • C# Basics • The type system • Components

  3. C# C# is a simple, modern, object oriented, and type-safeprogramming language derived from C and C++. It will immediately be familiar to C and C++ programmers. C# aims to combine the high productivity of Visual Basic and the raw power of C++. Anders Hejlsberg Chief Designer of C#, Turbo Pascal, Delphi and Visual J++

  4. Hello World Namespace directive Provided by the Microsoft .NET Framework class library using System; class Hello { static void Main() { Console.WriteLine("Hello world"); } } The main entry point for a program Console.WriteLine is a shorthand for System.Console.WriteLine. public class HelloWorld { public static void main(String[] args) { System.out.println(“Hello world”); } }

  5. Run the application • csc h.cs • h.exe • javac HelloWorld.java • java HelloWorld

  6. C# Program Structure package • Namespaces • Contain types and other namespaces • Type declarations • Classes, structs, interfaces, enums, and delegates • Members • Constants, fields, methods, operators, constructors, destructors • Properties, indexers, events • Organization • No header files, code written “in-line” • No declaration order dependence class

  7. C# Program Structure using System; namespace System.Collections { public class Stack { Entry top; public void Push(object data) { top = new Entry(top, data); } public object Pop() { if (null == top) throw new InvalidOperationException(); object result = top.data; top = top.next; return result; } } }

  8. Overview of Common Type System • CTS supports both value and reference types Type Value Type Reference Type

  9. Declaring and Releasing Reference Variable Coordinate c1; c1 = new Coordinate(); c1.x = 6.12; c1.y = 4.2; • Declaring and assigning reference variables • 6.12 4.2 • Releasing reference variables c1 = null; • 6.12 4.2

  10. Comparing Value Types to Reference Types • Reference types • The variable contains a reference to the data • Data is stored in a separate memory area • Value types • The variable contains the value directly • Examples: char, int string s; s = "Hello"; int i; i = 42; • Hello 42

  11. 123 i "Hello world" s Reference and Value Types 123 j t int i = 123; string s = "Hello world"; int j = i; string t = s;

  12. class T sbyte decimal bool byte char ushort short uint float int ulong double long C# Type System String Array T[ ] Object Enum enum T ValueType struct T

  13. Predefined Types • C# predefined types • Reference object, string • Signed sbyte, short, int, long • Unsigned byte, ushort, uint, ulong • Floating-point float, double, decimal • Character char • Logical bool • Predefined types are simply aliases for system-provided types • For example, int == System.Int32

  14. Question using System; class Test { static void Main() { string s = "Test"; string t = string.Copy(s); Console.WriteLine(s == t); Console.WriteLine((object)s == (object)t); } }

  15. Unifying the Type System • Unifyreference and value types • A single universal basetype • Can hold any value • Unification enables: • Calling virtual functions on any value • Collection classes for any type • No wrapper classes • Replacing OLE Automation Variant type

  16. How to Unify: C# Approach • All value types are derived from the ultimate base type “object”. • Value types automatically become reference types when necessary. • Heap allocation only when needed • Objects remain strongly typed. • Process is known as “boxing”

  17. Boxing and Unboxing • Boxing and Unboxing can make an instance to encapsulate a value-typedvariable, and use it as reference type

  18. Boxing and unboxing using System; class test{ staticvoid Main(){ int i=123; object o = i; //boxing int j = (int) o; //unboxing } }

  19. Boxing using System; class test{ staticvoid Main(){ int i=123; object o = i; //boxing int j = (int) o; //unboxing } } i 123 int i = 123 Boxing i o ref int 123 object o = i

  20. Unboxing i 123 int i = 123 Boxing i o int 123 ref object o = i j 123 int j = (int)o Unboxing o

  21. User-Defined Types • Classes (reference) • Used for most objects • Structs (value) • Objects that are like data (Point, Complex, etc). • Interfaces

  22. CAR? What Is a Class? • For the philosopher… • An artifact of human classification! • Classify based on common behavior or attributes • Agree on descriptions and names of useful classes • Create vocabulary; we communicate; we think! • For the object-oriented programmer… • A named syntactic construct that describes common behavior and attributes • A data structure that includes both data and functions

  23. What Is an Object? • An object is an instance of a class • Objects exhibit: • Identity: Objects are distinguishable from one another • Behavior: Objects can perform tasks • State: Objects store information

  24. Classes • Single inheritance • Multiple interface implementation • Class members • Constants, fields, methods, properties, indexers, events, operators, constructors, destructors • Static and instance members • Nested types • Member access • Public, protected, internal, protect internal, private

  25. Member accessibility • private • Accessible only by methods in the defining type • protected • Accessible only by methods in this type or one of its derived types without regard to assembly • internal • Accessible only by methods in the defining assembly • protectinternal • Accessible only by methods in this type any derived type, or any type defined in the defining assembly • public • Accessible to all methods in all assemblies

  26. Creating Objects • Step 1: Allocating memory • Use new keyword to allocate memory from the heap • Step 2: Initializing the object by using a constructor • Use the name of the class followed by parentheses Date when = new Date( );

  27. Object Cleanup • The final actions of different objects will be different • Those actions cannot be determined by garbage collection • Objects in .NET Framework have a Finalize method • If present, garbage collection will call destructor before reclaiming the raw memory • In C#, implement a destructor to write cleanup code • You cannot call or override Object.Finalizein C#

  28. Structs • Same as classes, but “value” behavior • Allocated inline • Always have a value • Assignment copies data • Inheritance? • Can’t derive from other types • Can’t be derived from • Advantages • Behave like a piece of data • Light weight • No heap allocation, less GC pressure

  29. Class vs Struct class Point{ public int x, y; public Point(int x, int y) { this.x = x; this.y = y; }} struct Point{ public int x, y; public Point(int x, int y) { this.x = x; this.y = y; }} Point a = new Point(10, 10); Point b = a; a.x = 20; Console.WriteLine(b.x);

  30. Interfaces • Can contain methods, properties, indexers, and events interface IDataBound { void Bind(IDataBinder binder); } class EditBox: Control, IDataBound { void Bind(IDataBinder binder) {...} }

  31. Component Development • What defines a component? • Properties, methods, events • Integrated help and documentation • Design-time information • C# has first class support • Components are easy to build and consume • Can be embedded (ASP.net pages)

  32. Properties • Properties are “smart fields” • Natural syntax, accessors, inlining public class Button: Control { private string caption; public string Caption { get { return caption; } set { caption = value; Repaint(); } } } Button b = new Button(); b.Caption = "OK"; String s = b.Caption;

  33. Creating a Simple .NET Framework Component with C# • Using Namespaces and Declaring the Class • Creating the Class Implementation • Implementing Structured Exception Handling • Creating a Property • Compiling the Component

  34. Using Namespaces and Declaring the Class • Create a New Namespace • Declare the Class using System; namespace CompCS {...} public class StringComponent {...}

  35. Creating the Class Implementation private string[] stringSet; • Declare a Private Field of Type Array of String Elements • Create a Public Default Constructor • Assign the stringSet Field to an Array of Strings public StringComponent() {...} stringSet = new string[] { "C# String 0", "C# String 1", ... };

  36. Implementing Structured Exception Handling public string GetString(int index) {...} • Implement the GetString Method • Create and Throw a New Object of Type IndexOutOfRangeException • Exceptions Caught by the Caller Using a try/catch/finally Statement • Structured Exception Handling Replaces HRESULT-Based Error Handling in COM if((index < 0) || (index >= stringSet.Length)) { throw new IndexOutOfRangeException(); } return stringSet[index];

  37. Creating a Property • Create a Read-Only Count Property to Get the Number of String Elements in the stringSet Array public int Count { get { return stringSet.Length; } }

  38. Compiling the Component • Use the /target:library Switch to Create a DLL • Otherwise, an executable with a .dll file extension is created instead of a DLL library csc /out:CompCS.dll /target:library CompCS.cs

  39. Creating a Simple Console Client • Using the Libraries • Instantiating the Component • Calling the Component • Building the Client

  40. Using the Libraries • Reference Types Without Having to Fully Qualify the Type Name • If Multiple Namespaces Contain the Same Type Name, Create a Namespace Alias to Remove Ambiguity using CompCS; using CompVB; using CSStringComp = CompCS.StringComponent; using VBStringComp = CompVB.StringComponent;

  41. Instantiating the Component • Declare a Local Variable of Type StringComponent • Create a New Instance of the StringComponent Class //… using CSStringComp = CompCS.StringComponent; //… CSStringComp myCSStringComp = new CSStringComp();

  42. Calling the Component • Iterate over All the Members of StringComponent and Output the Strings to the Console for (int index = 0; index < myCSStringComp.Count; index++) { Console.WriteLine (myCSStringComp.GetString(index)); }

  43. Building the Client • Use the /reference Switch to Reference the Assemblies That Contain the StringComponent Class csc /reference:CompCS.dll /out:ClientCS.exe ClientCS.cs

  44. Creating an ASP.NET Client • Writing the HTML for the ASP.NET Application • Coding the Page_Load Event Handler • Generating the HTML Response

  45. Writing the HTML for the ASP.NET Application <%@ Page Language="C#" Description="ASP.NET Client" %> • Specify Page-Specific Attributes Within a Page Directive • Import the Namespace and the Physical Assembly • Specify Code Declaration Blocks <%@ Import Namespace="CompCS"%> <script language="C#" runat=server> ... </script>

  46. Coding the Page_Load Event Handler void Page_Load(Object sender, EventArgs EvArgs) { StringBuilder Out = new StringBuilder(""); int Count = 0; // Iterate over component's strings and concatenate Out.Append("Strings from C# Component<br>"); CompCS.StringComponent myCSStringComp = new CompCS.StringComponent(); for(int index = 0; index < myCSStringComp.Count; index++) { Out.Append(myCSStringComp.GetString(index)); Out.Append("<br>"); } // … Message.InnerHtml = Out.ToString(); }

  47. Generating the HTML Response • Specify the Body of the HTML Response <body> <span id="Message" runat=server/> </body>

  48. Demonstration: Testing the ASP.NET Client

  49. System.String • Look up MSDN!

More Related