Introduction To .

NET
Learning .NET issues with C# implementation

‫הנושאים שנלמד‬
‫‪ ‬שפת #‪C‬‬ ‫‪ ‬כתיבת אפליקציות בעזרת ‪Windows Forms‬‬ ‫‪ ‬כתיבת אפליקציות בעזרת ‪Web Applications‬‬ ‫‪))ASP.NET‬‬ ‫‪ ‬עבודה עם ‪Web Services‬‬ ‫‪ ‬עבודה מול ‪SQL -ADO.NET‬‬

‫הנושאים שנלמד - המשך‬
‫‪ ‬שפת ‪UML‬‬

‫ולסיום - פרויקט‬

‫כללים‬
‫‪ ‬השעור מתחיל בזמן, עם כל מספר של תלמידים‬ ‫‪ ‬הפסקה – 51 דקות בלבד. נא לא ללכת לסופר.‬ ‫‪ ‬עבודה תנתן כל שבוע ביום ד. הגשה ביום ב.‬ ‫‪ ‬חומר לקריאה באנגלית, ינתן מידי יום ב'.‬ ‫‪ ‬חובה לבצע את כל התרגילים.‬ ‫‪ ‬יותר תרגול בבית – יותר הספק.‬

First Program
File: helloWorld.cs class HelloWorld { public static void Main)) { System.Console.WriteLine)"Hello, World"); } } > csc helloWorld.cs

?.NET ‫מה זה‬ ‫או‬ ‫מה מייחד את הסביבה מסביבות קודמות‬
:‫ הרכיבים הבסיסיים‬
CLR )C ommonL anguageR)untime  GC )G arbageC)ollector  :‫ ספריות לטיפול במירב הנושאים‬ GUI, Web, Collections, Threads, Communication ,Database, XML, Reflection

‫השפות שמהוות בסיס לשפת #‪C‬‬
‫‪Java – logic ‬‬ ‫‪C++ - syntax ‬‬ ‫‪Events model - VB ‬‬ ‫‪ ‬ממילא – הבדלים רבים בין #‪ C‬לשתי השפות‬ ‫הנ"ל.‬

‫ספריות הקיימות ב ++‪C‬‬
‫‪ ‬קלט/פלט ל ‪.Console‬‬ ‫‪ ‬כלל הספריות של ‪) C‬מחרוזות, מתמטיקה וכדו)‬ ‫‪STL ‬‬
‫‪string ‬‬ ‫‪Collections ‬‬ ‫‪Algorithms ‬‬

NET. ‫ספריות ב‬
GUI  Threading  Communication  Collections  Database  XML  Web Applications  ... 

CLR Flow

GC

Media file
 Run

Time Model – Mod02  GC - Simplified – Mod09

Basic Program Template
using NamespaceName; namespace MyNamespace { class MyClass {
public static void Main)) {

} } }

IL DASM

Resources
 

http://www.corner.co.il – http://www.developers.org.il –

‫ספר בעברית‬ ‫אתר המפתחים‬ ‫הישראליים‬ http://samples/gotdotnet.com/quickstart/ http://blogs.wdevs.com/Gootvilig

 

‫יעדי פיתוח‬
‫‪ ‬חלונות‬ ‫‪WEB ‬‬ ‫‪ ‬מחשבי כף יד‬ ‫‪ ‬טלפונים ניידים‬ ‫‪... ‬‬

‫הדגמות‬
CUIFirst Program ‫ תוכנית‬ GUIHelloGUI.cs ‫ תוכנית‬ WEB ‫ תוכנית‬

HelloGUI.cs
using System.Windows.Forms; using System.Drawing; class MyForm:Form { public static void Main)) { Application.Run)new MyForm))); } protected override void OnPaint)PaintEventArgs e) { e.Graphics.DrawString)"Hello World!", new Font)"Arial", 35), Brushes.Blue, 10, 100); } }

‫השוואה ל ++‪C‬‬
‫‪ ‬אין מצביעים‬ ‫‪ ‬אין קובצי .‪h‬‬ ‫‪ ‬אוביקטים מוקצים רק על ה ‪heap‬‬ ‫‪ ‬כל האוביקטים יורשים מ ‪object‬‬ ‫‪ ‬אין ירושה מרובה – יש ירושת ממשקים.‬ ‫‪ ‬אין משתנים או פונקציות גלובליים.‬ ‫‪ ‬נוספה המילה ‪.null‬‬

