Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Web Application

Similar presentations


Presentation on theme: "Introduction to Web Application"— 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-safe programming 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++. type-safe 代码是与内存地址隔离的代码。type-safe 代码只访问被授权可以访问的内存地址。 Type-safe code accesses only the memory locations it is authorized to access. (For this discussion, type safety specifically refers to memory type safety and should not be confused with type safety in a broader respect.) For example, type-safe code cannot read values from another object's private fields. It accesses types only in well-defined, allowable ways. During just-in-time (JIT) compilation, an optional verification process examines the metadata and Microsoft intermediate language (MSIL) of a method to be JIT-compiled into native machine code to verify that they are type safe. This process is skipped if the code has permission to bypass verification. For more information about verification, see Compiling MSIL to Native Code. Although verification of type safety is not mandatory to run managed code, type safety plays a crucial role in assembly isolation and security enforcement. When code is type safe, the common language runtime can completely isolate assemblies from each other. This isolation helps ensure that assemblies cannot adversely affect each other and it increases application reliability. Type-safe components can execute safely in the same process even if they are trusted at different levels. When code is not type safe, unwanted side effects can occur. For example, the runtime cannot prevent unsafe code from calling into native (unmanaged) code and performing malicious operations. When code is type safe, the runtime's security enforcement mechanism ensures that it does not access native code unless it has permission to do so. All code that is not type safe must have been granted SecurityPermission with the passed enum member SkipVerification to run. Anders Hejlsberg Chief Designer of C#, Turbo Pascal, Delphi and Visual J++

4 Hello World using System; class Hello { static void Main() {
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 Namespaces Type declarations Members Organization
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
Declaring and assigning reference variables Coordinate c1; c1 = new Coordinate(); c1.x = 6.12; c1.y = 4.2; 6.12 4.2 Releasing reference variables c1 = null; 6.12 4.2

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

11 Reference and Value Types
(Class) Value (Struct) Variable Holds Reference Actual Value Allocated Heap Inline Default value Null Zeroed = means Copy Reference Copy Value 123 i int i = 123; string s = "Hello world"; s "Hello world" t int j = i; 123 j string t = s;

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

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

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

16 Unifying the Type System
Unify reference and value types A single universal base type 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 OLE: Object Link and Embed

17 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”

18 Boxing and Unboxing Boxing and Unboxing can make an instance to encapsulate a value-typed variable, and use it as reference type

19 Boxing and unboxing using System; class test{ static void Main(){
int i=123; object o = i; //boxing int j = (int) o; //unboxing }

20 Boxing i o using System; class test{ static void 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

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

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

23 What Is a Class? For the philosopher…
CAR? 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

24 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

25 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

26 Member accessibility private protected internal protect internal
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 protect internal 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

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

28 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.Finalize in C#

29 Structs Same as classes, but “value” behavior Inheritance? Advantages
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

30 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; Point a = new Point(10, 10); Point b = a; a.x = 20; Console.WriteLine(b.x);

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

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

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

34 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

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

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

37 Implementing Structured Exception Handling
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 public string GetString(int index) {...} if((index < 0) || (index >= stringSet.Length)) { throw new IndexOutOfRangeException(); } return stringSet[index];

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

39 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

40 Creating a Simple Console Client
Using the Libraries Instantiating the Component Calling the Component Building the Client

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

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

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

44 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

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

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

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

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

49 Demonstration: Testing the ASP.NET Client

50 System.String Look up MSDN!

51 C# Interoperability COM Native DLLs Runtime marshalling
Using existing COM objects Exposing .NET objects as COM objects Native DLLs Using platform invoke Runtime marshalling Controlled through attributes

52 Common Language Runtime
Execution Model C# VC ... Script Native Code Install time Code Gen IL Common Language Runtime “Econo”-JIT Compiler Standard JIT Compiler Native Code

53 Native CPU Instructions
Managed EXE Console static void Main() { Console.WriteLine(“Hello”); Console.WriteLine(“Goodbye”); } static void WriteLine() JITCompiler static void WriteLine(String) JITCompiler NativeMethod Native CPU Instructions (remaining members) MSCorEE.dll JITCompiler function { In the assembly that implements the type (Console), look up the method (WriteLine) being called in the metadata. 2. From the metadata, get the IL for this method and verify it. 3. Allocate a block of memory. 4. Compile the IL into native CPU instructions; the native code is saved in the memory allocated in step #3. 5. Modify the method’s entry in the Type’s table so that it now points to the memory block allocated in step #3. 6. Jump to the native code contained inside the memory block. }

54 Summary C# overview Common Type System Component


Download ppt "Introduction to Web Application"

Similar presentations


Ads by Google