.NET Fundamentals Advanced Class
|
|
- Adelia Ross
- 5 years ago
- Views:
Transcription
1 .NET Fundamentals Advanced Class Michele Leroux Bustamante Brian Noyes IDesign, Inc. Agenda Operators, Conversion, and Comparison Strings, Immutability and StringBuilder Boxing/Unboxing Exception Handling Interface Based Programming Memory Management Delegates, Events, and Async Code Access Security Reflection Deployment and Versioning www. vsconnections.com 1
2 Operators Operator Overloading Promotes encapsulation Provides more intuitive type usage Assignment Concatenation Math operations Comparison Makes life easier for the user of your type For natural usage patterns www. vsconnections.com 2
3 Type Conversions Encapsulate natural type conversions to simplify type usage patterns Implicit Conversions int n = 10; long l = n; No loss of data results Explicit Conversions Requires a cast () expression long l = 10; int i = (int)l; Data Type Conversions Casting decimal d = ; // compiler error, double value decimal d = (decimal)999.99; // this works long x = 20; long y = 30; int i = (int)(x + y); // can cast result of expressions www. vsconnections.com 3
4 System.Convert Static functions convert to/from.net types No conversion performed if: Converting between same data type Conversion cannot be performed InvalidCastException is thrown double dbl = ; decimal d = Convert.ToDecimal(999.99); string s = Convert.ToString(d); Type Conversions System.IConvertible Supports System.Convert functionality Internally used for explicit interface access System.ComponentModel.TypeConverter Use TypeConverterAttribute to associate it Uses reflection (slow) Design time and runtime usage www. vsconnections.com 4
5 Comparing Items System.IComparable Implemented on types that can be ordered CompareTo() System.IComparer Custom sorting rules (i.e., column selection) Agenda Operators, Conversion, and Comparison Strings, Immutability and StringBuilder Boxing/Unboxing Exception Handling Interface Based Programming Memory Management Delegates, Events, and Async Code Access Security Reflection Deployment and Versioning www. vsconnections.com 5
6 Reference and Value Types int i = 123; string s = Hello world ; int j = i; string t = s; i 123 s "Hello world" j 123 t Immutable Strings string s1 = hello ; string s2 = world ; s1 s2 hello" world" s1 += s2; s1 hello" helloworld" Garbage Collector s2 world" www. vsconnections.com 6
7 System.Text.StringBuilder Pre-allocate string capacity Default is 16 characters Expands as needed (unless max set) Better performance from concatenation Append(), Insert(), Replace() Supports formatting AppendFormat() Agenda Operators, Conversion, and Comparison Strings, Immutability and StringBuilder Boxing/Unboxing Exception Handling Interface Based Programming Memory Management Delegates, Events, and Async Code Access Security Reflection Deployment and Versioning www. vsconnections.com 7
8 Kinds of Types Value Types Stack Allocated Contain data directly Cannot be null Reference Types Heap Allocated Garbage Collected Contain references to objects Can be null Assignment makes shallow copy int i = 5; string s = "Hello"; 5 "Hello" Value Types Primitives int i; Struct struct Pointint X,int Y Enum enum ColorRed,Green,Blue www. vsconnections.com 8
9 Value Types No inheritance (sealed) Assignment copies data, not reference Relatively cheap to use and allocate Reduce GC pressure No default constructor Reference Type Class class MyClass MyClass obj = new MyClass(); String string message = "Hello"; Object object obj = new object(); Array int[] numbers = new int[5]; Delegates delegate void MyDelegate(); www. vsconnections.com 9
10 Reference Type Comparing two reference types only compares the address, not the referenced value MyClass obj1 = new MyClass(); MyClass obj2 = new MyClass(); Debug.Assert(obj1!= obj2); Can implement IComparable or overload == for deep compare Like the string class: string s1 = "My String"; string s2 = "My String"; Debug.Assert(s1 == s2); Reference Type Two reference types can point to the same object public class MyClass public int X; //Client side code: MyClass obj1 = new MyClass(); MyClass obj2; obj1.x = 3; obj2 = obj1; Debug.Assert(obj2.X == 3); obj1.x = 4; Debug.Assert(obj2.X == 4); www. vsconnections.com 10
11 Boxing/Unboxing Boxing Promoting a value type to a reference type Space is heap allocated void SomeMethod(object obj) int i = 5; SomeMethod(i); int j = 6; j.tostring(); Boxing/Unboxing Un-boxing Converting a reference type to a value type Type mismatch triggers exception void SomeMethod(object obj) int i = (int)obj; Can even allocate primitives off the heap Primitive initialized to default value (all zeros) int i = new int(); //same as: //object obj = new int(); //int i = (int)obj; www. vsconnections.com 11
12 So Where The Heck Does My Object Live? Stack Heap Main( ) F1(); F4(); So Where The Heck Does My Object Live? Stack Heap F1( ) int i = 42; F2(i); Main( ) F1(); F4(); www. vsconnections.com 12
13 So Where The Heck Does My Object Live? Main( ) F1(); F4(); Stack F2(int i) MyClass mc = new MyClass(); // Some code F1( ) int i = 42; F2(i); Heap Some String MyClass string s = int j = So Where The Heck Does My Object Live? Stack Heap F1( ) int i = 42; F2(i); Main( ) F1(); F4(); Some String MyClass string s = int j = www. vsconnections.com 13
14 So Where The Heck Does My Object Live? Stack Heap Main( ) F1(); F4(); Some String MyClass string s = int j = So Where The Heck Does My Object Live? Stack Heap F4( ) // Some local variables // Some other code Main( ) F1(); F4(); Some String MyClass string s = int j = www. vsconnections.com 14
15 So Where The Heck Does My Object Live? Stack Heap F1( ) int i = 42; F2(i); Main( ) F1(); F4(); So Where The Heck Does My Object Live? Main( ) F1(); F4(); Stack F2(object i) MyClass mc = new MyClass(); // Some code F1( ) int i = 42; F2(i); Heap Some String MyClass string s = int j = www. vsconnections.com 15
16 So Where The Heck Does My Object Live? Stack Heap F1( ) int i = 42; F2(i); Main( ) F1(); F4(); Some String MyClass string s = int j = Arrays Memory Allocation int[] arr = new int[2]; arr 0 0 arr[0] = 10; arr[1] = 11; arr www. vsconnections.com 16
17 Arrays Memory Allocation string[] arr = new string[2]; arr null null arr[0] = hello ; arr[1] = world ; arr hello world Arrays Memory Allocation object[] arr = new object[2]; arr null null arr[0] = new SomeType(); arr[1] = new OtherType(); arr SomeType OtherType www. vsconnections.com 17
18 Collections and Memory Management What is wrong with this? ArrayList list = new ArrayList(); list.add(42); list.add(38); list.add(13); This: public class ArrayList public virtual int Add(object o)... // other members Not type safe Boxing Partial Solution in.net 1.x Strongly typed collection class public class CustomerCollection : CollectionBase public int Add(Customer c) return List.Add(c); public void Remove(Customer c) List.Remove(c); // other members Solves type safety Problems: Code Bloat many collection class definitions Boxing for value types www. vsconnections.com 18
19 Solution in.net 2.0 Generic Collections Built-in generic collections Collection<T> List<T> BindingList<T> Agenda Operators, Conversion, and Comparison Strings, Immutability and StringBuilder Boxing/Unboxing Exception Handling Interface Based Programming Memory Management Delegates, Events, and Async Code Access Security Reflection Deployment and Versioning www. vsconnections.com 19
20 Error Handling Exception based Rich standard set of exceptions Use as-is or derive and extend C++ / SEH like semantics throw/try/catch/finally Method should return result or object No error code, throw exception if error Exception advantages Cannot be ignored, handle wherever Error Handling Catch and handle every relevant exception Re-throw if you like throw <exception>; throw; Client can catch particular types, base type or all Like C++/Java Exception terminate thread Unless caught and handled www. vsconnections.com 20
21 Error Handling Use try around a code block that might throw exception Use catch block to catch specific exceptions Empty catch catches all exceptions public class MyClass public void MyMethod() bool ok = IsEverythingOK(); if(ok == false) InvalidOperationException exception; exception = new InvalidOperationException("I am not OK"); throw(exception); private bool IsEverythingOK()return false; protected void OnButtonClick(object sender,eventargs e) MyClass obj = new MyClass(); try obj.mymethod(); catch(exception exception)//same as catch string msg = "I had an error because "; msg += exception.message; MessageBox.Show(msg); www. vsconnections.com 21
22 Error Handling Can have multiple catch blocks Each catches its exception tree Compiler warns unreachable catch types MyClass obj = new MyClass(); try obj.mymethod(); catch(dividebyzeroexception exception) string msg = Do not divide by zero!"; MessageBox.Show(msg); catch(stackoverflowexception exception) string msg = Maybe the recursion went bad?"; MessageBox.Show(msg); throw exception; //re-throw Error Handling Re-throwing original exception dose not affect stack trace MyClass obj = new MyClass(); try obj.mymethod(); catch(stackoverflowexception exception) string msg = Maybe the recursion went bad?"; MessageBox.Show(msg); throw; //Same as throw exception www. vsconnections.com 22
23 Error Handling catch called when exception occurred finally block always called, regardless whether exception is thrown or not Do clean up, like closing files Can have finally block with or without catch catch block is called first, then finally try obj.mymethod(); Finally string msg = "This block always gets executed"; MessageBox.Show(msg); public class MyClass public void MyMethod() bool ok = IsEverythingOK(); if(ok == false) InvalidOperationException exception; exception = new InvalidOperationException("I am not OK"); throw(exception); private bool IsEverythingOK()return false; protected void OnButtonClick(object sender,eventargs e) MyClass obj = new MyClass(); try obj.mymethod(); catch(exception exception)//same as catch string msg = "I had an error because "; msg += exception.message; MessageBox.Show(msg); finally string msg = "This block always gets executed"; MessageBox.Show(msg); www. vsconnections.com 23
24 Error Handling Not all failures result in exception Do not use exceptions for expected errors Do not use exceptions for normal control flow Return null, false, EOF, or custom enums and constants whenever possible Avoid custom exceptions If you must, derive from ApplicationException Exception contains message, trace info Custom Exceptions Numerous predefined exceptions ArgumentOutOfRangeException IndexOutOfRangeException StackOverflowException Custom Exceptions Derive from System.ApplicationException Exception suffix naming convention www. vsconnections.com 24
25 Agenda Operators, Conversion, and Comparison Strings, Immutability and StringBuilder Boxing/Unboxing Exception Handling Interface Based Programming Memory Management Delegates, Events, and Async Code Access Security Reflection Deployment and Versioning Interfaces Interface can define methods, events, properties, indexes All are public always Cannot define static and constants Interface has visibility public interface IMyInterface internal interface IMyInterface www. vsconnections.com 25
26 Implementing Interfaces Subclass implementation must be public No need for override/new Must implement all methods in interface derivation chain public interface IMyInterface void Method1(); void Method2(); void Method3(); public class MyClass : IMyInterface public MyClass() public void Method1() public void Method2() public void Method3() Implementing Interfaces Can derive from multiple interfaces public interface IMyInterface1 void Method1(); public interface IMyInterface2 void Method2(); public class MyClass : IMyInterface1,IMyInterface2 public MyClass() public void Method1() public void Method2() www. vsconnections.com 26
27 Implementing Interfaces Can still derive from one concrete class, in addition to interfaces Must be first in derivation chain public interface IMyInterface public interface IMyOtherInterface public class MyBaseClass public class MySubClass : MyBaseClass,IMyInterface,IMyOtherInterface Using Interfaces Declare interface type and instantiate it with a class instance: //Implicit cast IMyInterface obj = new MyClass(); obj.method1(); Client can program directly against the object: MyClass obj = new MyClass(); obj.method1(); www. vsconnections.com 27
28 Using Interfaces Explicitly cast object reference Compiler does not enforce type safety Throws exception if not supported Should use try/catch public interface IMyInterface void Method1(); public class MyClass : IMyInterface IMyInterface obj = (IMyInterface)new MyClass(); obj.method1(); Using Interfaces Explicitly cast with non-generic class factories public interface IMyInterface void Method1(); public interface IClassFactory object GetObject(); public class MyClass : IMyInterface IClassFactory factory; /*some code to initialize the class factory*/ IMyInterface obj; obj = (IMyInterface)factory.GetObject(); obj.method1(); www. vsconnections.com 28
29 Using Interfaces Explicitly cast with multiple interfaces public interface IMyInterface void Method1(); public interface IMyOtherInterface void Method2(); public class MyClass : IMyInterface,IMyOtherInterface //Client side code: IMyInterface obj1; IMyOtherInterface obj2; obj1 = new MyClass(); obj1.method1(); obj2 = (IMyOtherInterface)obj1; obj2.method2(); Using Interfaces Even better: use as SomeType obj1; IMyInterface obj2; /* Some code to initialize obj1 */ obj2 = obj1 as IMyInterface; if(obj2!= null) obj2.method1(); else //Handle error in expected interface www. vsconnections.com 29
30 Interface-Based Programming Separation of interface from implementation is a core componentoriented principle Changing service provider, no affect on client Client programs against an abstraction of the service, not a particular implementation.net does not enforce the separation Unlike COM Disciplined developers should ALWAYS enforce separation Interface-Based Programming Developer has to provide for separation of interface from implementation.net lets you program against the object directly using MyAssembly; //Avoid doing this: MyComponent obj; obj = new MyComponent(); obj.showmessage(); www. vsconnections.com 30
31 Interface-Based Programming Client-side programming: Program against interface, not object Never assume the object support an interface Use try/catch or as SomeType obj1; IMyInterface obj2; /* Some code to initialize obj1 */ obj2 = obj1 as IMyInterface; if(obj2!= null) obj2.method1(); else //Handle error in expected interface Interface-Based Programming Server-side programming: Provide explicit member implementation Explicit implementation cannot be public Or have any visibility modifier at all public interface IMyInterface void Method1(); void Method2(); public class MyClass : IMyInterface public MyClass() void IMyInterface.Method1()//Explicit implementation void IMyInterface.Method2()//Explicit implementation www. vsconnections.com 31
32 Interface-Based Programming Explicit implementation forces client to program against interface, not object IMyInterface obj1 = new MyClass(); obj1.method1(); //This does not compile: MyClass obj2 = new MyClass(); obj2.method1(); Interfaces Method Collision Interfaces can define the same method Implementing class can Channel both to the same implementation public interface IMyInterface1 void MyMethod(); public interface IMyInterface2 void MyMethod(); public class MyClass : IMyInterface1,IMyInterface2 public MyClass() public void MyMethod()//Same implementation for both interfaces www. vsconnections.com 32
33 Interfaces Method Collision Interfaces can define the same method Qualifying interface Clients can only access via interface type public interface IMyInterface1 void MyMethod(); public interface IMyInterface2 void MyMethod(); public class MyClass : IMyInterface1,IMyInterface2 public MyClass() void IMyInterface1.MyMethod() //First interface implementation void IMyInterface2.MyMethod() //Second interface implementation Methods, Properties and Events public interface IMyInterface void Method1(); //A method int SomeProperty get; set; //A property int this[int index] get; set;//an indexer event NumberChangedEvent NumberChanged;//An event public class MyClass : IMyInterface public void Method1() public int SomeProperty get set public int this[int index] get set public event NumberChangedEvent NumberChanged; www. vsconnections.com 33
34 Interfaces and Structs Can provide base interface for structs Should use properties only Benefits of polymorphism, even though structs cannot derive from a common base struct public interface IMyBaseStruct int SomeNumber get; set; string SomeString get; set; struct MyStruct : IMyBaseStruct public int SomeNumber get set public string SomeString get set struct MyOtherStruct : IMyBaseStruct public int SomeNumber get set public string SomeString get set public class MyClass public void DoWork(IMyBaseStruct storage) www. vsconnections.com 34
35 Interfaces and Subclasses Can mix class hierarchy and interfaces public interface ITrace void TraceSelf(); public class A : ITrace public virtual void TraceSelf()Trace.WriteLine("A"); public class B : A public override void TraceSelf()Trace.WriteLine("B"); public class C : B public override void TraceSelf()Trace.WriteLine("C"); ITrace trace = new B(); trace.traceself(); //output: "B" Interface Factoring and Design Is this a good design? www. vsconnections.com 35
36 Interface Factoring and Design Is this a good design? Interface Factoring and Design Is this a good design? www. vsconnections.com 36
37 Interface Factoring and Design Balance number of components with development effort Total system cost Cost Minimum cost Cost to interface Cost / interface Number of interfaces Interface Factoring and Design When factoring interface, think always in terms of reusable elements Example: a dog interface Requirements Bark Fetch Veterinarian clinic registration number A property for having received shots www. vsconnections.com 37
38 Interface Factoring and Design Could define IDog public interface IDog void Fetch(); void Bark(); long VetClinicNumber get; set; bool HasShots get; set; public class Poodle : IDog public class GermanShepherd : IDog This interface is not well factored Interface Factoring and Design Better factoring: public interface IPet long VetClinicNumber get; set; bool HasShots get; set; public interface IDog void Fetch(); void Bark(); public interface ICat void Purr(); void CatchMouse(); public class Poodle : IDog,IPet public class Siamese : ICat,IPet www. vsconnections.com 38
39 Interface Factoring and Design If operations are logically related, but repeated, factor to hierarchy of interfaces public interface IMammal void ShedFur(); void Lactate(); public interface IDog : IMammal void Fetch(); void Bark(); public interface ICat : IMammal void Purr(); void CatchMouse(); Interface Factoring Metrics Interface factoring results in interfaces with fewer members Balance out two counter forces Too many granular interfaces Vs few complex, poorly factored interfaces Just one member is possible, but avoid it Dull facet, too many parameters Optimal number 3 to 5 No more than 20 (12) www. vsconnections.com 39
40 Interface Factoring Metrics Ratio of methods, properties and events Interfaces should have more methods than properties Just-enough-encapsulation Ratio of at least 2:1 Exception is interfaces with properties only Should have no methods Avoid defining events.net Factoring Metrics 300+ interfaces examined On average, 3.75 members per interface Methods to properties ratio of 3.5:1 Less than 3 percent of the members are events On average,.net interfaces are well factored www. vsconnections.com 40
41 Agenda Operators, Conversion, and Comparison Strings, Immutability and StringBuilder Boxing/Unboxing Exception Handling Interface Based Programming Memory Management Delegates, Events, and Async Code Access Security Reflection Deployment and Versioning Memory Management.NET allocates reference types from the managed heap Every new allocates memory Including boxing Objects are not destroyed when exit scope Destroyed when collected.net tags allocations Garbage collection periodically releases unreachable memory Non deterministic Classes can perform specific clean-up when collected www. vsconnections.com 41
42 Memory Management Developers manage other resources.net manages memory occupied by object Object may hold files, connections, ports, handles, events Developer has to be minded about deterministic needs May kill your application Makes sharing objects difficult Memory Allocation Every process has a managed heap New objects are allocated off the heap, and the pointer moves up When the heap is exhausted, GC takes place Multi generation allocation New object part of younger generation Younger generations are more collectable New Object Heap is pre-allocated Obj 4 Allocation is much faster than native Obj 3 allocation Managed Heap Obj 2 Obj 1 www. vsconnections.com 42
43 Garbage Collection Dispose of unreachable objects Object that no one can reach no client has a reference to Nobody can use them OK to kill.net keeps list of roots Top-level objects: static, global, local variable, GC objects JIT compiler maintains the list When GC starts, it deems everything as garbage GC traverses recursively from roots Builds a graph of reachable objects Adds to graph just once (cyclic references) All threads must suspend during GC Garbage Collection Dispose of unreachable objects Treated as empty space Moved to New Object finalized queue Obj 10 if required Garbage Obj 8 Compact the heap Move reachable Obj 8 objects down Obj 4 Patch references Obj 3 Obj 2 Obj 1 Garbage Collection New Object Obj 10 Obj 8 Obj 4 Obj 3 Obj 2 Obj 1 www. vsconnections.com 43
44 Garbage Collector Types Workstation GC Hosted by console or Windows forms applications Can take advantage of MP Server GC Parallel MP capable GC thread per CPU Multiple heaps for scalability Garbage Collection GC is expensive Takes time Suspended threads Extensive use of metadata to cast and trace references Moving objects in memory Patching references GC is no more expensive than a page-fault 1 millisecond Object are never told when they are deemed garbage How can objects do resource cleanup? www. vsconnections.com 44
45 Finalization Object can optionally implement Finalize() method void Finalize() Must have this exact signature When garbage collected, if object has Finalize() method, it is copied from the heap to a special queue GC knows about Finalize() from Metadata GC calls Finalize() GC removes from queue (object is gone) Finalization Finalization postpones releasing resources to undetermined point in the future Usually till next GC Can severely hamper application scalability Use deterministic finalization if an issue All objects referenced by a Finalize()-able object are kept alive Their finalization is postponed, because they are still reachable App shutdown causes GC www. vsconnections.com 45
46 Finalization and Destructor In C#, even if you add a destructor, the compilers converts it to Finalize() In C#, do not use Finalize(), always use destructor public class MyClass public MyClass() ~MyClass() /// code that is actually generated: public class MyClass public MyClass() protected virtual void Finalize() try //Your destructor code goes here finally base.finalize();//everybody has one, from Object www. vsconnections.com 46
47 Deterministic Finalization Unlike COM, there is no way the object knows when is not required by its clients Unless you implement your own reference count Object has to be explicitly told by client when not required Two programming patterns Close/Open Dispose Close/Open Design Pattern Object provides Open() and Close() methods Close() disposes of the resources the object holds Used when the resources can be reacquired Files, connections, ports Open() recreates the object Clients should not use object without calling Open() first Disadvantages Where to implement? (class? every interface?) Couples client to object finalization mechanism Makes sharing objects complicated Couples clients to clients www. vsconnections.com 47
48 Dispose() Design Pattern Object provides Dispose() method Disposes of all the resources the object holds Doing whatever Finalize() would do Call base-class Dispose() Disposing of resources makes object unusable More common than Close() pattern Finalize() should not be used Disadvantages Where to implement? (class? every interface?) Couples client to object finalization mechanism Makes sharing objects complicated Couples clients to clients All your base classes should implement Dispose() IDisposable Object implements System.IDisposable interface With a Dispose() method: public interface IDisposable void Dispose(); public interface IMyInterface void MyMethod(); public class MyClass : IMyInterface,IDisposable public void MyMethod() public void Dispose() //do object cleanup, call base.dispose() if has one www. vsconnections.com 48
49 IDisposable Client uses domain-methods, and then tries to dispose: IMyInterface obj; obj = new MyClass(); obj.mymethod(); //Client wants to expedite whatever needs expediting: IDisposable disposable = obj as IDisposable; if(disposable!= null) disposable.dispose(); Disposing and Error Handling Should use a try/finally blocks to dispose of objects MyClass obj; obj = new MyClass(); try obj.somemethod(); finally IDisposable disp; disp = obj; disp.dispose(); Code gets messy if multiple objects are involved www. vsconnections.com 49
50 Disposing and Error Handling To automate, use the using(x) statement Only in C# for now MyClass obj; obj = new MyClass(); using(obj) obj.somemethod(); Generates the try/finally blocks Type must derive from IDisposable Compiler enforced Cannot use with interfaces Unless derived from IDisposable Dispose() and Finalize() The two are not mutually exclusive Should provide both Client may not call Dispose() Exceptions If Dispose() not called, should do cleanup in Finalize() If Dispose() called should suppress finalization Should channel Dispose() and Finalize() to same method Should handle multiple Dispose() calls Should handle class hierarchies www. vsconnections.com 50
51 public class BaseClass: IDisposable private bool m_disposed = false; protected bool Disposed get lock(this) return m_disposed; //Do not make Dispose() virtual prevent subclass from overriding public void Dispose() lock(this) // Check to see if Dispose() has already been called if(m_disposed == false) Cleanup(); m_disposed = true; // Take yourself off the Finalization queue // to prevent finalization from executing a second time. GC.SuppressFinalize(this); public class BaseClass: IDisposable protected virtual void Cleanup() /*Do cleanup here*/ //Destructor will run only if Dispose() is not called. //Do not provide destructors in types derived from this class. ~BaseClass() Cleanup(); public void DoSomething() if(disposed)//verify in every method throw new ObjectDisposedException("Object is already disposed"); www. vsconnections.com 51
52 public class SubClass1 : BaseClass protected override void Cleanup() /*Do cleanup here*/ //Call base class base.cleanup(); public class SubClass2 : SubClass1 protected override void Cleanup() /*Do cleanup here*/ //Call base class base.cleanup(); Dispose() and Finalize() Handles correctly all permutations of variable type, actual instantiation type, and casting: SubClass1 a = new SubClass2(); a.dispose(); SubClass1 b = new SubClass2(); ((SubClass2)b).Dispose(); IDisposable c = new SubClass2(); c.dispose(); SubClass2 d = new SubClass2(); ((SubClass1)d).Dispose(); SubClass2 e = new SubClass2(); e.dispose(); www. vsconnections.com 52
53 Agenda Operators, Conversion, and Comparison Strings, Immutability and StringBuilder Boxing/Unboxing Exception Handling Interface Based Programming Memory Management Delegates, Events, and Async Code Access Security Reflection Deployment and Versioning Delegates Delegate is a method reference Type-safe C function pointer Function object in C++ Delegate type defines signature No implementation Used for call-back Events Asynchronous execution www. vsconnections.com 53
54 Delegates Compiler creates a sophisticated typespecific class -= and += operators add/remove from list Invocation methods Delegate calls static or instance methods Delegates public delegate void MyDelegate(int num1,int num2); public class MyClass public void SomeMethod1(int num1,int num2) MessageBox.Show("MyClass.SomeMethod1"); public void SomeMethod2(int num1,int num2) MessageBox.Show("MyClass.SomeMethod2"); www. vsconnections.com 54
55 Delegates MyDelegate mydelegate = null; MyClass obj = new MyClass(); mydelegate += new MyDelegate(obj.SomeMethod1); mydelegate += new MyDelegate(obj.SomeMethod2); mydelegate += new MyDelegate(obj.SomeMethod2); mydelegate(1,2); mydelegate -= new MyDelegate(obj.SomeMethod2); mydelegate(3,4); Can pass delegates as method parameters Inner objects do callback Delegate contains reflection info about the callback methods Events Subscribing Client Subscribing Client Publishing Object Method call Event firing Subscribing Client www. vsconnections.com 55
56 Events Standard way of connecting publisher to subscriber Event publisher is called event source Event subscriber is called event sink Events public delegate void MyDelegate(int num); public class MySource public event MyDelegate NumberChangedEvent; public void SomeMethod(int num) NumberChangedEvent(num); public class MySink public void OnNumberChanged(int num) MessageBox.Show("OnNumberChanged. New value is "+num.tostring()); www. vsconnections.com 56
57 Events MySource source = new MySource(); MySink sink = new MySink(); source.numberchangedevent += new MyDelegate(sink.OnNumberChanged); source.somemethod(1); source.numberchangedevent -= new MyDelegate(sink.OnNumberChanged); source.somemethod(2); event is syntactic sugar around delegate Event can only be fired from within the class Client can only += or -= Events can be virtual, abstract, or override Events VS.NET auto-complete subscription Press TAB But not un-subscription VS.NET auto-generates event handling Press another TAB Only on the same class www. vsconnections.com 57
58 Defensive Event Publishing In C#, delegate is null if no targets Must always check public class MySource public event EventHandler MyEvent; public void FireEvent() if(myevent!= null) MyEvent(this,EventArgs.Empty); Defensive Event Publishing Exceptions thrown by subscribers propagate to publisher Usually publisher does not care public class MySource public event EventHandler MyEvent; public void FireEvent() try if(myevent!= null) MyEvent(this,EventArgs.Empty); catch www. vsconnections.com 58
59 Defensive Event Publishing Can iterate manually over delegate's internal invocation list GetInvocationList() method of delegate public virtual Delegate[] GetInvocationList(); Obtain target collection Publish to each target Catch individual exceptions Defensive Event Publishing public class MySource public event EventHandler MyEvent; public void FireEvent() if(myevent == null) return; Delegate[] delegates = MyEvent.GetInvocationList(); foreach(delegate del in delegates) EventHandler sink = (EventHandler)del; try sink(this,eventargs.empty); catch www. vsconnections.com 59
60 Defensive Event Publishing Can abstract to a generic utility EventsHelper public delegate void SomeDelegate(int num,string str); public class MySource public event SomeDelegate SomeEvent; public void FireEvent(int num, string str) EventsHelper.Fire(SomeEvent,num,str); Fire() method Accepts params object[] Defensive Event Publishing public static class EventsHelper public static void Fire(Delegate del,params object[] args) if(del == null) return; Delegate[] delegates = del.getinvocationlist(); foreach(delegate sink in delegates) try sink.dynamicinvoke(args); catch www. vsconnections.com 60
61 Managing Many Events Impractical to have as many member variables as events Allocation, documentation, code management Use EventHandlerList in System.ComponentModel public sealed class EventHandlerList : IDisposable public EventHandlerList(); public Delegate this[object key] get; set; public void AddHandler(object key, Delegate value); public void RemoveHandler(object key, Delegate value); public void Dispose(); Managing Many Events Must combine with event accessors Delegate to AddHandler/RemoveHandler Use a string or dedicated object for a key Can use any delegate type www. vsconnections.com 61
62 public class MyButton EventHandlerList m_eventlist; public MyButton() m_eventlist = new EventHandlerList(); public event EventHandler Click add m_eventlist.addhandler("click",value); remove m_eventlist.removehandler("click",value); protected void FireClick() EventHandler handler = (EventHandler)m_EventList["Click"]; handler(this,eventargs.empty); /* Other methods and events definition */ Asynchronous Calls Required in almost every application Avoid blocking while something can take place in the background In the past, developers hand-crafted asynch solutions Proprietary Re-inventing the wheel Hard to develop and test.net provides standard implementation www. vsconnections.com 62
63 Asynch Programming Requirements Same server code for sync/async case Client decides async/sync Client can have multiple calls in progress Needs to distinguish between calls Mechanism for out/return parameters Some mechanism for error handling Simple to use Hide the threads, etc. Async Programming Models Client issues async call, then: Receive event when method returns Do something, then poll for completion Polling is blocking Do something, then wait for completion Can wait for event for pre-determined amount of time or infinite Client should be able to wait for multiple calls (all/any) www. vsconnections.com 63
64 Delegates Delegate is a method reference Type-safe C function pointer Function object in C++ Delegate defines signature No implementation Used for Callback, events, asynchronous execution Delegate maintains a list of delegates With async calls, only one delegate allowed Delegates By default, when using delegate, caller is blocked till all callbacks called The delegate class can be used to asynchronously invoke methods BeginInvoke() returns immediately to caller Executes on a thread from thread pool Be mindful of concurrency issues Flexible programming model, complying with requirements www. vsconnections.com 64
65 Delegates The class actually generated: //public delegate int BinaryOperation(int num1,int num2); public class BinaryOperation: System.MulticastDelegate public BinaryOperation(Object target,int methodptr)... public virtual int Invoke(int num1,int num2)... public virtual IAsyncResult BeginInvoke(int num1,int num2, AsyncCallback callback, object asyncstate)... public virtual int EndInvoke(IAsyncResult result)... EndInvoke() has any out/ref parameters and return value Delegates The class actually generated: www. vsconnections.com 65
66 BeginInvoke() Takes the original in /in-out parameters Optional parameters: AsyncCallback callback a delegate to receive method completed notification object asyncstate a generic object, to pass state info to the party handling call end Calculator calc = new Calculator(); BinaryOperation oppdel; oppdel = new BinaryOperation(calc.Add); //Better than += oppdel.begininvoke(2,3,null,null); //Done asynchronously IAsyncResult Interface BeginInvoke() returns IAsyncResult public interface IAsyncResult // Properties object AsyncState get; WaitHandle AsyncWaitHandle get; bool CompletedSynchronously get; bool IsCompleted get; Pass it to EndInvoke() Get the async state object (callback model only) Cast to AsyncResult,get original delegate Wait on the handle www. vsconnections.com 66
67 EndInvoke() Takes original out /in-out parameters After BeginInvoke(), do work, then use EndInvoke() to block Pass in the async object identifying which method to wait on Calculator calc = new Calculator(); BinaryOperation oppdel = null; oppdel = new BinaryOperation(calc.Add); IAsyncResult asyncresult = oppdel.begininvoke(2,3,null,null); /*Do some work */ //Sometime later: int result = oppdel.endinvoke(asyncresult); Debug.Assert(result == 5); EndInvoke() Using EndInvoke(), must save IAsyncResult after BeginInvoke() Must call EndInvoke() on the original delegate EndInvoke() can only be called once for each asynchronous operation www. vsconnections.com 67
68 AsyncResult Class BeginInvoke() returns IAsyncResult interface implemented on object of type AsyncResult System.Runtime.Remoting.Messaging AsyncResult used primarily to access the original delegate AsyncDelegate property Can verify EndInvoke() was not called AsyncResult Class public class AsyncResult : IAsyncResult, IMessageSink //IAsyncResult Properties public object AsyncState virtual get; public WaitHandle AsyncWaitHandle virtual get; public bool CompletedSynchronously virtual get; public bool IsCompleted virtual get; //Other properties public bool EndInvokeCalled get; set; public object AsyncDelegate virtual get; //IMessageSink Methods public IMessageSink NextSink virtual get; public virtual IMessageCtrl AsyncProcessMessage(IMessage msg, IMessageSink replysink); public virtual IMessage SyncProcessMessage(IMessage msg); //Other Methods public virtual void SetMessageCtrl(IMessageCtrl mc); public virtual IMessage GetReplyMessage(); www. vsconnections.com 68
69 EndInvoke() and AsyncResult Call EndInvoke() on the original delegate Instead of caching it, use AsyncResult.AsyncDelegate Calculator calc = new Calculator(); BinaryOperation oppdel = null; oppdel = new BinaryOperation(calc.Add); IAsyncResult asyncresult = oppdel.begininvoke(2,3,null,null); /*Do some work */ //Sometime later: AsyncResult ar = (AsyncResult)asyncResult; Debug.Assert(asyncResult.EndInvokeCalled == false); BinaryOperation myoppdel = (BinaryOperation)ar.AsyncDelegate; int result = myoppdel.endinvoke(asyncresult); Debug.Assert(result == 5); Waiting/Polling Instead of blocking on EndInvoke() IAsyncResult.AsyncWaitHandle Calculator calc = new Calculator(); BinaryOperation oppdel = null; oppdel = new BinaryOperation(calc.Add); IAsyncResult asyncresult = oppdel.begininvoke(2,3,null,null); //Sometime later: asyncresult.asyncwaithandle.waitone(); //This may block int result = oppdel.endinvoke(asyncresult); //This will not block Debug.Assert(result == 5); Call EndInvoke(), ret/out params Used to specify timeout, or wait for a collection of async calls (all or any) www. vsconnections.com 69
70 Waiting/Polling Call IAsyncResult.IsCompleted Just polling, no blocking Calculator calc = new Calculator(); BinaryOperation oppdel = null; oppdel = new BinaryOperation(calc.Add); IAsyncResult asyncresult = oppdel.begininvoke(2,3,null,null); //Sometime later: if(asyncresult.iscompleted) int result = oppdel.endinvoke(asyncresult); //This will not block else //do something meanwhile Async Callback Instead of polling, blocking or waiting Preferred model in event-driven application Usually the easiest model with async execution Provide to BeginInvoke() a delegate to your implementation of a callback Delegate must be of type AsyncCallback public delegate void AsyncCallback(IAsyncResult asyncresult); www. vsconnections.com 70
71 Async Callback The framework invokes callback No need to save IAsyncResult Calculator calc = new Calculator(); BinaryOperation oppdel = null; oppdel = new BinaryOperation(calc.Add); AsyncCallback callback; callback = new AsyncCallback(OnAsyncCallBack); oppdel.begininvoke(2,3,callback,null); void OnAsyncCallBack(IAsyncResult asyncresult) AsyncResult ar = (AsyncResult)asyncResult; BinaryOperation oppdel = (BinaryOperation)ar.AsyncDelegate; int result = 0; //Will never block on EndInvoke() result = oppdel.endinvoke(asyncresult); Debug.Assert(result == 5); Async State Object Can pass to BeginInvoke() an object to be used on method completion Optional Useful only when using a callback Otherwise, you call EndInvoke() at leisure But can use anywhere Calculator calc = new Calculator(); BinaryOperation oppdel = null; oppdel = new BinaryOperation(calc.Add); AsyncCallback callback; callback = new AsyncCallback(OnAsyncCallBack); int asyncstate = 4; //int, for example oppdel.begininvoke(2,3,callback,asyncstate); www. vsconnections.com 71
72 Async State Object Un-box on the receiving side: void OnAsyncCallBack(IAsyncResult asyncresult) int asyncstate = 0; asyncstate = (int)asyncresult.asyncstate; Debug.Assert(asyncState == 4); //rest of the processing: AsyncResult ar = (AsyncResult)asyncResult; BinaryOperation oppdel = (BinaryOperation)ar.AsyncDelegate; int result = 0; //Will never block on EndInvoke() result = oppdel.endinvoke(asyncresult); Debug.Assert(result == 5); Error Handling If async method throws exception EndInvoke() throws the exception when called www. vsconnections.com 72
73 Error Handling If there was only in parameters and no returned value, not care about exceptions Use [OneWay] attribute public class MyClass [OneWay] public void SomeMethod(int num1,int num2) MessageBox.Show("MyClass.SomeMethod"); By itself, does not make call asynchronous Asynchronous Events Cannot call BeginInvoke() must have single target (iterate manually) public class MySource public event MyDelegate OnNumberEvent; public void FireAsynch(int number) Delegate[] delegates = OnNumberEvent.GetInvocationList(); foreach(delegate del in delegates) MyDelegate sink = (MyDelegate)del; sink.begininvoke(number,null,null); public void FireSynch(int number) OnNumberEvent(number); www. vsconnections.com 73
74 Asynchronous Events Publishing events fire-and-forget will cause resource leaks Unless subscribers are OneWay methods Publisher cannot assume subscribers are one-way Can automate Asynchronous Events The EventsHelper class public class MySource public event MyDelegate OnNumberEvent; public void FireAsynch(int number) EventsHelper.FireAsync(OnNumberEvent,number); public void FireSynch(int number) OnNumberEvent(number); www. vsconnections.com 74
75 public static class EventsHelper public static void FireAsync(Delegate del,params object[] args) if(del == null) return; Delegate[] delegates = del.getinvocationlist(); AsyncFire asyncfire = new AsyncFire(InvokeDelegate); foreach(delegate sink in delegates) asyncfire.begininvoke(sink,args,null,null); delegate void AsyncFire(Delegate del,object[] args); [OneWay] static void InvokeDelegate(Delegate del,object[] args) del.dynamicinvoke(args); Async. Vs Synch Calls Although technically possible to use the same components synch or asynch, in reality it is unlikely The reasons are changes in workflow semantics www. vsconnections.com 75
76 Async. Vs Synch Calls Example: On-line shoes store Client Shoe Store Order Ship Billing Order Ship Async. Vs Synch Calls If asynch calls used, methods can be now invoked in random order All hell can break lose No item in the store, but we shipped it and billed the client for it You can not just invoke methods asynchronously Client Shoe Store Order Ship Billing www. vsconnections.com 76
77 Async. Vs Synch Calls Must change components code And methods signatures Each component invokes the next method in the work flow Introduces tight coupling between components Client Shoe Store Order Ship Billing Async vs Sync Calls Use asynch calls with care Wait on events, etc. Useful in isolated scenarios Consider spinning worker thread in complex scenarios www. vsconnections.com 77
78 Agenda Operators, Conversion, and Comparison Strings, Immutability and StringBuilder Boxing/Unboxing Exception Handling Interface Based Programming Memory Management Delegates, Events, and Async Code Access Security Reflection Deployment and Versioning What is Missing in Windows Security Windows security is user-oriented OS viewed as one monolithic chunk A user can either do something or not at all No granularity (do one thing, but not the other) Users vulnerable to attacks Downloads viruses Worms Spoofing Luring attacks www. vsconnections.com 78
79 What is Missing in Windows Security Today, applications and OS are componentbased Need a component-oriented security model What a component is allowed to do No all or nothing Component origin Compliments Windows security User-based access control Authentication Authorization.NET Security Intricate administrative permissions schema Programmatic permissions support Role-base security www. vsconnections.com 79
80 Security Permission An individual grant Grants access to a resource Perform operation Examples File I/O permission Read, write append data to a specific file UI Permission Accessing windows, top level windows, clipboard access Reflection Permissions.NET defines 19 permission types Environment variables n Web access File dialog n Performance counter File IO n Directory services Isolated storage n Message queue Reflection n Service controller Registry n OLE DB UI n SQL client Security n Event log DNS n Sockets access Printing www. vsconnections.com 80
81 Permission Sets Individual permission is specific Access only C:\Temp Access all files Can display windows Permission set is grouping of permissions Access read only to all of C:\ and can display windows Standard named permission sets Nothing n Execution n SkipVerification Internet n LocalIntranet Everything n Full Trust Can define custom permission sets Permission Sets Named permission sets www. vsconnections.com 81
82 Security Evidence Permissions granted based on evidence Evidence is some form of proof assembly provides to substantiate identity Origin-based evidences Content-based evidences Origin-based evidence Application Directory, Site, URL, Zone Content-based evidence Strong name, Publisher certificate, Hash Code Groups Binding of a single permission set with a single evidence Code Group Permission Set Evidence Permission A Permission B Permission C www. vsconnections.com 82
83 Security Policy Collection of code groups Permissions granted by a policy is the union of all the individual groups satisfied Not granted Code Group A Code Group D Granted Code Group B Security Policy Code Group C Code Group E Security Policy All policies must concur on allowed permissions Actual permissions granted is intersection of the permissions granted by all policies www. vsconnections.com 83
84 Managing Security Policies Manage permission using.net configuration tool Security Policy.NET defines three policies Enterprise Machine User Each policy defines code groups Each policy defines its own permission sets www. vsconnections.com 84
85 Security Policy Policies nest code groups Child code group not evaluated if parent s evidence is satisfied Can customize policies Demo Default walk-through Code Grouping by Zone Zones are: Internet Intranet My computer No zone Trusted sites IE list of trusted sites Untrusted sites IE list of restricted sites www. vsconnections.com 85
86 How It All Fits Together When assembly loaded Assembly classified to code group in policies Intersecting policy calculated Framework classes have built-in security demands Indicate type of operation requested Indicate security action and time When assembly tries to perform operation Granted access to resource or Security exception How It All Fits Together CLR must verify permission of chain of callers Not good enough if component has permission but not upstream caller Verify using stack walk Resource demand for security permission verification triggers stack walk If even one caller does not have permission -> security exception Administrative security is independent of actual component code www. vsconnections.com 86
87 Agenda Operators, Conversion, and Comparison Strings, Immutability and StringBuilder Boxing/Unboxing Exception Handling Interface Based Programming Memory Management Delegates, Events, and Async Code Access Security Reflection Deployment and Versioning Reflection Programmatic act of: Discovering what is the object type Discovering what is the object made of Methods, properties, base class Most useful with attributes Allows to create new types on the fly Esoteric Allows for late-binding invocation Not type safe System.Reflection www. vsconnections.com 87
88 Type An abstraction of a type Every entity represented as a Type Get the Type on any entity by Type Object.GetType() typeof operator //Client can use Object.GetType() MyClass obj = new MyClass(); Type type1 = obj.gettype(); //or the typeof() operator Type type2 = typeof(myclass); Debug.Assert(type1 == type2); Type Used to obtain metadata of an object GetMember() returns MemberInfo GetMethod() returns MethodInfo Get<entity name> returns. InvokeMember() for dynamic invocation BaseType GetCustomAttributes() Caller must have Reflection permission Type.ToString() returns type name www. vsconnections.com 88
89 Type MyClass obj = new MyClass(); Type type = obj.gettype(); string name = type.tostring(); Debug.Assert(name == "MyClass"); Type Methods Iteration Example: programmatically iterate over public methods of a type And potentially invoke them Call GetMethods() with no filter No constructors (call GetConstructors()) MyClass obj = new MyClass(); Type type = obj.gettype(); MethodInfo[] methodinfos = type.getmethods(); //Trace all the public methods foreach(methodinfo info in methodinfos) Trace.WriteLine(info.Name); www. vsconnections.com 89
90 Attributes Classes declaratively affect entity behavior Classes, interfaces, methods, enums. Most.NET services available using attributes Enterprise Services Interoperability Serialization Security Synchronization Powerful development tool Pre/post call processing Attributes All attribute are directly or indirectly derived from System.Attribute All attribute name should have Attribute suffix Enable referring with short name [Serializable] instead of [SerializableAttribute] Attributes are in [] Can set attribute properties if has any Can use default constructor if provided Can use parameterized constructor www. vsconnections.com 90
91 Attributes Exclude from compilation all method calls When the condition is not defined System.Diagnostics #define MySpecialCondition //usually DEBUG public class MyClass public MyClass() [Conditional("MySpecialCondition")] public void MyMethod() //Client side code MyClass obj = new MyClass(); //This line is conditional obj.mymethod(); Attributes Only works with methods Method must return void, to prevent usage in expressions Conditional attribute has one public property ConditionString Public read only, for reflection www. vsconnections.com 91
92 Custom Attributes Add information to a type metadata For general custom attributes, usually also provide code to use new attribute Usually tool developers Very useful Pre and post call processing Context activation policy Attribute cannot accept class or struct as parameter Besides arrays, Type, Object Example Color Attribute Requirement: applied to classes and interfaces only Design: Derive from System.Attribute Color is available as a property Default and a parameterized constructor public enum ColorOption Red,Green,Blue; [Color(ColorOption.Green)] public class MyClass www. vsconnections.com 92
93 public enum ColorOption Red,Green,Blue; [AttributeUsage(AttributeTargets.Class AttributeTargets.Interface)] public class ColorAttribute : Attribute protected ColorOption m_color; public ColorOption Color get return m_color; set m_color = value; public ColorAttribute() Color = ColorOption.Red; public ColorAttribute(ColorOption color) this.color = color; Example Color Attribute Using reflection to find out color: static ColorOption GetColor(object obj) Type type = obj.gettype(); ColorOption color = ColorOption.Red;//Initialization //Find out the color, on base classes as well object[] attributes = type.getcustomattributes(true); foreach(object attribute in attributes) ColorAttribute colorattribute = attribute as ColorAttribute; if(colorattribute!= null) color = colorattribute.color; break; return color; www. vsconnections.com 93
94 Agenda Operators, Conversion, and Comparison Strings, Immutability and StringBuilder Boxing/Unboxing Exception Handling Interface Based Programming Memory Management Delegates, Events, and Async Code Access Security Reflection Deployment and Versioning Use Strongly Named Assemblies Strict enforcement of assembly versions Manifest dependency binding Friendly assembly references disallowed Additional runtime security checks Assembly verification for integrity Callers require FullTrust Exception: AllowPartiallyTrustedCallersAttribute Global Assembly Cache (GAC) support www. vsconnections.com 94
95 Strong Name Review Strong Name Utility (sn.exe) creates cryptographic key pair Sign assembly using key pair or public key Assembly linker option (al.exe) Compiler leverages.net attributes Public key stored in assembly manifest Private key used to digitally sign assembly Assembly Signing: File sn.exe k mlbkey.snk mlbkey.snk Public Key Private Key assemblyinfo.cs [assembly: AssemblyKeyFile( mlbkey.snk )] csc.exe al.exe Compile Manifest Public Key Digital Signature Assembly Module Types Resources Code www. vsconnections.com 95
96 Think Before You GAC Global Assembly Cache (GAC) Install shared assemblies here Requires strong name Benefits Centralized administration Better performance Side-by-side deployment Secure deployment location Side-By-Side Deployment Gacutil.exe /i assemblyfilename Gacutil.exe /u assemblyname www. vsconnections.com 96
C# Asynchronous Programming Model
Spring 2014 C# Asynchronous Programming Model A PRACTICAL GUIDE BY CHRIS TEDFORD TABLE OF CONTENTS Introduction... 2 Background Information... 2 Basic Example... 3 Specifications and Usage... 4 BeginInvoke()...
More informationObject-Oriented Programming
Object-Oriented Programming 1. What is object-oriented programming (OOP)? OOP is a technique to develop logical modules, such as classes that contain properties, methods, fields, and events. An object
More informationHierarchical inheritance: Contains one base class and multiple derived classes of the same base class.
1. What is C#? C# (pronounced "C sharp") is a simple, modern, object oriented, and type safe programming language. It will immediately be familiar to C and C++ programmers. C# combines the high productivity
More informationC++\CLI. Jim Fawcett CSE687-OnLine Object Oriented Design Summer 2017
C++\CLI Jim Fawcett CSE687-OnLine Object Oriented Design Summer 2017 Comparison of Object Models Standard C++ Object Model All objects share a rich memory model: Static, stack, and heap Rich object life-time
More informationMCSA Universal Windows Platform. A Success Guide to Prepare- Programming in C# edusum.com
70-483 MCSA Universal Windows Platform A Success Guide to Prepare- Programming in C# edusum.com Table of Contents Introduction to 70-483 Exam on Programming in C#... 2 Microsoft 70-483 Certification Details:...
More informationDOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS
Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully
More informationShort Notes of CS201
#includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system
More informationSaikat Banerjee Page 1
1. What s the advantage of using System.Text.StringBuilder over System.String? StringBuilder is more efficient in the cases, where a lot of manipulation is done to the text. Strings are immutable, so each
More informationCS201 - Introduction to Programming Glossary By
CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with
More informationAsynchronous Programming Model (APM) 1 Calling Asynchronous Methods Using IAsyncResult 4 Blocking Application Execution by Ending an Async Operation
Asynchronous Programming Model (APM) 1 Calling Asynchronous Methods Using IAsyncResult 4 Blocking Application Execution by Ending an Async Operation 5 Blocking Application Execution Using an AsyncWaitHandle
More informationCourse Hours
Programming the.net Framework 4.0/4.5 with C# 5.0 Course 70240 40 Hours Microsoft's.NET Framework presents developers with unprecedented opportunities. From 'geoscalable' web applications to desktop and
More informationC# 6.0 in a nutshell / Joseph Albahari & Ben Albahari. 6th ed. Beijin [etc.], cop Spis treści
C# 6.0 in a nutshell / Joseph Albahari & Ben Albahari. 6th ed. Beijin [etc.], cop. 2016 Spis treści Preface xi 1. Introducing C# and the.net Framework 1 Object Orientation 1 Type Safety 2 Memory Management
More informationAsynchronous Functions in C#
Asynchronous Functions in C# Asynchronous operations are methods and other function members that may have most of their execution take place after they return. In.NET the recommended pattern for asynchronous
More informationWeiss Chapter 1 terminology (parenthesized numbers are page numbers)
Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement
More informationCPS 506 Comparative Programming Languages. Programming Language
CPS 506 Comparative Programming Languages Object-Oriented Oriented Programming Language Paradigm Introduction Topics Object-Oriented Programming Design Issues for Object-Oriented Oriented Languages Support
More informationSri Lanka Institute of Information Technology System Programming and Design II Year 3 Tutorial 06
Sri Lanka Institute of Information Technology System Programming and Design II Year 3 Tutorial 06 1. What is an asynchronous call? How does it differ from a synchronous call? In synchronous call, the caller
More informationReview sheet for Final Exam (List of objectives for this course)
Review sheet for Final Exam (List of objectives for this course) Please be sure to see other review sheets for this semester Please be sure to review tests from this semester Week 1 Introduction Chapter
More informationQUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file?
QUIZ on Ch.5 Why is it sometimes not a good idea to place the private part of the interface in a header file? Example projects where we don t want the implementation visible to the client programmer: The
More informationC# Programming in the.net Framework
50150B - Version: 2.1 04 May 2018 C# Programming in the.net Framework C# Programming in the.net Framework 50150B - Version: 2.1 6 days Course Description: This six-day instructor-led course provides students
More informationIntroduction to Programming Using Java (98-388)
Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;
More informationCS 3 Introduction to Software Engineering. 3: Exceptions
CS 3 Introduction to Software Engineering 3: Exceptions Questions? 2 Objectives Last Time: Procedural Abstraction This Time: Procedural Abstraction II Focus on Exceptions. Starting Next Time: Data Abstraction
More informationItem 18: Implement the Standard Dispose Pattern
Item 18: Implement the Standard Dispose Pattern 1 Item 18: Implement the Standard Dispose Pattern We ve discussed the importance of disposing of objects that hold unmanaged resources. Now it s time to
More informationIntroduction to Programming Microsoft.NET Applications with Visual Studio 2008 (C#)
Introduction to Programming Microsoft.NET Applications with Visual Studio 2008 (C#) Course Number: 6367A Course Length: 3 Days Course Overview This three-day course will enable students to start designing
More informationMicrosoft.NET Programming (C#, ASP.NET,ADO.NET, VB.NET, Crystal Report, Sql Server) Goal: Make the learner proficient in the usage of MS Technologies
Microsoft.NET Programming (C#, ASP.NET,ADO.NET, VB.NET, Crystal Report, Sql Server) Goal: Make the learner proficient in the usage of MS Technologies for web applications development using ASP.NET, XML,
More informationObject Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.
CMSC 131: Chapter 28 Final Review: What you learned this semester The Big Picture Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach. Java
More informationIntroduce C# as Object Oriented programming language. Explain, tokens,
Module 2 98 Assignment 1 Introduce C# as Object Oriented programming language. Explain, tokens, lexicals and control flow constructs. 99 The C# Family Tree C Platform Independence C++ Object Orientation
More informationImplementing Subprograms
Implementing Subprograms 1 Topics The General Semantics of Calls and Returns Implementing Simple Subprograms Implementing Subprograms with Stack-Dynamic Local Variables Nested Subprograms Blocks Implementing
More informationCS 231 Data Structures and Algorithms, Fall 2016
CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard
More informationIndex COPYRIGHTED MATERIAL
Index COPYRIGHTED MATERIAL Note to the Reader: Throughout this index boldfaced page numbers indicate primary discussions of a topic. Italicized page numbers indicate illustrations. A abstract classes
More informationG Programming Languages - Fall 2012
G22.2110-003 Programming Languages - Fall 2012 Lecture 2 Thomas Wies New York University Review Last week Programming Languages Overview Syntax and Semantics Grammars and Regular Expressions High-level
More informationCGS 2405 Advanced Programming with C++ Course Justification
Course Justification This course is the second C++ computer programming course in the Computer Science Associate in Arts degree program. This course is required for an Associate in Arts Computer Science
More informationCS 160: Interactive Programming
CS 160: Interactive Programming Professor John Canny 3/8/2006 1 Outline Callbacks and Delegates Multi-threaded programming Model-view controller 3/8/2006 2 Callbacks Your code Myclass data method1 method2
More informationDAD Lab. 2 Additional C# Topics
DAD 2017-2018 Lab. 2 Additional C# Topics Summary 1. Properties 2. Exceptions 3. Delegates and events 4. Generics 5. Threads and synchronization 1. Properties Get/Set Properties Simple way to control the
More informationAbsolute C++ Walter Savitch
Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents
More informationSERIOUS ABOUT SOFTWARE. Qt Core features. Timo Strömmer, May 26,
SERIOUS ABOUT SOFTWARE Qt Core features Timo Strömmer, May 26, 2010 1 Contents C++ refresher Core features Object model Signals & slots Event loop Shared data Strings Containers Private implementation
More informationCS558 Programming Languages
CS558 Programming Languages Winter 2017 Lecture 4a Andrew Tolmach Portland State University 1994-2017 Semantics and Erroneous Programs Important part of language specification is distinguishing valid from
More informationCOPYRIGHTED MATERIAL. Contents. Part I: C# Fundamentals 1. Chapter 1: The.NET Framework 3. Chapter 2: Getting Started with Visual Studio
Introduction XXV Part I: C# Fundamentals 1 Chapter 1: The.NET Framework 3 What s the.net Framework? 3 Common Language Runtime 3.NET Framework Class Library 4 Assemblies and the Microsoft Intermediate Language
More informationMemory management has always involved tradeoffs between numerous optimization possibilities: Schemes to manage problem fall into roughly two camps
Garbage Collection Garbage collection makes memory management easier for programmers by automatically reclaiming unused memory. The garbage collector in the CLR makes tradeoffs to assure reasonable performance
More informationJava: introduction to object-oriented features
Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer
More informationC#: framework overview and in-the-small features
Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer C#: framework overview and in-the-small features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer
More informationClass, Variable, Constructor, Object, Method Questions
Class, Variable, Constructor, Object, Method Questions http://www.wideskills.com/java-interview-questions/java-classes-andobjects-interview-questions https://www.careerride.com/java-objects-classes-methods.aspx
More informationInside the Garbage Collector
Inside the Garbage Collector Agenda Applications and Resources The Managed Heap Mark and Compact Generations Non-Memory Resources Finalization Hindering the GC Helping the GC 2 Applications and Resources
More informationContents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix
PGJC4_JSE8_OCA.book Page ix Monday, June 20, 2016 2:31 PM Contents Figures Tables Examples Foreword Preface xix xxi xxiii xxvii xxix 1 Basics of Java Programming 1 1.1 Introduction 2 1.2 Classes 2 Declaring
More informationMicrosoft. Microsoft Visual C# Step by Step. John Sharp
Microsoft Microsoft Visual C#- 2010 Step by Step John Sharp Table of Contents Acknowledgments Introduction xvii xix Part I Introducing Microsoft Visual C# and Microsoft Visual Studio 2010 1 Welcome to
More informationRun-Time Environments/Garbage Collection
Run-Time Environments/Garbage Collection Department of Computer Science, Faculty of ICT January 5, 2014 Introduction Compilers need to be aware of the run-time environment in which their compiled programs
More informationC#.Net. Course Contents. Course contents VT BizTalk. No exam, but laborations
, 1 C#.Net VT 2009 Course Contents C# 6 hp approx. BizTalk 1,5 hp approx. No exam, but laborations Course contents Architecture Visual Studio Syntax Classes Forms Class Libraries Inheritance Other C# essentials
More informationMemory Usage. Chapter 23
C23621721.fm Page 280 Wednesday, January 12, 2005 10:52 PM Chapter 23 Memory Usage The garbage collector is one of the most sophisticated pieces of the Microsoft.NET Framework architecture. Each time an
More informationCore Java - SCJP. Q2Technologies, Rajajinagar. Course content
Core Java - SCJP Course content NOTE: For exam objectives refer to the SCJP 1.6 objectives. 1. Declarations and Access Control Java Refresher Identifiers & JavaBeans Legal Identifiers. Sun's Java Code
More informationCS558 Programming Languages
CS558 Programming Languages Fall 2016 Lecture 3a Andrew Tolmach Portland State University 1994-2016 Formal Semantics Goal: rigorous and unambiguous definition in terms of a wellunderstood formalism (e.g.
More informationCMSC 132: Object-Oriented Programming II
CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation
More informationChapter 4 Defining Classes I
Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the
More informationExpert C++/CLI:.NET for Visual C++ Programmers
Expert C++/CLI:.NET for Visual C++ Programmers Marcus Heege Contents About the Author About the Technical Reviewer Acknowledgments xiii xv xvii CHAPTER 1 Why C++/CLI? 1 Extending C++ with.net Features
More informationCMSC 132: Object-Oriented Programming II
CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation
More information02 Features of C#, Part 1. Jerry Nixon Microsoft Developer Evangelist Daren May President & Co-founder, Crank211
02 Features of C#, Part 1 Jerry Nixon Microsoft Developer Evangelist Daren May President & Co-founder, Crank211 Module Overview Constructing Complex Types Object Interfaces and Inheritance Generics Constructing
More informationConcepts of Programming Languages
Concepts of Programming Languages Lecture 10 - Object-Oriented Programming Patrick Donnelly Montana State University Spring 2014 Patrick Donnelly (Montana State University) Concepts of Programming Languages
More informationStructure of Programming Languages Lecture 10
Structure of Programming Languages Lecture 10 CS 6636 4536 Spring 2017 CS 6636 4536 Lecture 10: Classes... 1/23 Spring 2017 1 / 23 Outline 1 1. Types Type Coercion and Conversion Type Classes, Generics,
More informationPace University. Fundamental Concepts of CS121 1
Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction
More informationCMSC 330: Organization of Programming Languages
CMSC 330: Organization of Programming Languages Memory Management and Garbage Collection CMSC 330 - Spring 2013 1 Memory Attributes! Memory to store data in programming languages has the following lifecycle
More informationPES INSTITUTE OF TECHNOLOGY
Seventh Semester B.E. IA Test-I, 2014 USN 1 P E I S PES INSTITUTE OF TECHNOLOGY C# solution set for T1 Answer any 5 of the Following Questions 1) What is.net? With a neat diagram explain the important
More informationWhidbey Enhancements to C# Jeff Vaughan MSBuild Team July 21, 2004
Whidbey Enhancements to C# Jeff Vaughan MSBuild Team July 21, 2004 Outline Practical Partial types Static classes Extern and the namespace alias qualifier Cool (and practical too) Generics Nullable Types
More informationMicrosoft Visual C# Step by Step. John Sharp
Microsoft Visual C# 2013 Step by Step John Sharp Introduction xix PART I INTRODUCING MICROSOFT VISUAL C# AND MICROSOFT VISUAL STUDIO 2013 Chapter 1 Welcome to C# 3 Beginning programming with the Visual
More informationQUIZ Friends class Y;
QUIZ Friends class Y; Is a forward declaration neeed here? QUIZ Friends QUIZ Friends - CONCLUSION Forward (a.k.a. incomplete) declarations are needed only when we declare member functions as friends. They
More information3A01:.Net Framework Security
3A01:.Net Framework Security Wolfgang Werner HP Decus Bonn 2003 2003 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice Agenda Introduction to
More information20 Most Important Java Programming Interview Questions. Powered by
20 Most Important Java Programming Interview Questions Powered by 1. What's the difference between an interface and an abstract class? An abstract class is a class that is only partially implemented by
More information[Course Overview] After completing this module you are ready to: Develop Desktop applications, Networking & Multi-threaded programs in java.
[Course Overview] The Core Java technologies and application programming interfaces (APIs) are the foundation of the Java Platform, Standard Edition (Java SE). They are used in all classes of Java programming,
More informationCS 221 Review. Mason Vail
CS 221 Review Mason Vail Inheritance (1) Every class - except the Object class - directly inherits from one parent class. Object is the only class with no parent. If a class does not declare a parent using
More informationFramework Fundamentals
Questions Framework Fundamentals 1. Which of the following are value types? (Choose all that apply.) A. Decimal B. String C. System.Drawing.Point D. Integer 2. Which is the correct declaration for a nullable
More informationCompositional C++ Page 1 of 17
Compositional C++ Page 1 of 17 Compositional C++ is a small set of extensions to C++ for parallel programming. OVERVIEW OF C++ With a few exceptions, C++ is a pure extension of ANSI C. Its features: Strong
More informationVALLIAMMAI ENGINEERING COLLEGE
VALLIAMMAI ENGINEERING COLLEGE SRM Nagar, Kattankulathur 603 203 DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING QUESTION BANK B.E. - Electrical and Electronics Engineering IV SEMESTER CS6456 - OBJECT ORIENTED
More informationObject-Oriented Programming in C# (VS 2015)
Object-Oriented Programming in C# (VS 2015) This thorough and comprehensive 5-day course is a practical introduction to programming in C#, utilizing the services provided by.net. This course emphasizes
More informationCOP 3330 Final Exam Review
COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time
More informationLecture 23: Object Lifetime and Garbage Collection
The University of North Carolina at Chapel Hill Spring 2002 Lecture 23: Object Lifetime and Garbage Collection March 18 1 Fundamental Concepts in OOP Encapsulation Data Abstraction Information hiding The
More informationC++ for System Developers with Design Pattern
C++ for System Developers with Design Pattern Introduction: This course introduces the C++ language for use on real time and embedded applications. The first part of the course focuses on the language
More information15CS45 : OBJECT ORIENTED CONCEPTS
15CS45 : OBJECT ORIENTED CONCEPTS QUESTION BANK: What do you know about Java? What are the supported platforms by Java Programming Language? List any five features of Java? Why is Java Architectural Neutral?
More informationCpt S 122 Data Structures. Course Review Midterm Exam # 2
Cpt S 122 Data Structures Course Review Midterm Exam # 2 Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Midterm Exam 2 When: Monday (11/05) 12:10 pm -1pm
More informationCS 241 Honors Memory
CS 241 Honors Memory Ben Kurtovic Atul Sandur Bhuvan Venkatesh Brian Zhou Kevin Hong University of Illinois Urbana Champaign February 20, 2018 CS 241 Course Staff (UIUC) Memory February 20, 2018 1 / 35
More informationProfessional ASP.NET Web Services : Asynchronous Programming
Professional ASP.NET Web Services : Asynchronous Programming To wait or not to wait; that is the question! Whether or not to implement asynchronous processing is one of the fundamental issues that a developer
More informationCS558 Programming Languages
CS558 Programming Languages Fall 2017 Lecture 3a Andrew Tolmach Portland State University 1994-2017 Binding, Scope, Storage Part of being a high-level language is letting the programmer name things: variables
More informationAn Introduction to C++
An Introduction to C++ Introduction to C++ C++ classes C++ class details To create a complex type in C In the.h file Define structs to store data Declare function prototypes The.h file serves as the interface
More informationProgramming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur
Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture - 43 Dynamic Binding (Polymorphism): Part III Welcome to Module
More informationInterview Questions of C++
Interview Questions of C++ Q-1 What is the full form of OOPS? Ans: Object Oriented Programming System. Q-2 What is a class? Ans: Class is a blue print which reflects the entities attributes and actions.
More informationObject-Oriented Programming in C# (VS 2012)
Object-Oriented Programming in C# (VS 2012) This thorough and comprehensive course is a practical introduction to programming in C#, utilizing the services provided by.net. This course emphasizes the C#
More informationThreads are lightweight processes responsible for multitasking within a single application.
Threads Threads are lightweight processes responsible for multitasking within a single application. The class Thread represents an object-oriented wrapper around a given path of execution. The class Thread
More informationChapter 5 Object-Oriented Programming
Chapter 5 Object-Oriented Programming Develop code that implements tight encapsulation, loose coupling, and high cohesion Develop code that demonstrates the use of polymorphism Develop code that declares
More informationPage 1
Java 1. Core java a. Core Java Programming Introduction of Java Introduction to Java; features of Java Comparison with C and C++ Download and install JDK/JRE (Environment variables set up) The JDK Directory
More information#using <System.dll> #using <System.Windows.Forms.dll> using namespace System; using namespace System::Windows::Forms;
Lecture #13 Introduction Exception Handling The C++ language provides built-in support for handling anomalous situations, known as exceptions, which may occur during the execution of your program. Exceptions
More informationProgramming in Visual Basic with Microsoft Visual Studio 2010
Programming in Visual Basic with Microsoft Visual Studio 2010 Course 10550; 5 Days, Instructor-led Course Description This course teaches you Visual Basic language syntax, program structure, and implementation
More informationAP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS
AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this
More informationSynchronization SPL/2010 SPL/20 1
Synchronization 1 Overview synchronization mechanisms in modern RTEs concurrency issues places where synchronization is needed structural ways (design patterns) for exclusive access 2 Overview synchronization
More informationMultiple choice questions. Answer on Scantron Form. 4 points each (100 points) Which is NOT a reasonable conclusion to this sentence:
Multiple choice questions Answer on Scantron Form 4 points each (100 points) 1. Which is NOT a reasonable conclusion to this sentence: Multiple constructors for a class... A. are distinguished by the number
More informationTypes. Type checking. Why Do We Need Type Systems? Types and Operations. What is a type? Consensus
Types Type checking What is a type? The notion varies from language to language Consensus A set of values A set of operations on those values Classes are one instantiation of the modern notion of type
More informationThe issues. Programming in C++ Common storage modes. Static storage in C++ Session 8 Memory Management
Session 8 Memory Management The issues Dr Christos Kloukinas City, UoL http://staff.city.ac.uk/c.kloukinas/cpp (slides originally produced by Dr Ross Paterson) Programs manipulate data, which must be stored
More informationCompiler construction 2009
Compiler construction 2009 Lecture 6 Some project extensions. Pointers and heap allocation. Object-oriented languages. Module systems. Memory structure Javalette restrictions Only local variables and parameters
More informationChapter 6 Introduction to Defining Classes
Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of
More informationChapter 1 GETTING STARTED. SYS-ED/ Computer Education Techniques, Inc.
Chapter 1 GETTING STARTED SYS-ED/ Computer Education Techniques, Inc. Objectives You will learn: Java platform. Applets and applications. Java programming language: facilities and foundation. Memory management
More informationCOMP322 - Introduction to C++ Lecture 10 - Overloading Operators and Exceptions
COMP322 - Introduction to C++ Lecture 10 - Overloading Operators and Exceptions Dan Pomerantz School of Computer Science 19 March 2012 Overloading operators in classes It is useful sometimes to define
More informationPOLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE
Abstract Base Classes POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors class B { // base class virtual void m( ) =0; // pure virtual function class D1 : public
More informationPROGRAMMING IN VISUAL BASIC WITH MICROSOFT VISUAL STUDIO Course: 10550A; Duration: 5 Days; Instructor-led
CENTER OF KNOWLEDGE, PATH TO SUCCESS Website: PROGRAMMING IN VISUAL BASIC WITH MICROSOFT VISUAL STUDIO 2010 Course: 10550A; Duration: 5 Days; Instructor-led WHAT YOU WILL LEARN This course teaches you
More informationCompaq Interview Questions And Answers
Part A: Q1. What are the difference between java and C++? Java adopts byte code whereas C++ does not C++ supports destructor whereas java does not support. Multiple inheritance possible in C++ but not
More informationPOLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors
POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors CSC 330 OO Software Design 1 Abstract Base Classes class B { // base class virtual void m( ) =0; // pure virtual
More information