.NET Notes

C# Programming

Version 0.01 8/9/2003 by Samar

  1. Lexicology (Cmd-Line; C# OOP; Data Structures; Preprocessor; History; Variables; Classes)
  2. GDI+
  3. Threading
  4. Visual Studio
  5. 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 |
                                 -----------------------

- 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.Permissions

4. Debugging (Trace + Debug; try-catch-finally)

    3 Types of Common Errors
  1. syntax errors
  2. run-time
  3. logical


x. WinForms

System.Windows.Forms
    Form Lifetime Events:
  1. Load: 1st x Form.Show() / Form.ShowDialog() called
  2. Activated: fired if form gets focus, ie. if Form.Show() | ShowDialog() | Activate() Deactivate: fired if focus lost, ie.if Form.Hide() | Close()
  3. VisibleChanged: if Visible prop changd
  4. Closing: if form in process of closg but notyet closed
  5. 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();

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

    OOP

    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


    3. GDI+

    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

    Member of ThreadState enum Description
    AbortedThe thread is in the Stopped state.
    AbortRequestedThe 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.
    BackgroundThe 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.
    RunningThe thread has been started, it is not blocked, and there is no pending ThreadAbortException.
    StoppedThe thread has stopped.
    StopRequestedThe thread is being requested to stop. This is for internal use only.
    SuspendedThe thread has been suspended.
    SuspendRequestedThe thread is being requested to suspend.
    UnstartedThe Thread.Start method has not been invoked on the thread.
    WaitSleepJoinThe thread is blocked as a result of a call to Wait, Sleep or Join methods.

    4. Collections


    5. Windows Forms


    x. Visual Studio vs.net

    ADO.net usg vs


    Printing

    System.Drawing.Printing

    Misc


    References