‫ - המשך‬C++ ‫השוואה ל‬ Properties
class Person { private string _Name; public string Name { get {return _Name;} set {_Name = value;} } } Person p = new Person)); p.Name = “‫;”שמואליק‬

‫ - המשך‬C++ ‫השוואה ל‬ Attributes
[STAThread] static void Main) ) { Application.Run)new Form1) )); }

‫השוואה ל ++‪ - C‬המשך‬ ‫עבודה חלונאית‬
‫‪ ‬עורך ‪Designer‬‬ ‫‪ ‬קישור ל ‪event‬‬ ‫‪ ‬הדגמה‬

‫‪Demo‬‬
‫‪ ‬דוגמאות בסיסיות עם ‪IO‬‬

WelcomeCSS.cs
// Namespace Declaration using System; // Program start class class WelcomeCSS { // Main begins program execution. public static void Main() { // Write to console Console.WriteLine("Welcome to the C#!"); } }

InteractiveWelcome.cs
using System; // Program start class class InteractiveWelcome { // Main begins program execution. public static void Main() { // Write to console/get input Console.Write("What is your name?: "); Console.Write("Hello, {0}! ", Console.ReadLine()); Console.WriteLine("Welcome to the C# Station Tutorial!"); } }

Types
‫ סוגי הטיפוסים‬ Value Types versus Reference Type 

‫סוגי הטיפוסים‬

The Size and Range of C# Integral Types
Type sbyte byte short ushort int uint long ulong char Size (in bits) 8 8 16 16 32 32 64 64 16 Range -128 to 127 0 to 255 -32768 to 32767 0 to 65535 -2147483648 to 2147483647 0 to 4294967295 -9223372036854775808 to 9223372036854775807 0 to 18446744073709551615 0 to 65535

The Floating Point and Decimal Types with Size, Precision, and Range
Type float double decimal Size (in bits) 32 64 128 Precision 7 digits 15-16 digits 28-29 decimal places Range 1.5 x 10-45 to 3.4 x 1038 5.0 x 10-324 to 1.7 x 10308 1.0 x 10-28 to 7.9 x 1028

Boxing and Unboxing

.Boxing and Unboxing Cont
Allows the implementation of generic container types class Queue {...
public void Enqueue)object x) {...} public object Dequeue)) {...} {

This Queue can then be used for reference types and value types Queue q = new Queue)); q.Enqueue)new Rectangle))); q.Enqueue)3); Rectangle r = )Rectangle) q.Dequeue)); int x = )int) q.Dequeue));

:‫ טיפוסים מובנים נוספים‬
String  Array 

Int32Int32.cs.htm‫ מימוש‬ )Lutz Reflector( ‫ ממשק המערך‬

Class System.String

public static void Loops)) { Int32 index; // while loop index = 10; while)index != 0){ Console.WriteLine)index); index--; } // for loop for)index = 0;index<100;index++){ Console.Write)index); Console.Write)"\t"); }

// do-while loop index = 0; do{ Console.WriteLine)"Happens at least once"); } while)index < 0); // foreach loop Int32[] myArray = new Int32[]{10, 20, 30, 40}; foreach)Int32 i in myArray) { Console.WriteLine)i); } }

‫לולאות‬

foreach statement – more examples

More about foreach
static void Main)string[] args) { int [] intArray = new int[] {1,2,3}; foreach)int i in intArray) Console.Write)"{0} ",i); Queue q = new Queue)); foreach)int i in intArray) q.Enqueue)i); foreach)int i in q) Console.Write)"{0} ",i); Console.ReadLine)); }
private static void Main)string[] args) { int[] numArray1 = new int[] { 1, 2, 3 }; int[] numArray2 = numArray1; for )int num4 = 0; num4 < numArray2.Length; num4++) { int num1 = numArray2[num4]; Console.Write)"{0} ", num1); } Queue queue1 = new Queue)); int[] numArray3 = numArray1; for )int num5 = 0; num5 < numArray3.Length; num5++) { int num2 = numArray3[num5]; queue1.Enqueue)num2); } foreach )int num3 in queue1) { Console.Write)"{0} ", num3); } Console.ReadLine)); }

