From Wikipedia, the free encyclopedia
[edit] ide / keyboard shortcuts
- Ctrl+Shift+Space - intellisense - For help (e.g. format), "string format" is a bold after ".WriteLine(". use "string format" in index help.
- Ctrl+space
- Always use the bin/ directory (not the obj/)
- Could refactor your code automatically
- Task List view -> searches for comments with "TODO" and "TASK"
- Press tab,tab during intellisense. Also, Insert Snippet (Right click). There is also a Code Snippet Manager (Tools).
-
-
- Snippy - gotdotnet.com - Manage snippet xml.
- Better than comments! (IDE thing)
#region Name_name
......
#endregion
- "Property pages" -> Publish (For deployment)
- Versioning: Major.Minor.Release.Build [2.0.0.1]
- Strong Named Assembly... Add a "orgKey.snk" in the properties
- GAC:
c:\windows\assembly in HD
Access this via .net configuration (control panel). The Key is also found here
ngen.exe install file.dll - Nativa code generator (Can only gen signed code). Cannot decompile this.
caspol.exe - Code access security policy
fuslogvw.exe - Assembly binding Log Viewer (Run fuslogvw, run file.exe, refresh fuslogvw)
- Need to put a path in the log to disk.
perfmon (windows standard) - Look at ".NET CLR memory" as Performance object. Then select the specific Counter.
- Assembly are searched in: (Assembly/.dll is usually 1:1 with namespace)
Application Config File - "Add" application Config file (.ini file equivalent). Should be "app.config" filename.
<configuration>
<runtime>
<assemblyBinding
xmlns="urn:schemas-microsoft-com:asm.v1">
<probing privatePath="libs"/>
<publisherPolicy apply="no"/>
<dependentAssembly>
<assemblyIdentity name="AReverser" publicKeyToken="paste_the_public_token_here_from_.net_config"></assemblyIdentity>
<bindingRedirect oldVersion="2.0.0.0"
newVersion="2.0.1.0"></bindingRedirect>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
Publish policy
Machine.config
csc /? // Help
csc /out:file.exe /t:exe|library /r:ref1.dll,ref2.dll file.cs
[edit] Introduction
?? expr -> This is a "print(expr);". Shorthand for display returned value.
??? -> Need to check/not sure of the implementation
- "Lutz Roeder" - Reflector - decompile MSIL
- "using" is not a #include.... so that you would not type the entire System. etc,
- WebExpressions -> Layout of a web (another product)
- CLR - Common Language Runtime (Virtual Machine)
- MSIL-Microsoft Intermediate Language, JIT-Just in Time Compilation, Garbage Collection
- PE - Portable Executable, GAC - Global Assembly Cache
- IJW - It just works!
- Metadata -> System.Reflection.Assembly (e.g. [Assembly: ...]) "Assembly" is an attribute type
- ErrorProvider (in Toolbox) - WinForms
- See Course Book for ASP.NET in Module 3.
- Versions:
1.1 - Training Manual
2.0 - Visual Studio 2005
3.0 - Vista
- Managed C# --> Managed C++; ---> Unmanaged C++ (Use the Manged C++ as a layer)
- System.Object (standard methods)
Public Equals - (Overloaded) Determines whether two Object instances are equal
Public GetHashCode - hash function
Public GetType - Get the type of the object
Public ReferenceEquals - Determines if the specified Ibject are the same instance (same address)
Public ToString - Returns a string that represent the object. Override this if needed.
- Special object method called internally if a function is requiring a string argument (and you passed the object as argument).
Protected Finalize - Allows Object to attempt to free resources and perform other cleanup operation before the Object is reclaimed by garbage collection
Protected MemberWiseClone - Creates a shallow copy of the current Object
Value-type: Stored in Stack - Exist only within the scope
- Built-in Value Type
- struct (User-Defined Value Types). Cannot have default constructor "()". Struct works just like Class (difference in memory allocation).
- enum (Enumerations)
Reference-type: Stored in Heap - Garbage Collected - Allocated during "new" declaration.
- All others / Objects, Class
bool - System.Boolean - true/false
char - System.Char - Unicode 16 bit
sbyte - System.SByte - signed 8 bit integer
short - System.Int16 - signed 16 bit integer
int - System.Int32 - signed 32 bit integer
long - System.Int64 - signed 64 bit integer
byte - System.Byte - unsigned 8 bit integer
ushort - System.UInt16 - unsigned 16 bit integer
uint - System.UInt32 - unsigned 32 bit integer
ulong - System.UInt64 - unsigned 64 bit integer
float - System.Single - 32 bit
double - System.Double - 64 bit
Public - World (default: enum, interface)
Protected - Including Derived
Internal - within assembly -> .dll/.exe
Private - same class Class only (default: struct, class). Note: In C++ this is public.
Protected Internal - protected OR internal (not and)
- Polymorphic is when you assign baseclass=Derivedclass (No polymorphism in javascript bec it is untyped)
implicit: (small) char -> int -> float (big)
explicit: (small) char <- int <- float (big) - Bec some information could be lost
int x=25; double d=x; // no error
double x=36.7; int z=(int)x; // need to explicitly cast
dog = (Dog)a;
dog = a as Dog; // same as above (Dog, Cat is OBJECT)
if(a is Cat) { } // dynamic casting is happening
if(a.GetType()==typeof(Cat)) { } // same as above
Overload implicit/explicit Conversion (if the objects are not related/inherited):
static public implicit operator byte(digit d) { // byte is object, digit is object
return(d.Data);
}
static public explicit operator digit(byte b) { // bec digit is smaller than byte
return(new digit(b))
}
- Identity/Equality, Overloading Operators
objx s1 = new objx("ABC");
objx s2 = s1;
objx s3 = new objx("ABC");
?? object.referenceEquals(s1,s2) // boolean TRUE (object.equals) is the same as referenceequals???
// This is identity
== -> object.equals // Equality
?? object.equals(s1,s3); // identity is FALSE, Equality is TRUE (Overload the .equals and == operator)
static bool operator==(objx lhs, objx rhs) {
if((object)lhs==null) return false;
return(lhs.Equals(rhs);
}
public override bool Equals(object obj) { // use object so that polymorphism will take effect
if(obj==null || obj.GetType()!=this.GetType)) return false;
// || (!(obj is student)) ) // Another way
student arg=obj as student;
return(this.name == arg.name && ..code.. );
}
Guidelines:
* If overriding Equals override GetHashCode
* If overloading ==, override Equals to use the same algorithm
* If implementing IComparable, implement Equals
* Equals, GetHashCode, and == operator should never throw exceptions
* Overload != when overloading ==. != should be a ! of Equals.
[edit] Objects & Syntax
- "static" method - class method.
- non-static - instance method - object
foo(ref int x) { } // as a pointer
foo(out int x) { } // out is out only. ref is in/out. default is in only.
const int rows=45; // constant
int x;
object o=x; // boxing
int y=(int)o; // unbox
virtual public int methodname() { } // identifies an overloadable method (base class)
public override int methodname() { } // derived class override. Can only override virtual method.
public new int methodname() { } // New methodname (not derived). Difference in polymorphic behavior.
public abstract void method(); // Method is not defined in base class, it must be defined in derived class.
public sealed override void method(); // Cannot use this in Base class. Any derived class cannot override Foo.
public static void method(); // Can only accessed via the classname!
public readonly int var; // readonly, can be initialized in constructor
public const int var=3; // const: compile time constant. Const is always static.
base.foo(); // Calls the base ???
Type t=obj.Gettype; // Gets the type ???
params char[] // variable number of arguments ???
yield return(val); // New in 2.0. used inside IEnumerable function.
using System;
namespace Days1 {
public class Employee { // : Object (derived from Object, implied)
// Fields
public static int globid=2; // This is a built in constructor.
public string sex="Male"; // This is also a constructor (default)
private string name;
// public static Employee() { } // static constructor are called after a program begins running but before the 1st instance of the class is created.
public Employee() : this("Noname") { } // Default Constructor, calls another constructor
public Employee(string name) { // Constructor
this.name = name;
}
public string getname { // Property
set { name=value+" OK"; } // value is a reserved word
get { return("Mr "+name); }
}
public int func_id(int id) { // Method
globid = id;
return (globid);
}
public int func_id() { // override for no arguments
return (globid);
}
public static Employee operator +(Employee c1, Employee c2) { } // Creating operators
}
public class Program
{
public static void Main()
{ // Main Function
Employee aa = new Employee();
Employee bb = new Employee("Fred");
Console.WriteLine("Hello {0} {1}", aa.getname, aa.func_id(43)); // Hello Mr Noname 43
Console.WriteLine("Hello {0} {1}", bb.getname, bb.func_id()); // Hello Mr Fred 43
// THIS IS A STATIC example!
Console.WriteLine(Employee.globid); // This is the way to access static members
aa.sex = "Female"; // Write to a member directly
}
}
}
- Interfaces - No Implementation. Just like a .h in C. Starts with "I". An object can have multiple interfaces.
-
- * Do not put public/private/protected in interface
interface ICDPlayer {
void Play(short PlayTrackNum);
short CurretTrack { get; set; }
}
public class Device : ICDPlayer { ... }
public class name : DeriveBase, [Iinterface1, Iinterface2, Ietc..] { .... }
abstract class Animal { } // Cannot use abstract class in "new".
// Use this when base class does not implement the member.
// Abstract has code but it is not complete (interface doesnt have any code)
sealed class Classname { } // Cannot be inherited
ushortAge = Convert.ToUInt16(longAge); // Convert class
- Singleton - Private Constructor. Useful if there is only one spooler for example.
class Singleton {
private Singleton() { } // Need to declare as private
static private Singleton thedata;
static public Singleton GetSingleton {
get { if (thedata == null)
thedata = new Singleton(); // will only be executed ONCE
return thedata;
}
}
}
....
Singleton s1=Singleton.GetSingleton;
Singleton s2=Singleton.GetSingleton; // s1 is the same as s2
Singleton s3=new Singleton(); // This is INVALID bec the constructor is private!
[edit] Using / enum / pointers
System.IO.FileStream aFileStream;
vs
using System.IO;
FileStream aFileStream;
vs
using alias1 = System.IO.FileStream
alias1 aFileStream;
// Temporary Resource Usage Pattern (note: Resource is a user object that implements IDisposable)
using (Resource r1 = new Resource()) { // battle with compile time error. This is a better way of coding.
r1.Foo();
}
-is the same as-
Resource r1 = new Resource(); // battle with runtime error
try { r1.Foo() }
finally {
if(r1 != null) ((IDisposable)r1).Dispose();
}
- enum access (enum (builtin) vs Enum (Class))
enum Weekdays { Monday, Tuesday, Wednesday, Thursday, Friday }; // declare enum type (Cannot do this in function/method)
....
Weekdays wd;
string st = Console.ReadLine(); // Get input
wd=(Weekdays)Enum.Parse(typeof(Weekdays), st); // Convert the enum string
if (wd == Weekdays.Friday) { .... }
[Flags] enum Weather : ushort { Sunny=1, Cloudy=2, Rain=4, Snow=8,Flog=16};
Weather ww;
ww = Weather.Sunny | Weather.Cloudy; // the enum holds both
?? ww.ToString() // Sunny, Couldy
- Pointers (Useful in efficient Algorithms e.g. bitmaps)
byte bref;
unsafe { // need to uncheck in project settings
fixed (byte bp=&bref) {
...code...
}
}
[Dllimport("legacy.dll")]
void Algo( );
Algo();
- BackGroundWorker class (Doing stuff in Background)
[edit] Arrays
- System.Array is the Base Class. Interfaces: ICloneable, iList, ICollection, IEnumerable
objx[] xx = new objx[sizeN] { new objx(...), new objx(...) }; // Array of objects
int[] intArray = new int[sizeN];
int[,] multidim = new int[ , ] { {1,1,1},{2,2,2} }; // or int[,,]
int ex = multidim[1,2]; // Layed out linearly in memory (could be accessed via single dim array)
int[][] jaggedarray = new int[4][]; // jagged array
for(i=0;i<jaggedarray.Length;i++)
jaggedarray[i]=new int[++dim];
foreach(int[] rows in jaggedarray)
foreach(int col in rows) { }
IEnumerator iter = intarray.GetEnumerator();
while(iter.MoveNext()) { ?? iter.Current }
iter.Reset(); // set the enumerator at the top. (Cannot modify the source object if you are currently using the enumerator)
Array.Sort(intArray); // boxed (slow). Modifies the intArray.
Array.Sort<int>(intArray); // faster, more efficient (parameterized)
// Make objects IComparable<parameterized> (interface) so that sort could be used. Use the standard design pattern/template.
Array.Sort<int>(intArray, new DescComparator()); // DescComparator is a IComparable ???
Array.Reverse<int>(intArray); // Reverse it
ArrayList emplist = new Arraylist(); // Generic. You could add emplist.add(3.2);
Employee e = new Employee(...);
emplist.add(e);
emplist.add(new Employee(...));
emplist.Insert(idx, new Employee(...));
emplist.Sort(); // No parameterized implementation for ArrayList.
?? emplist.Indexof(e) // integer
?? emplist.Contains(e) // bool
?? emplist[idx]
IEnumerator curr = emplist.GetEnumerator(); // This is object
IEnumerator<Employee> curr = emplist.GetEnumerator(); // Specific to employee (if parameterized)
// curr.Current.Method could be used
as IvalueType ???
List<Employee> emplist = new List<Employee>(); ??? // specific to Employee!!
Array.ForEach<int>(intArray, new Action<int>(delegate(int arg) { ++arg; } ) ); // However, the array is not changed bec "int arg" is passed as values.
public int CompareTo(Object obj) { // standard sort compareto function
if(obj==null) return 1;
if(!(obj is classname)) throw new ArgumentException();
// Do comparison, -1 if this<obj, 0 if this==obj, 1 if this>obj
}
- hashtable - efficient lookup
- Dictionary - tree type
- In hashtables, the .GetHashCode() is NOT CALLED internally! (Stupid why they have .GetHashCode()).
Hashtable hh = new Hashtable();
hh["aa"] = "1st";
hh["aa"] = "2nd"; // This is ok. Using .add willnot work
hh["aa"] = objx; // Could be any object
hh[objx] = "3rd"; // Key could also be anything. In this case the key is the object (it's NOT calling the .toString internally)
?? hh["aa"] // "2nd"
?? hh.ContainsKey("cc")) // False. hh.Contains() actually calls hh.ContainsKey()
foreach (object key in hh.Keys) // simpliest way
?? hh[key] // key is automatically converted to string
foreach (DictionaryEntry d in hh) { // another method
Console.WriteLine("{0} = {1}", d.Key, d.Value);
Console.WriteLine("{0} = {1}", d.Key, hh[d.Key]); // Same as above, but above is more efficient bec data is already retrieved
}
IDictionaryEnumerator ky = hh.GetEnumerator(); // another method
while(ky.MoveNext())
Console.WriteLine("{0} = {1}", ky.Key, ky.Value);
SortedList hh = new SortedList(); // SortedList example. Use this if you want "sort(keys(%hh))" in perl
hh["nn"] = "value";
foreach (string ss in hh.Keys) // Can use string directly. This is already sorted
?? hh[ss]
Dictionary<string, string> dict = new Dictionary<string, string>(); // Dictionary example
dict["nn"] = "value";
foreach (string ss in dict.Keys) // Can use string directly
?? dict[ss]
Hashtable table = new Hashtable();
foreach (Employee emp in emplist) // ie, if Employee is IEnumerator
table.add(emp.GetHashCode(), emp); // Cannot .add duplicate key. Implicitly call .GetHashCode()
?? table.ContainsKey(key);
?? table.ContainsValue(value);
[edit] Exceptions / Error
- C# - Try NOT to create your own exception CLASS.
try {
...code...
} catch(IndexOutOfRangeException e) { // THIS SHOULD BE SPECIFIC
?? e.Message
} catch(Exception e ) { } // THIS is ANY exception
throw new IndexOutOfRangeException();
} finally {
// place code that runs after try to catch runs
}
[edit] Mixing Managed/Unmanaged
- Mixing Managed and Unmanaged Useful Information
- Blittable Types - do not require conversion when passed between managed and unmanaged code.
- System namespace blittable types
-
-
- System.Byte
- System.SByte
- System.Int16
- System.UInt16
- System.Int32
- System.UInt32
- System.Int64
- System.IntPtr
- System.UintPtr
- Non-Blittable types - require conversion when passed between managed and unmanaged code. Delegates, which are data structures that refer to a static method or to a class instance, are also non-blittable.
- System namespace Non-blittable types
-
-
- System.Array Converts to a C-style or a SAFEARRAY.
- System.Boolean Converts to a 1, 2, or 4-byte value with true as 1 or -1.
- System.Char Converts to a Unicode or ANSI character.
- System.Class Converts to a class interface.
- System.Object Converts to a variant or an interface.
- System.Mdarray Converts to a C-style array or a SAFEARRAY.
- System.String Converts to a null-terminated string or to a BSTR.
- System.Valuetype Converts to a structure with a fixed memory layout.
- System.Szarray Converts to a C-style array or a SAFEARRAY.
Wtype.h Type C# Type
HANDLE int
BYTE byte
SHORT short
WORD ushort
INT int
UINT uint
LONG int
ULONG uint
BOOLEAN int
CHAR char
FLOAT float
DOUBLE double
LPSTR(and most String for in, StringBuilder for inout
other string
types)
[edit] String / Formats / Regular Expressions
- String (C#) vs string (built-in). These are the same! string allocates the exact memory! (immutable - Always creates new copy)
-
-
- Using string for non-changing string. Use stringbuilder for strings that change (efficient).
- No limit for string length (memory limit only)
starr = new string[] { "txt1", "txt2", "txt3" };
?? starr.Length // Number of elements
string name; // name has null value
(name="") == (name=string.Empty) // These are equivalent
((string)e.Current).TrimStart('a') // implicitly convert e.Current to a string.
?? "Hello"[2]; // "l" 3rd character
?? @"C:\Docs\Source"; // rather than "C:\\Docs\\Source".
?? "\u0068ello "+"world"; // "Hello world"
int ii=int.Parse("12,345", NumberStyles.AllowThousands | NumberStyles.CurrencySymbol, cultinfo); // string to number. 2nd argument is optional. It's enum. cultinfo is CultureInfo
string ss=String.Format("{0:###-##-####}",34);
int ii=String.Compare(str1, "Hello");
string ss=String.Join(",", words); // also, string s2 = String.Join(",", (new string[] {"a","b"}));
string ss=(100).ToString("C"); // "$100.00", same as Console.WriteLine("{0:C}", 100);
string ss="hello".ToUpper(); // .ToLower()
string ss=" hello ".Trim();
string ss="hello".PadLeft(20,'-');
string[] words=line.Split(null); // returns an array, separate by whitespace
StringBuilder sb=new StringBuilder("string"); // Ultra fast!!! (if you manipulate strings a lot);
sb.Append("added text");
if(sb.ToString() == "abc"); // Checks if sb equals "abc"
if(sb.Equals(new StringBuilder("abc"))); // Another Way
string[] sx = Directory.GetCurrentDirectory().Split(Path.DirectorySeparatorChar); // Path.DirectorySeparatorChar=='\\'
foreach(string sx1 in sx) ?? sx1;
DateTime curdate = DateTime.Now; // This is a struct so no need for "new"
Console.WriteLine("{0:C}", 100); // $100.00
Console.WriteLine("{0:d}", (new DateTime(2000,1,10,0,0,0))); // "1/10/2000"
// d-"MM/dd/yyyy" D-"DD MMMM YYYY" f-"DD MMMM YYYY HH:MM" F-"DD MMMM YYYY HH:mm:SS"
// C-"$nn,nnnn.nn"
CultureInfo ci = new CultureInfo("En-GB"); // Use Cultures
- Put Regular Expressions examples here
Regex ex = new Regex("ab+", RegexOptions.IgnoreCase); // create the regular expression. RegexOptions is enum
string line = "abbbabababbfabrbdbsbaaab";
foreach (object oo in ex.Matches(line)) // .GetEnumerator() is implicitly called in foreach
Console.WriteLine(oo); // .toString is implicitly called bec writeline arg type is string.
MatchCollection mc = ex.Matches(line); // Long method
IEnumerator e = mc.GetEnumerator();
while (e.MoveNext()) Console.WriteLine(e.Current);
if(ex.IsMatch(line)) { } // Regular expression matched
[edit] Memory and Garbage Collection
- There are two heaps: Managed heap and the Large Managed Heap (object > 20KB). Both are doing the same garbage collection algo.
- Destructor. Use this for non-memory resources (e.g. file handling)
class Foo {
~Foo() { fs.close(); } // implicitly called
}
objx a1 = new objx();
a1=null; // The memory allocated for the "new" object is now ready for garbage collection.
- Garbage Collection: ONLY MEMORY resources are garbage collected.
- -----------------------
- | Finalize Queue
- | - objects are added here the same time as in Root Ref if the object has destructor
- -----------------------
- |
- | Managed Heap
- |
- -----------------------
- | ---------------------
- | | Freachable Queue // objects from Finalize Queue are moved here during GC
- | ---------------------
- | Root Ref
- -----------------------
- Finalize - Runs on different thread. Executes the Freachable Queue
- Generations: Max of 2 generations. Generation0-1st execution of GC. Gen1-those that lived after 1st GC. Only execute GC on Gen0.
- Ressurrection is a bad idea.
GC.Collect([int Generation])
GC.GetGeneration(Object obj); // query the generation of an object
GC.MaxGeneration(int);
- Weak Reference (e.g. Cache)
objx sr = new objx();
WeakReference wr = new WeakReference(sr);
sr=null; // deallocate it
... // GC.Collect(); // dispose
if( (sr=(objx)wr.Target) != null ) { // or check if(wr.isAlive) { }
treat_sr_normally();
} else {
sorry_no_more_sr();
}
unsafe {
int i=3;
int* ip=&i;
fixed (byte* bp=buf) { // buf is defined somewhere
*(bp+3) = 34;
...etc
}
[edit] Data Stream and Files
Read, Write, Seek // Fundamental Stream Operations
- CanRead, CanWrite, CanSeek // properties
- Flush()
- Close() // performs implicit flush
NetworkStream, BufferedStream, memoryStream, FileStream, CryptoStream // Stream Classes
BinaryReader, BinaryWriter // Binary classes
TextReader, TextWriter // character classes
StreamReader, StreamWriter // derived from TextReader/Writer
StringReader, StringWriter // derived from TextReader/Writer that uses StringBuilder class
FileStream - Class for Reading and Writing to Files
FileMode - Open, Append, Create (enum)
FileAccess - Read, ReadWrite, Write (enum)
FileShare - None, Read, ReadWrite, Write (enum)
File - Class with methods for Create, Copy, Delete, Move, Open
FileInfo - Just like File Class but faster when reusing the object.
Directory - Class for Directories
DirectoryInfo - Faster than Directory bec one security check
Path - Helper Class for Paths
FileSystemWatcher - Class used to Monitor a File System
IsolatedStorageFile - Class for Isolated Storage
IsolatedStorageFileStream
.Begin* - Asynchronous methods
.End* - Asynchronous methods
if(!File.Exists("filename")) { } // exists
FileStream fs = new FileStream("filename", FileMode.CreateNew); // FileMode.Open
BinaryWriter w = new BinaryWriter(fs);
w.write( (int)45 );
w.Close(); fs.Close();
BinaryReader r = new BinaryReader(fs);
?? r.ReadInt32()
FileInfo fi = new FileInfo(Path.Combine(dir,subdir));
if(!fi.Exists) { };
using(StreamReader sr = fi.OpenText()) { }
FileStream astream = File.Create("name"); // Another way
DirectoryInfo dir = new DirectoryInfo(".");
foreach(FileInfo f in dir.Getfiles("*.*")) {
?? f.Fullname;
?? f.Length;
?? f.CreationTime;
}
FileSystemWatcher watcher = new FileSystemWatcher(); // Create ================
watcher.Path = "pathstring"; // or args[0]; // Configure =============
watcher.Filter = "*.txt"
watcher.NotifyFilter = NotifyFilters.FileName; // this is enum
watcher.Renamed += new RenamedEventHandler(OnRenamed); // this is the lightningbolt! on ide
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.IncludeSubdirectories = true; // include subdirectory
watcher.EnableRaisingEvents = true; // Begin Watching ========
public static void OnRenamed(object s, RenamedEventsArgs e) {
?? e.OldFullPath
?? e.FullPath
}
IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForDomain();
IsolatedStorageFileStream isoStream - new IsolatedStorageFileStream("MyStuff.txt", etc);
using(StreamWriter wr = new StreamWriter(isoStream)) { wr.WriteLine("Stuff"); }
IsolatedStorageFile isoread = IsolatedStorageFile.GetUserStoreForDomain();
string[] isoFiles = isoread.GetFilenames("MyStuff.txt");
[edit] Serialization
- See Module12 for complete examples and see DemoFiles also. (The example includes XML writing via SoapFormatter). See below for the basic template.
- Persistence - Store and retrieve a graph of objects to and from a file
- Remoting - Pass by Value arguments that are transmitted between processes
- Use Serialization if you have objects with reference to each other. e.g. obj1 -> obj2
[Serializable] public class Myclass {
[NonSerialized] int _cachSize; // Skip specific members
....
}
[Serializable] public class ExampleFoo : ISerializable { // Example
public int i,j,k;
public ExampleFoo() {}
internal ExampleFoo(SerializationInfo si, StreamingContext context) {
i=si.GetInt32("i"); j=si.GetInt32("j"); k=si.GetInt32("k");
}
public void GetObjectData(SerializationInfo si, StreamingContext context) {
si.AddValue("i",i); si.AddValue("j",j); si.AddValue("k",k);
Type t=this.GetType();
si.AddValue("TypeObj", t);
}
}
FileStream fs = File.Create("Person.xml"); // SOAP example
SoapFormatter sf = new SoapFormatter();
ArrayList al = new ArrayList(); // Then put mutliple objects in al. For this example, Person objects.
sf.Serialize(fs, al);
fs.Close(); // DONE
fs = File.OpenRead("Person.xml");
ArrayList al = (ArrayList)sf.Deserialize(fs); // READIT
[edit] Delegates & Events
- Delegate is universe. Event is a subset of Delegate (solar system).
- Delegate is Function object. Should always treat it as MultiCast. (SingleCast should not be used!)
public class objx { // Sample Object
public string foo(int id) {
return (id.ToString() + " from foo");
}
}
delegate string MyDelegate1( int ii ); // syntax. "int ii" bec foo() takes in int. string bec foo() returns string.
Mydelegate1 myhandler = null; // This portion is just semantics. It wont work, refer to SwitchandLight for a working one.
function connecto(MyDelegate1 del1) {
myhandler += del1; // adds delegates
}
objx oo = new objx();
MyDelegate1 dd = new MyDelegate1(oo.foo);
?? dd(21); // Call the delegate. This will return "21 from foo"
[edit] Web Services / Request / Sockets
- WCF - Windows Communocation Foundation (Remoting is becoming obsolete)
- "wsdl http:www.webservicex.net/file.asmx?WSDL" (Web service). -> This creates a class library file. Then open this.
Using System.Xml;
...
USZip zipper = new USzip(); // USZip is created by wsdl automatically. Need to add "System.WebService" as reference
XmlNode node = zipper.getInfoByZIP(97210); // Then do something with node
- Create a new .asmx web service via Visual Studio wizard. Use the following:
[WebMethod] public String myfunc() { return("Hello World"); }
WebRequest request = WebRequest.Create("localhost:3427");
reqyest.Credentials = CredentialCache.DefaultCredentials;
WebResponse response = request.GetResponse();
?? ((HttpWebResponse)response).StatusDescription
WebBrowser1.Url = new Uri(addr);
For Socket... see sockets example from Lab and manual
[edit] ADO.NET
SQL <---> OLEdb
SqlConnection Class
SqlCommand Class
SqlAdapter Class
OLEdb Class
using(SqlConnection mysql = new SqlConnection(@"Connection String")) { // to determine connection string: (New Web App: Choose Item: SQLConnection, drag to desktop, goto properties "Connection String", then you should see "Add Connection" window)
?? mysql.ConnectionString
string ssql = "select * from region";
SqlDataAdapter adaptor = new SqlDataAdaptor(ssql, mysql);
DataSet mydataset = new DataSet();
adaptor.Fill(mydataset, "Regionx"); // Name of the table that gets created?
?? mydataset.Tables["Regionx"].Rows.Count
adaptor.SelectCommand.CommandText = "select * from customers"; // Another query
foreach(DataRow mydatarow in mydataset.Tables["Regionx"].Rows)
?? myDataRow["RegionID"].ToString(); // RegionID is a field
adaptor.update -> Update the database
DataView mydataview = mydataset.Tables["Regionx"].DefaultView;
mydataview.Sort = "Country";
mydataview.RowFilter = .....
}