.NET Notes
C# Programming
Version 0.01 8/9/2003 by Samar
- Lexicology (Cmd-Line;
C# OOP;
Data Structures; Preprocessor;
History; Variables; Classes)
- GDI+
- Threading
- Visual Studio
-
About: Smallest reference set with no programs.
Conventions:
1.
Lexical Syntax
-------------- compiler csc -----------------
|C# src code |---------------->| MSIL exe or dll |
-------------- ------------------
execn + |
type verifn |
------------------
| JIT Compiler |
------------------
compiled to |
|
CLR -----------------------
final o/p <--------------| Managed Native Code |
-----------------------
- assemblies: self-describg (containg metadata in a manfiest describg contents + dependencies) .net unit
of deploymt, versng + security, incl. 1/+ modules + resrcs; mk usg csc or al
Assembly Contents
- Manifest: metadata describg assembly + types = Name, Version, Culture, Strong name, Assembly
contents, Type info, References, Gen.Info; usu. AssemblyInfo.cs
- Modules: /target:module; .netmodule (deflt extensn)
cannot be used directly by clr.
- Resources
- assembly manifest = link between assembly data types + clr
- metadata of assembly: clr relies on metadata to load assembly + requd libs, vers support, type validatn.
etc;
settg via cmd-line:
al /out:f.exe /target:exe /main:f.Main
/title:My Title
/company: My Company
/product: My Product
- single-file assembly: 1 file = 1 module + metadata (deflt for csc):
> csc /target:exe /out:Application.exe MyApplication.cs MySupportClass.cs
- multi-file assembly: 1/+ modules (maybe in different langs) + manifest;
> al /out:f.exe /target:exe /main:f1.Main f1.netmodule f2.netmodule
(manifest file, format exe, entry point is f1 class' Main(), mods tobe included in assembly.
- Data Types
- Value Type: data alloc on stack, scope var; eg. int, bool, char, struct, enum:
1 step: int i;
- int i = 0x32EF;
- char c = 'w'; char c = '\u01fe'; (4-dig hexa unicode)
- Ref. Type: data in 2 mem locs: obj in heap, pointer on stack; eg classes,
interface, array, delegate:
2 steps: Form MyForm = new Form();
- aObject = bObject --> both a + b point to same instance of Object +
return same vals for properties
- ext libs: Sol Explorer > r(References) > Add Ref > .net | com | local
- Structures:
public struct xstruct
{ public int i; }
- nested types:
public class oClass { private class bClass {...} }
- class vs struct:
classes: ref types (instance data on heap), structs value types instance data on stack, fast
for small data).
- constants : public const double pi = 3.14;
- enums: public enum xenum {
x = 1;
y; // is zero
z; // is one
}
int = deflt data type for enum;
public enum xenum : byte { ... } ;
deflt values: 0,1,...
- arrays:
int[] i = new int[5]; i = new int[7];
int [,] i = { {1,2}, {3,4} };
- jagged array = array of arrays:
string[][] s = new string[3][];
- type conversn
- implicitly / auto, no data loss:
long l = i;
- explicitly / cast:
short s = (short) i;
false casting:
int i = 100000;
short s; s = (short)i; -> i = -31072; since max val breached
- built-in fu's forall datatypes:
Equals() | GetHashCode() | GetType() | ToString()
- Parse() : string -> any value data type,
int i = Parse(xstring);
String Handling
- Insert
- PadLeft | PadRight
- Remove | Replace | Substring
- Split (break nto aray of substrings)
- ToCharArray
- ToLower, ToUpper
- Trim, TrimEnd, TrimStart (rem trailg + leadg, trailg, leadg blanks)
- Compare
- Concat, Join
- Format
- BCL (base class lib) auto included in every prog
Garbage Collection
garb.coll = auto mem mgt scheme
- priority increased when mem low -> free mem
- Dispose() - explicitly free resrc
a.
Cmd Line
x.
Security
System.Security.Principal
- WindowsBuiltInRole -
local Windows grps :
AccountOperator, Administrator, BackupOperator, Guest, PowerUser, PrintOperator,
Replicator, SystemOperator, User
- WindowsPrincipal -
WindowsPrincipal.IsInRole -
if current principal belongs to a specified Windows user group.
System.Security.Permissions
-
PrincipalPermission: Allows checks against the active principal
4.
Debugging (Trace + Debug; try-catch-finally)
3 Types of Common Errors
- syntax errors
- run-time
- logical
Steppg through code optns in vs
- Step Into
- Step Over: step over calls to other fu's
- Step Out: exec remainder of code in currt fu + stop at next line in fu
that called it.
- Run To Cursor: exec code up to line
- Set Next Statement: skip intermediate lines
- breakpts: exec halts + app enters Break mode.
- System.ApplicationException: sukperclass of custom exceptns
- .InnerException: wrap exceptn in new exceptn
x.
WinForms
System.Windows.Forms
Form Lifetime Events:
- Load: 1st x Form.Show() / Form.ShowDialog() called
- Activated: fired if form gets focus, ie. if Form.Show() | ShowDialog() | Activate()
Deactivate: fired if focus lost, ie.if Form.Hide() | Close()
- VisibleChanged: if Visible prop changd
- Closing: if form in process of closg but notyet closed
- Closed: after form closed
System.Web.UI > ControlCollection Class
FormStartPosition = Manual | CenterScreen | WindowsDefaultLocation | WindowsDefaultBounds |
CenterParent (use Location, center, deflt, deflt loc + deflt boundg size + centered on parent form)
MyForm.BackColor = System.Drawing.Color.Red;
MyForm.BackColor | ForeColor
MyForm.Font
MyForn.Text
MyForm.Cursor
.BackGroundImage
Opacity = 1 (deflt, fully opaque)
TabIndex
- PictureBox cannot recv focus -> no TabIndex prop
Anchor
Dock
System.Windows.Forms.Form: superclass of forms
Form.Show() - disply + recv focus, sets MyForm.Visible = true
ShowDialog() - show only after user complets actn,
Activate() - focus to visible form + move to front
Hide() - set MyForm.Visible = false
Close() - rem from memy
- cause form to remain open:
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
e.Cancel = true
}
prevent KeyPress evt handler exec:
private void MyForm_KeyPress(object sender, KeyPressEventArgs e) {
e.Hanlded = true;
}
aControl.Focus(); (give focus)
- Beep() exists in vb.net not cs
- ErrorProvider:
1. oControl.CausesValidation = true;
2. f_validating { ... oErrorProvider.SetError( oTextBox, "no blanks"); }
myCheckBox.AccessibleName = "Preview";
myCheckBox.AccessibleDescription =
"A toggle button used to show the document preview.";
+ When the mouse enters the control to be dropped, the DragEnter
event is fired.
+ When the mouse hovers over the control to be dropped, the DragOver
event is fired.
+ When the mouse leaves the control to be dropped, the DragLeave
event is fired.
+ When the mouse drops over the control to be dropped, the DragDrop
event is fired.ListBox1_DragEnter
Controls
Container Ctrls:
- Panel: scrollable cont no captn
Panel.AutoScroll = true; (enable scroolbars in panel)
- GroupBox
- TabControl
TabControl.TabPages
- GroupBox
- GroupBox.Enabled = false
- Controls Collectn: all ctrls contained by container ctrl:
Control oControl = oForm.Controls[3];
oForm.Controls.Add(oLabel);
oForm.Controls.Remove(oLabel);
oForm.Controls.RemoveAt(3);
oControl.TabPages[1].Controls.Add(oButton);
- Button.Click
- Button: deflt evt: Click
- Checkbox.CheckChanged: deflt evt
.Click
.DoubleClick
MouseEnter
MouseMove
MouseHover
MouseDown
MouseWheel
MouseUp
MouseLeave
MouseEventArgs - Button,
Clicks (no. clicks)
Delta (no notches wheel rotated, +/-, 1 notch=120)
- ToolTipProvider
string s_tooltip = oToolTipProvider.GetToolTip(oButton);
oToolTipProvider.SetToolTip(oButton, "hi");
Menus:
MainMenu
ShowShortcut = true | false
oMenuItem.Checked = true;
oMenuItem.Visible = false;
oContextMenu.MenuItems.Add( oMenuItem.CloneMenu() );
oMenuItem.MergeMenu( oContextMenu );
TextBox.MexLength | PasswordChar | ReadOnly | MultiLine
Keybd events:
KeyDown | KeyPress | KeyUp
KeyEventArgs
KeyUp, KeyDown if Alt, Ctrl, Shift
fires KeyEventArgs,
KeyEventArgs.Alt | Ctrl | Shift = true ( Alt key pressed)
KeyEventArgs.KeyCode - gives Key val of key,
e.KeyCode.ToString();
KeyPress (if key has ascii val), KeyPressEventArgs raised,
KeyPressEventArgs.KeyChar gives ascii val
Char.IsDigit(eKeyPressEventArgs.KeyChar) == true
| IsLetter | IsLetterOrDigit | IsPunctuation | IsLower | IsUpper
if(oTextBox.CanFocus == true)
oTextBox.Focus();
Order of Focus Evts
- Enter
- GotFocus
- Leave
- Validating - raised iff oControl.CausesValidation = true (deflt)
- Validated
- LostFocus
Java vs c#
j2se:
java.net - System.Net
collections - System.Collections
jaxp (java api for xml processg) - System.Xml
rmi - remoting
jdbc - ado.net
jndi - System.DirectoryServices
awt/swing - Winforms
java2d - gdi+
javabeans - -
corba - -
j2ee:
ejb - -
javamail - System.Web.Mail
jca (java connector arch.) - ms Host Integratn Server
jms (java message service) - MSMQ (Ms Msg Queuing)
jsp - asp.net
jta (java transaction api) - MTS (Ms. Transactn Server)
servlets - jsp
Syntax
KEYWORDS (Jones 2003, p.41f)
c# - java
using = import
namespace = package
Types + Constant Keywords: Simple Types
Integer Types
-------------
cs : type : java : desc
bool : System.Boolean: boolean : true | false
char : System.Char : char : (16b unicode char)
sbyte : System.SByte : byte : (8b signed int -128-127)
byte : System.Byte : - : (8b unsigned int 0-255)
short : System.Int16 : short : (16b signed int -32768-32767)
ushort : System.UInt16 : - : (16b unsigned int 0-65535)
int : System.Int32 : int : (32b signed int -2x109-2x109
uint : System.UInt32 : - : (32b unsigned int 0 - 4x109)
long : System.Int64 : long : (64b signed int)
ulong : System.UInt64 : - : (64-bit unsigned int 0 - 1.8x1019 | 264-1)
string : System.String :
object : System.Object : supertype of all types
true | false | null | void : true | false | null | void
(true,false,null are not java keywords but literals)
Floating Point Types
--------------------
float : System.Single : float : (32b double precisn floatg pt)
double : System.Double : double : (64b double precisn floatg pt, approx. 10-324 - 10308)
decimal : System.Decimal: - : (128-bit hi-prec dec with 28 significt digits for financial calcs)
Complex Type
------------
class : class
const : const
delegate: - (ref type defing method signature)
enum : - (set of named constts)
event : - (event member)
this : - (indexer member in class/struct)
interface: interface
object : - (alias for System.Object, java Object class not keyword)
operator: -
string : - (alias for System.String for Unicode String vals, java String not keyword)
struct : - (complex type)
- : extends (c#: class : superclass {...} )
- : implements (c#: class : interface {...})
params : - (id a param array)
out : - (var not require init tobe passed to fu, java out i/o)
ref : - (id var by reference not by value)
as : - (cast but return null if cast fails, no exceptn)
is : instanceof (is obj an instance of type)
new : new (mk instance of type)
typeof : - (return instance of System.Type for spec type)
base : super (ref.superclass members)
this : this (self-ref)
explicit: - (declare explicit type conversn operator)
implicit: - (declare implicit type conversn operator)
Access Modifier Keywords
public : public (var:public | class: instantiated byany obj, deflt for class/struct)
private : private (var: onlyfor members of class | instant by objs of own type or ext nested classes)
protected: protected (class + subclasses; c# protected different from java)
internal: - (all members of assembly | instant only be mems of assembly)
protected internal: - (union of prot + int, assembly or subclasses)
Inheritance Keywords
abstract: abstract (incomplete implementn of prog elemt)
sealed : final (cannot be derived from)
new : - (hides inherited member, deflt, != new for obj instantiatn)
override: - (overrides inherited virtual member with same sig, only virtual
mems canbe overridden)
virtual : - (canbe overridden in subclass, deflt for java)
Other Modifier Keywords
readonly: final (field assignable only once)
extern : native (implementn external to c# code, usu dll)
static : static (static elemt existg in context of type not of class/struct instance)
- : strictfp
lock : synchronized (synchronized access to block not full fu unlike synch)
- : transient (c# NonSerialized comparable)
volatile: volatile (synchronized + ordered field access)
Flow Control Keywords
- : assert (c#: Trace + Debug)
if : if
else : else
switch : switch
case : case
default : default
for : for (determinant loop)
do : do (postloop conditnal)
while : while (preloop conditnal)
foreach : -
in : - (part of foreach)
goto : goto (unused reserved keywords java, cs: unconditnal branchg)
continue: continue (start new loop iteratn)
break : break
return : return
Exception Handling Keywords
try : try
catch : catch
finally : finally
throw : throw (throw/rethrow exceptn)
- : throws
checked : - (arithmetic overflow checkg on, oper + stmt)
unchecked: - (arithmetic overflow checkg off)
Unmanaged Code Keywords
fixed : - (allow pointer to ref managed var -> garbace collector not deallocate var in use)
sizeof : - (siz ein bytes of memory occupd by avlue type instance)
stackalloc: - (alloc mem blocks on stack for storage of local vars)
unsafe : - (unsafe members)
Operator Keywords
c# java
is instanceof
sizeof - (bytes occupd by value type in mem, only in unsafe)
typeof Class.forName (get System.Type obj)
checked unchecked - (overflow excepn ctrl)
* -> [] & - (indirn + addr operators)
- > > > , > > > =
+ - - (delegated concatn removal)
true|false - (operators aswellas literals)
- abstract, sealed are mutex
- structs cannot be abstract as they dont support inheritance
- all abstract mems implicitly virtual
- abstract mutex with static, virtual + override
- abstract fu's must have empty stmt
- subclass fu providg implementn of abstract fu musthave override keyword
- new + override mutex
- overridg mem mustbe delcared with same accessibility modifiers as overridden fu
- override mutex with new, static, virtual, abstract
- mem being overridden mustbe accessible to overridg mem
- warng if atempt to override nonvirtual mem
- sealed + abstract mutex
- structs implicitly sealed + dont support inheritance
- sealed + override on inherited virtual fu -> fu cannot be overridden by subclasses
- sealed class -> cannot be subclassed
- virtual mutex with static, abstract + override
- if extern implement in dll, mems mustbe static + use DLLImport attrib
- extern mutex with abstract
- body of mem modifd with extern mustbe empty
- static fus have no access to this
namespaces
- nested ns: cannot use hierarchical name in single declarn, ie
namespace ns1 { namespace ns2 { namespace ns3 ... not namespace ns1 { namespace ns1.ns2
- if no namespace defd, mems of deflt global ns + no ns requd for access
- ns implicitly public accessibility
- using = import
- 1 mem cannot be imported by using unlike java
using MyNamespace {
using co = com.mycompany; // alias for ns
c# java
goto mylabel ... break mylabel ...
mylabel: ... mylabel: ...
CONTROL FLOW
- cs not support fall-through for case
- goto case "red"; (switch)
- compiler error if goto called in finally
- break : exit enclosg stmt
- continue: start new iteratn of enclosg stmt
string[] s = new string[] {"a", "be", "cee"};
- System.OverflowException if val of checked expr cannot be found till runtime
- unchecked deflt for vars.
- checked deflt for constants
- using ( MyClass c = new MyClass(), MyStruct s = new MyStruct() ) { c.f(); s.f(); ... }
if MyClass, MyStruct implement System.IDisposable
}
pinvoke: Platform Invocation: call unmanaged code fu
b.
OOPs
C# OOP Concepts
- 5 access levels: [webb.98, 102]
- public: free for all
- protected: open for members in currt class + subclasses;
(iff member defs, not for class/module defs)
- private: members of currt class only
- internal: all members in currt proj
- protected internal: members in currt proj + subclasses (iff member
defs, not clas/module defs)
- delegates - call fu's by addr not by name; callback;
types usedto invoke 1/+ methods where actual fu invoked determined at
runtime. -> asynchronous procedures;
custom evt handlers:
public delegate void f();
[webb.112]
- virtual - member canbe overridden in subclasses
- abstract - class defg an interface for subclasses,
cannot be instantiated, only subclassed
public abstract float f();
public abstract float f { get; set; }
- interface - def members a class must provide;
dont provide any bodies, but abstract classes can;
all subclasses inherit interface implentns
of superclasses interface implementns [webb.121]
- subclass : baseclass
- override - subclass member overrides superclass member of same name
and signature (name, param list, param types, return type)
- overload - same name, difft signature
- shadow - derived member replaces base member
- this - call member of currt instance of class
- multiple inheritance notexist
OOP
- base : access base class implementn of member
- inherited mems:
- override : override : public override void f_overridable(int i);
where superclass f musbe public virtual f_overridable()
- hide superclass mems: new ;
mustbe same sig + type, but maybe difft access level + can return difft var type
c.
Data Structures
- value types (java: "primitive types") : byte, int, long, float, double
- reference types: class, interface, array, pointer
- every data type subclass of System.Object
- boxing: auto convert value type to reference type if val type used as object or cast to interface
= java wrapper classes
eg. object xobject = xint; object xobject = 45L;
IInterface i = oMyStruct; if MyStruct implements IInterface
- unboxing
int xint = (int) xobject;
else System.InvalidCastException
- struct like class, but structs removed when scope lost,
public struct MyStruct : IMyInterface { ... }
- structs <-- System.ValueType <-- System.Object
- empty constructors valid for classes, invalid for structs as deflt constructor sets all mems
to deflt vals
- new keyword not requd for instantiatn of structs but then all mems mustbe explicitly
assigned else compiler error
- struct vars cannever be assigned null
- structs cannot have destructors as structs are not garbage collected
- ref or out requd to pass struct by reference, else passed by value + local copy made
- small: structs, large data struct: use class
- structs faster as stack-based
c.
Preprocessor
* #if
* #else
* #elif
* #endif
* #define
* #undef
* #warning
* #error
* #line
* #region
* #endregion
d.
XML Documentation
- /// & which precede user-defined type|member|method|namespace
Recommended Tags
- <param>: describe params
- <summary>: used by IntelliSense in VS to disply info
about type/member
- cref attribute forany tag: provide reference to code element.
- csc f.cs /doc:f.xml
3.
GDI+
System.Drawing
- Graphics
- Graphics g = myButton.CreateGraphics();
- deflt Graphics unit = pixel;
g.PageUnit = GraphicsUnit.Inch;
- g.DrawEllipse(myPen, new Rectangle(10, 10, 50, 20);
(draw ellipse ulhc x, ulhc y, width, height)
g.DrawEllipse(myPen, 20, 30, 10, 50);
- g.DrawBezier()
- g.FillPie(myBrush, new Rectangle(i_x1, i_y1, i_width,
i_height);
- g.DrawRectangle(myPen, myRectangle[]);
- g.FillRectangle(Brushes.Black, 0, 0, Width, Height);
g.FillRectangle(myBrush, 0, 0, Width, Height);
(fill whole form black)
- always call Dispose on all objs consuming resrcs,
eg. graphics, fonts, pens, brushes:
g.Dispose(); myBrush.Dispose();
- Pen (drawg lines, curves, outlines)
- Pen myPen = new Pen(Color.Blue, 5);
(thicknss 5)
- Pen myPen = new Pen(Color.Red); myPen.Width = 5;
myPen.Color = Color.PeachPuff;
- Pen myPen = new Pen(myBrush);|new Pen(myBrush, 5);
(pen based on existing brush)
- Width | Color | StartCap | EndCap (shapes at
line ends)
- Color
- Color c = Color.FromArgb(23,56,78); (rgb 0-255)
- c = Color.FromArgb(100, 255, 255, 255);
(alpha-blendg|transparency 100:0-255)
- c = Color.FromArgb(128, Color.Tomato);
- c = Color.FromName(xDropDownListt.SelectedItem.Value);
- Brush (
abstract|MustInherit base class to create solid shapes for
SolidBrush; TextureBrush;
Drawing2D.{HatchBrush,
LinearGradientBrush,PathGradientBrush})
- System.Object
- System.MarshalByRefObject
- TextureBrush
-
TextureBrush myBrush = new TextureBrush(new Bitmap(@"C:\d\f.bmp"));
- SolidBrush (drawg lines)
- SolidBrush b = new SolidBrush(Color.Black);
(fillg large areas)
- Bitmap (pixel data img)
- Bitmap bm = new Bitmap(10,10);
... bm.SetPixel(x,y,Color.White); ...
myPictureBox.Image = bm;
- ArgumentException : if set pixel outside bounds
- StringFormat
- System.Drawing.StringFormat aFormat = new
StringFormat(StringFormatFlags.DirectionVertical);
g.DrawString(aString, aFont, aBrush, x, y,
aFormat); (vertical text)
IO
- StreamReader : read txt from file.
System.Text
- StringBuilder (mutable sequence of
chars, unlike immutable strings,
efficiency > string as new strings created)
- StringBuilder.Append();
- 16 (deflt) < capacity < Int32.MexValue
- strings are immutable
- string + oper destroys original strg, creates new strg
-> ineffict.
System.Drawing.2D
- HatchBrush
- HatchBrush aHatchBrush = new
HatchBrush(HatchStyle.Plaid, Color.Red, Color.Blue)
(red fg, blue bg)
- LinearGradientBrush
- LinearGradientBrush myBrush = new
LinearGradientBrush(myRectangle,
Color.Red, Color.Yellow, LinearGradientMode.Vertical);
- Double Buffering:
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.DoubleBuffer, true);
SolidBrush |
simplest brush, paintg in solid color. |
HatchBrush |
paints in large no. preset patterns
|
TextureBrush |
paints usg texture, eg. an img |
LinearGradientBrush |
2 colors blended alg gradient. |
PathGradientBrush |
complex gradt of blended colors along
defined unique path. |
4.
Threading
Thread = basic unit to which processor allocates processor time
System.Threading
- Thread
- Monitor : ctrls access to objs by grantg lock for obj
(ie. code regns) to one thrd.
- Monitor.Enter(i): acquire lock for obj/mark beg of
critical sectn.
- TryEnter(): = Enter()
-
Monitor.Wait(myQueue)|Wait(myQueue,100)|Wait(this): release
lock +
callg thrd wait for notificn
- Monitor.Pulse(myQueue) | PulseAll(): next thrd in
wait queue to proceed;
send signal to 1/+ waitg thrds. abt changes to obj's state.
- Monitor.Exit(): release lock on obj
- Monitor locks objs (ie. ref types) not value types.
- cannot be instantiated.
- SynchronizationLockException thrown if value types used.
-
System.Runtime.CompilerServices.MethodImplAttribute
& specify Synchronized value in constructor of
MethodImplAttribute. -> lockg facility for whole method
w/o usg Monitor.
- ThreadState
- ThreadPool
- ThreadPool.QueueUserWorkItem(new WaitCallback(t),
new SomeState(0));
- Mutex :
protect shared resrc from simultaneous access by multiple thrds
- Mutex m = new Mutex(true)|(true, "myMutex");
- Mutex.WaitAll(m); (wait till all released)
- Mutex.WaitAny(m); (wait till any mutex is released)
- m.WaitOne() (wait till mutex m relased)
- m.ReleaseMutex()
- state = signaled (not owned by any thrd) | nonsignaled (owned)
- only 1 thrd at a time can own a mutex obj
- AutoResetEvent
- static AutoResetEvent are = new AutoResetEvent(false);
- are.Set(); (flagging method is done)
- WaitHandle : represts OS waitable objs,
OS-dependant. Monitor portable & more effict.
- WaitHandle.WaitAll(myAutoResetEvent);
- Ticker clashes with System.Threading, if used
in same prog -> "ambiguous reference".
- 5 priorities: 0,1,2,3,4
(ThreadPriority.Lowest | BelowNormal | Normal | AboveNormal |
Highest)
- stop/freeing thread done auto by .net fw clr
Member of ThreadState
enum
| Description |
Aborted | The thread is in the
Stopped
state. |
AbortRequested | The ThreadAbort method has
been invoked on the thread, but the thread has not yet
received the pending System.Threading.ThreadAbortException that will
attempt to terminate it. |
Background | The thread is being executed as a
background thread, as opposed to a foreground thread.
This state is controlled by setting the IsBackground property of the
Thread class. |
Running | The thread has been started, it is
not blocked, and there is no pending ThreadAbortException. |
Stopped | The thread has stopped. |
StopRequested | The thread is being requested
to stop. This is for internal use only. |
Suspended | The thread has been suspended. |
SuspendRequested | The thread is being
requested to suspend. |
Unstarted | The Thread.Start method has not
been invoked on the thread. |
WaitSleepJoin | The thread is blocked as a
result of a call to Wait, Sleep or Join methods. |
4.
Collections
System.Collections
- ArrayList
- Add(): oArrayList.Add( object );
object o = oArrayList[0];
- Remove(): oArrayList.Remove(xobject);
- RemoveAt(): oArrayList.RemoveAt(2);
idx nus reassigned to fill spaces
- .Count: nu items
- readonly : foreach ( object o in oArrayList) { ... o.ToString(); ... } ;
foreach (int i in intarray) ...
- BitArray
- CollectionBase : base for custom collectn classes
- Hashtable
- Queue
- SortedList
- Stack
- Properties: class mems exposg vars/objs usg getter+setter
oTextBox.Text = "hello";
private string slocal;
public string s
{
get{ return slocal; }
set{ if(...)... slocal = value; }
}
- value = val of property being set
readonly props
private readonly int i;
public int xint { get{ return i; } }
- indexer: deflt property, name = this:
public int this[int i] {...}
- Delegates: type-safe functn pointer
public delegate int MyDelegate(double d);
... MyDelegate oMyDelegate = new MyDelegate(f);
- Events:
public delegate void oDelegate(double d); // delegate evt will use
public event oDelegate MyEvent;
...
MyEvent(2); // raise evt
- evt handler = fu called through delegate when evt raised
- if evt withno evt handler raised -> error
- instance evts + shared/static evts
- evt handlers can return value
- Evt Handler
- System.EventHandler = deflt delegate class for most
WinForms ctrls.
- Evt Handler:
oButton.Click += new System.EventHandler( clickHandler );
oObject += new oDelegate(f); // assoc evt with delegate
oObject -= new oDelegate(f); // remove handler at runtime
5.
Windows Forms
- FontDialog
- FontDialog fd = new FontDialog();
fd.ShowDialog();
xform.Font = fd.Font;
- ColorDialog
- ColorDialog cd = new ColorDialog();
cd.ShowDialog();
this.BackColor = cd.Color;
x.
Visual Studio vs.net
- vs has 2 types of windows: Document windows
(content of app)
+ Tool wdws
(componts to create apps)
- 2 edit modes: Design (gui) | HTML (hard-code): at bottom left corner
- IntelliSense: help for completg html elemts, keywords, class
members; doesnt work if C# mis-spellg
as case-sensitive
- Projects pane: shows last 4 saved projs as hyperlinks
- project: collectn of files to ultimately makeup the exec, proj
files: .vbproj or .csproj
- breakpts: select gray margin / F9
- view var values at breakpt: mouse hover / drag to Watch wdw (for
complex vars: arrays)
- stepping, one line at a time : F10 | F11;
Continue | F5: continue all other.
F10: steps over, exec line, stop at next line.
F11: steps in, stop at 1st line of called procedure.
- help: 3 ways to fd topics: Contents wdw, Index wdw, Search wdw
- solution: a grp of projects makg up a single functnal unit.
- start-up proj: proj runs when Start clicked
- solutn file:
C:\My Documents\f.sln (deflt)
- Projects > New Project
- code-behind file: code files created auto by vs when new web form
created, name: webform_basename.cs | .vb = f.aspx.cs | .vb
- vs generates class def, init procedure, Page_Load evt foreach web
forms code-behind file
- donot change "Web Form Designer Generated Code" regns
- #Region directive: +/-: hide/show generated code
- Properties wdw > pageLayout = GridLayout (deflt) | FlowLayout
→ <body ms_positioning="GridLayout"> | <body>
vs Windows :
- Locals wdw: local vars, local to currt context of debugger
in brk mode;
see vars + params while in break mode, + editable in Locals wdw,
even see value of stored procedure params while in
break mode.
- Modules wdw: list + info of modules (dll's, exe's) used by prog
- Output wdw: see
Debug & Trace objs if app in debug mode. TraceListener sends o/p to Output wdw.
- Command wdw: allows users to directly exec cmds in ide.
- Breakpoints wdw: show all breakpts set in app.
- Disassembly wdw: display app assembly code.
- Call Stack wdw: dispaly calls currently on stack
- Threads wdw show threads created by prog beg debugged.
- f.aspx: <@Page inherits="Subclass" %>
links to f.aspx.cs: Subclass : Page (code-behind file in vs.net)
f.aspx: <@Page inherits="Subclass" src="f.aspx.cs" %>
(code-behind file linkg with notepad)
- merge modules: installer packages only installable from other
installer packages; same merge module canbe deployed on any no of apps.
- Xcopy deploymt: deploy assembly used by only 1 app + requires no
additnal setup steps to occur on target compr.
- Web Setups: deploy web apps onto a web server
- Standd Setups: deploy windows desktop apps
- Property Pages dialog: spec. different root ns
- classes not defd within namespace:
MyClass = RootNamespace.MyClass
or MyClass = MyClass
- class defd within namepsace :
MyNamepsace.MyClass
- deflt namespace of app = app name
- 124 namespaces defind:
using System;;
nested namespaces: Ns1.Ns2.Class.Member
- 2 ways of defing namespaces: i) namespace MyNamespace { ... } ;
ii) Property Pages > Root namespace = Mynamespace
- deflt. app namespace = app name.
- 3 eds: Enterprise Architect, Ent. Developer,
Professnal
- Server Explorer > Server > Generate Create Script --> build
data scructure on another server
- Configuration Properties > Debugging > Enable SQL Debugging
-->
debug stored procedures: set breakpt in stored procedure code in Server
Explorer window; Locals wndw shows vars and params.
- Asp.net Web Application = template for a web app.;
web apps put into virtual folder //localhost
\Inetpub\wwwroot\localhost
- //localhost = web root folder
- share new folders under Inetpub\wwwroot
with web before creatg new projects
- creatg virtual folders in vs:
1. create virtual folder
2. Add FrontPage Server Extensions to the virtual folder to create a
subweb. -> vs can create and maintain web apps in that folder.
- subweb: a virtual folder containg a website.
- dblcick (ctrl) in Design wdw -> vs creates evet procedures
for obj's deflt event
- Event Wiring: connectg obj's evt and evt procedure:
vc# requires manual additn of code to InitializeComponent() for
nondeflt evts
- modules: code not havg persistent data;
classes for items defing own storage (for vb.net only, not exist in vc#)
- Toolbox: Drag-Drop ctrl or dblclick
ADO.net usg vs
- ado usg vs:
vs: View > Server Explorer > Connect to Database
> DataLink Properties > [ Provider >
oledb for sql server (deflt, ms sql server) /
oledb Jet 4.0 (ms access)
| Connection > Test Connection ] >
drag item to webform
[webb.228]
- creatg dataset:
rclick(data adapter) > Generate Dataset >
- rclick(dataset obj) > View Schema -->
shown in XML Designer Wdw [webb.232]
-
DataGrid > Properties >
[ Property Builder > Data Source = DataSet | DataMember = tbl ]
[ Columns > Clear Columns Automatically > Available Columns ]
- creatg custom DataView:
Toolbox > Data Ctrls > drag DataView onto webform Design Window
> Table = DataSet: aTable > add DataGrid ctrl to webform
> DataSource = DataView justcreated.
- viewg type info for a dataset:
rclick(dataset in Design window) > View Schema
Printing
System.Drawing.Printing
- PrintDocument : represts a printed doc
- Designer > Win Forms tab > PrintDocument
- PrintDocument oPrintDocument = new PrintDocument();
oPrintDocument.Print(); (start printg)
- oPrintDocument.PrinterSettings.SupportsColor = true;
- PrintPage evt; PrintPageEventArgs
- PrintPageEventArgs
- Cancel | Graphics | HasMorePages | MarginBounds |
PageBounds | PageSettings (if prt job tobe cancelled | obj used to render content
to prtd pg | get/set if additnal pages should be printed | get Rectangle of pg inside
margins | get Rectangle obj of total pg | pg settgs )
- PrintPreviewControl : preview
- oPrintPreviewControl.Document = oPrintDocument;
- oPrintPreviewControl.InvalidatePreview(); (refresh pg displayed)
Misc
-
public void f_keydown(Object o, KeyEventArgs e)
{
if(e.KeyCode == Keys.Down) { f_down(); }
}
publc void f_keypress(Object o, KeyPressEventArgs e)
{
if(e.KeyChar == 'n') f_newgame(); // usg codes for down keys not work
if(e.KeyChar == (char)12) f_quit(); // use numeric key vals
}
- Web Browser control: display html
- Undeletable Files:
# mkdir ALT(789)numpad:numlock=offsam
creates undeletable ¶sam dir, only removable usg same
ascii char code
- Beta Tester: betareq@microsoft.com; betaplace.com
- ibuyspy.com: ms web services example.
References
- [msdn:cpr] = "C# Programmer's Reference":
http://MSDN.microsoft.com > MSDN Library > .NET Dev. > Visual
Studio .NET
> VB & VC++ > Reference > Visual C# Lang. > C# Programmer's
Reference
- [on.net] =
"O'Reilly On Dot Net" http://ONDotnet.com
- "Keys Enumeration" (msdn: .NET fw > Ref. > Class
Lib
> Sys.Windows. Forms )
- .net glossary,
http://www.developer.com/net/csharp/article.php/1756291
- .net books,
http://jztele.com/~coldice/book/net/
Exam Prep
- C# Programming slides,
http://itcourseware.com
MCAD
- c# interview questions (*****)
http://www.techinterviews.com/index.php
- CertYourself
http://www.certyourself.com
- learn csharp
http://learncsharp.cjb.net/
- Dot Net Framework Essentials 2nd ed. *****
http://www.itraining.net.cn/lzh/down/O%27Reilly%20-%20Dot%20Net%20Framework%20Essentials%202nd%20Edition.pdf