Original

From Reflector

String & Array
using System; class ForEachLoop { public static void Main)) { string[] names = {"Cheryl", "Joe", "Matt", "Robert"}; foreach )string personin names) { Console.WriteLine)"{0};) ", person

{ { {

Homework - To do List

Todo
  

Insert Date )auto) Destination Date Description

 

Insert 3-5 items Print formatted:
  

Description Pray Buy a car Come to learn

Date 22/2 24/2 13/2

Destination 22/2 06:30 01/6 08:00 20/2 19:15

With the homework !

switch statement

‫תרגיל מחשבון‬
‫‪ ‬יש לקבל משורת הפקודה ביטוי חשבוני בפורמט:‬ ‫‪ .number [+-*/] number‬לדוגמא: 18 – 71‬ ‫‪ ‬להדפיס את תוצאת התרגיל.‬ ‫‪ ‬במידה ומספר הארגומנטים שונה מ 3 או שלא נתקבלה פקודה‬ ‫חשבונית מתאימה )+-*/) יש להדפיס הודעה מתאימה‬ ‫‪ ‬למתקדמים:‬
‫שימוש ב ‪))double.TryParese‬‬ ‫התמודדות עם קלט ברצף )ללא רווחים) תוך שימוש ב ‪))string.Split‬‬
‫‪‬‬ ‫‪‬‬

One-dimensional Arrays
int [] a = new int[3]; int [] b = new int[] {3, 4, 5}; int [] c = {3, 4, 5}; // Array of references SomeClass[] d = new SomeClass[10]; // Array of values )directly in the array) SomeStruct[] e = new SomeStruct[10]; int len = a.Length; // number of elements in a

Multidimensional Arrays
Regular int[][] a = new int[2][];

a[0] = new int[3]; a[1] = new int[4]; int x = a[0][1]; int len = a.Length;// 2 len = a[0].Length;// 3

.Multidimensional Arrays –Cont

Rectangular )more compact, more efficient access)

int[,] a = new int[2, 3]; int x = a[0, 1]; int len = a.Length; // 6 len = a.GetLength)0); // 2 len = a.GetLength)1); // 3

Enumeration
Declaration )directly in a namespace) enum Colors {red, blue, green} // values: 0, 1, 2 enum Access {personal=1, group=2, all=4} enum Access : byte{personal=1, group=2, all=4} Use Colors c = Colors.blue; // must be qualified Access a = Access.personal | Access.group; if ))Access.personal & a( != 0( Console.WriteLine)"access granted"(;

.Enums – cont

Strongly typed
 No

implicit conversions to/from int  Operators: +, -, ++, --, &, |, ^, ~

Can specify underlying type
 Byte,

short, int, long

enum Color: byte { Red = 1, Green = 2, Blue = 4, Black = 0, White = Red | Green | Blue, }

using System; public class Fib{ Decimal current; Decimal last; public Fib)){ current = 1; last = 0; } private Fib)Decimal last, Decimal secondToLast){ current = last+secondToLast; this.last = last; } public Fib GetNext)){ return new Fib)current, last); } public Decimal Value{ get{return current;} } } csc /Target:library FibObj.cs

Dll and Exe using System; class App { public static void Main)) { Int32 index = 50; Fib obj = new Fib)); do{ Console.WriteLine)obj.Value); obj = obj.GetNext)); }while)index-- != 0); } } csc /r:FibObj.dll FibTest.cs

Class – Dtor
~MyClass) ) { // do work here } the C# compiler translates it to: protected override void Finalize) ) {
try { // do work here. } finally { base.Finalize) ); }

} Demonstrate GC with Flash (Media file)

Dtor vs.IDisposable
public interface IDisposable { void Dispose)); }

IDisposable - skeleton
class Testing : IDisposable {
public void Dispose) ){} // Called by user ~Testing) ){} // Called by GC protected virtual void Dispose)bool disposing){}

}

IDisposable
class Testing : IDisposable {
bool is_disposed = false; protected virtual void Dispose)bool disposing) {
if )!is_disposed) // only dispose once! {
if )disposing) { Console.WriteLine)"Not in destructor, OK to reference other objects"); }

// perform cleanup for this object Console.WriteLine)"Disposing..."); } this.is_disposed = true;

}

//Continue…

.IDisposable – Con
public void Dispose) ) {
Dispose(true); // tell the GC not to finalize GC.SuppressFinalize(this);

} ~Testing) ) {
Dispose(false); Console.WriteLine)"In destructor.");

}

}

Using IDisposable
using System.Drawing; class Tester {
public static void Main) ) {
using )Font font = new Font)"Arial", 10.0f)) { // use font } // compiler will call Dispose on font Font anotherFont = new Font)"Courier",12.0f); using )anotherFont) { // use anotherFont } // compiler calls Dispose on anotherFont

}

}

Inheritance
virtual  override  new  interface
 

DEMO

Improve the DrawingObject

Add
 Color  Rectangle

)Think how to implement in Line) percent);

Add
 Resize)int

Draw object after changes take place.

readonly
public string readonly Name = “Yossi”; Or  public string readonly Name; public Person)) { Name = “Shlomi”; }

const
class MyClass { public string ErrorMessage = “Error”; public void DoNothing)) { const int c = 770; Console.WriteLine)“Loacl constant = {0}”,c); }

Exceptions
static void Main)string[] args) { try { File.OpenRead)"NonExistentFile"); } catch)Exception ex) { Console.WriteLine)ex.ToString))); } }

System.IO.File.OpenRead)( Exceptions
       

SecurityException ArgumentException ArgumentNullException PathTooLongException DirectoryNotFoundException UnauthorizedAccessException FileNotFoundException NotSupportedException

catch order
catch)FileNotFoundException fnfex) { Console.WriteLine)fnfex.ToString))); } catch)Exception ex) { Console.WriteLine)ex.ToString))); }

try – catch - finally
FileStream outStream = null; FileStream inStream = null; try { outStream = File.OpenWrite)"DestinationFile.txt"); inStream = File.OpenRead)"BogusInputFile.txt"); } catch)Exception ex) { Console.WriteLine)ex.ToString))); } finally { if )outStream != null) { outStream.Close)); } if )inStream != null) { inStream.Close)); } }

Communication between object
interface  delegate  event

interface

Interface ISon { void Feed)Food food); } class Father { ISon [] sons = new sons [5]; void DoWork)) { Food food = new Food)5); foreach)ISon son in sons) son.Feed)food.One); }

}

delegate & event
Demonstration in SSW 2 – p21 )ILDasm – what the complier added.)

Delegates

on

Lig

htC ha

ng

e

on

h itc Sw

C

ge an h

Click Switch

Homework
Add enum of priority to the ToDoList  Get as a string from the user, parse be Enum.Parse)).  Use try-catch to avoid exceptions  Advanced – print sorted by priority. )you can try to use System.Collections. Not must.)

Object Interface
) )Equals ) )GetHashCode ))ReferenceEquals ) )Finalize ) )GetType ) )ToString .Evaluates whether two objects are equivalent Allows objects to provide their own hash function for use in collections Evaluates whether two objects refer to the same .instance Cleans up non memory resources; implemented by a destructor Provides access to the type object .Provides a string representation of the object

MemberwiseClone)) Creates a shallow copy of the current Object.

Inheriting from Object
using System; public class SomeClass {
public SomeClass)int val) { value = val; } public override string ToString) ) { return value.ToString) ); } private int value;

}

Homework
 

 

Add ToString)) to the ToDo object Print the ToDo task with ToString)) )implicitly and explicitly) Add Equals & operator== to the ToDo object 2 ToDo are equals if the Description and Destination are the same. Add Demonstration to the equals behavior.

Overloaded Operators
SSW1 – 63/4  DEMO : ObjectInterface

String
DEMO

Indexers
public class ListBox: Control { private string[] items; public string this[int index] { get { return items[index]; } set { items[index] = value; Repaint(); } } }
More – SSW 1 - 61

System.String Indexer
public char this[int index] { get { return this.InternalGetChar)index); } }

Example
class ToDoList { ToDo [] items = new ToDo [5];
public ToDo this[int index] { get { if)index < 0 || index > 4) throw new ArgumentOutOfRangeException)); return this. Items[index]; } set { if)index < 0 || index > 4) throw new ArgumentOutOfRangeException)); this. Items[index] = value ; } }}

Array
IList  ICloneable  IEnumerable  ICollection

ICloneable
public interface ICloneable { object Clone)); }

IEnumerable
public interface IEnumerable { IEnumerator GetEnumerator)); } public interface IEnumerator { bool MoveNext)); object Current { get; } void Reset)); }

ICollection
public interface ICollection : IEnumerable { // Methods void CopyTo)Array array, int index); // Properties int Count { get; } bool IsSynchronized { get; } object SyncRoot { get; } }

IList
public interface IList : ICollection, IEnumerable { // Methods int Add)object value); void Clear)); bool Contains)object value); int IndexOf)object value); void Insert)int index, object value); void Remove)object value); void RemoveAt)int index); // Properties bool IsFixedSize { get; } bool IsReadOnly { get; } object this[int index] { get; set; } }

Collections

Lists
 Array  ArrayList  StringCollection  Queue  Stack  BitArray  CollectionBase  ReadOnlyCollectionBase

IDictionary
public interface IDictionary : ICollection, IEnumerable { // Methods void Add)object key, object value); void Clear)); bool Contains)object key); IDictionaryEnumerator GetEnumerator)); void Remove)object key); // Properties bool IsFixedSize { get; } bool IsReadOnly { get; } object this[object key] { get; set; } ICollection Keys { get; } ICollection Values { get; } }

Dictionaries
 SortedList  Hashtable  ListDictionary  HybridDictionary  StringDictionary  DetionaryBase

Sort Arrays

Array.Sort Sorts the elements in an entire one-dimensional Array using the IComparable interface implemented by each element of the Array Array.BinarySearch Searches a one-dimensional sorted Array for a value, using a binary search algorithm.

IComparable Interface
CompareTo Compares the current instance with another object of the same type.  Classes already implement IComparable

 String  Enum  Primitive

types

public class Temperature : IComparable { public int CompareTo)object obj) { if)obj is Temperature) { Temperature temp = )Temperature) obj; return m_value.CompareTo)temp.m_value); } throw new ArgumentException)"object is not a Temperature"); } // The value holder protected int m_value; public int Value { get {return m_value;} set {m_value = value;} } public int Celsius {get{return )m_value-32)/2; } set {m_value = value*2+32;}} }

DEMO
Arrays

Streams

Streams
 FileStream  MemoryStream  BufferedStream  NullStream  NetworkStream  CryptoStream

Reader & Writers

Binary
 BinaryReader

& BinaryWriters

Text
 TextReader

& TextWriters & StreamWriters

Stream
 StreamReader

String
 StringReader

& StringWriters

FileStream.Open
  

public static FileStream Open)string)
Opens a FileStream on the specified path.

public static FileStream Open)string, FileMode);
Opens a FileStream on the specified path with read/write access

public static FileStream Open)string, FileMode, FileAccess); public static FileStream Open)string, FileMode, FileAccess, FileShare);
Opens a FileStream on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option.

Opens a FileStream on the specified path, with the specified mode and access.

FileStream Enumerations

FileAccess
 FileAccess.Write:

New data can be written to

the file  FileAccess.Read: Existing data can be read from the file  FileAccess.ReadWrite: Existing data can be read from the file and new data be written to the file

FileShare
     

FileShare FileShare.Inheritable: Allows other file handles to inherit from this file FileShare.None: The file cannot be shared FileShare.Read: The file can be opened and read from FileShare.Write: The file can be opened and written to FileShare.ReadWrite: The file can be opened to write to it or read from it

FileMode

FileMode

 

FileMode.Append: If the file already exists, the new data will be added to its end. If the file doesn't exist, it will be created and the new data will be added to it FileMode.Create: If the file already exists, it will be deleted and a new file with the same name will be created. If the file doesn't exist, then it will be created FileMode.CreateNew: If the new already exists, the compiler will throw an error. If the file doesn't exist, it will be created FileMode.Open: If the file exists, it will be opened. If the file doesn't exist, an error would be thrown FileMode.OpenOrCreate: If the file already exists, it will be opened. If the file doesn't exist, it will be created FileMode.Truncate: If the file already exists, its contents will be deleted completely but the file will be kept, allowing you to write new data to it. If the file doesn't exist, an error would be thrown

More File Abilities
Directory  Path

FileSystemWatcher
   

Path Filter NotifyFilter Events
 Created  Changed  Deleted  Renamed

Sign up to vote on this title
UsefulNot useful