Wednesday, October 31, 2007

Trust Level in Dot Net

Trust level refers to permission set in the web.config file
"system.web"
"securitypolicy"
"trust level="medium""
"/trust"
"/securitypolicy"
Application operating under a Medium trust level have no registry access, no access to windows eventlog, and cannot use reflection, file system access is limited to the applications virtual directory hierarchy.

Different trust levels
"trust level="Full|High|Medium|Low|Minimal""

ASP.Net 1.1 and 2.0, medium trust application can access SQL server database because SQL Server data provider does not demand full trust and SqlClientPermission is granted to medium trust applications.
In 2.o Oracle .net provider, the OLE DB .NET data provider, ODBC .NET data provider no longer demand full trust.

DOT NET 2.0 Notes Part 3

Threading

Thread th = new Thread(new ThreadStart(Test));
ThreadStart is a delegate which doesn't take parameter, we can give a reference to the method which do not take any parameter.

Thread.Sleep(3000); //will cause the current thread to sleep for 3 secs, i.e. 3000 ms.
th.Join(); //if any other thread has no finished its task it will block the main thread till the another thread finishes

ThreadPriority Enumeration consists of values that can be use to set or get the thread priority.
ThreadPriority.Highest, ThreadPriority.Lowest, ThreadPriority.Normal etc.

To pass information to the thread use delegate ParameterizedThreadStart
E.g.
//function to be called by the ParameterizedThreadStart
public static void TestParametereized(int i)
{
}
ParameterizedThreadStart pt = new ParameterizedThreadStart(TestParametereized);
Thread thP = new Thread(pt);
thP.Start(10);
// to stop the thread, system prepares ThreadAbortException, whether caught
// or not thread will be stopped.
thP.Abort();

Code between Thread.BeginCriticalRegion(); and Thread.EndCriticalRegion(); is treated as a single line of code, while executing the code between this block if the thread receives a Abort Signal it will complete executing the code between this block and then die throwing ThreadAbortException, this way it will leave the object in a consistent state.


Q) What type of object is required when starting a thread that requires a single parameter?
A) ThreadStart delegate.

Q) What method stops a running thread?
A) Thread.Abort

Sharing Data Multi Threading

Synchronization with windows kernel objects:

Mutex : Allows synchronization (locking mechanism) across AppDomain and Process boundries, e.g. Single instance application.
Semaphore

Event : Provides a way to notify to multiple threads that event has occured.

Mutex, Semaphore, AutoResetEvent, ManualResetEvent all derive from WaitHandle class.

On mutex created with a well-known name, one can use OpenExisting method to get a Mutex that has already been created.

Event class are type of kernel objects that has two states, on and off. These states allow threads across an application to wait until an event is signaled to do something specific.

Asynchronous Programming Model

Three styles to deal with handling of the end of the call in an asynchronous call.
Wait until done
Polling
Callback

Wait until done: Use BeginInvoke methode and pass null for callback and stateobject. E.g. BeginRead of FileStream, call EndInvoke (e.g. EndRead) this will block the thread until the asynchronous call is done.
E.g.
IAsyncResult iResult = fw.BeginRead(buffer,0,buffer.Length,null,null);
int nByteRead = fw.EndRead(iResult); //thread will be blocked, until the asynch is done.

Polling: Use BeginRead and get the reference to AsynchResult, Code will poll IAsyncResult to see whether it is completed.
E.g.
IAsyncResult iResult = fw.BeginRead(buffer,0,buffer.Length,null,null,);
while(!iResult.IsCompleted)
{
Thread.Sleep(1000);
}
Callback Model:




System.Globalization to address the geogrophical scope of the application

Invariant Culture: This culture category is culture-insenistive, useful when creating trial application, not based on English language but is associated with it and bears more similiarity with it.

Neutral Culture: English, French, and Spanish are all neutral culture, a neutral culture is associated with Language but has no relationship to countries or region. A neutral culture is designated by the first two characters in CultureInfo class.

Specific Culture: Most Precise of three, represented by a neutral culture, a hyphen and then a specific culture abbrevation. e.g. fr-FR, en-US.

E.g. to set a culture of current thread.
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");
Console.WriteLine((1000).ToString("C"));

Dot Net 2.0 Notes Part 2

Serialization

Q) What is serialization?
A) Serialization as implemented in the System.Runtime.Serialization is the process of Serializing and Deserializing objects so that they can stored or transferred and then later recreated.

Q) What is Serializing?
A) Seraializing is a process of converting object into a linear sequence of bytes that can be stored on disk or transferred over network.

Q) What is Deserializing?
A) Deserializing is a process of converting previously serialized sequence of bytes into an object.

E.g. Serializing

FileStream fs = new FileStream(@"c:\test_env\serialized.dat", FileMode.Create, FileAccess.Write);
//binary formatter to perform serialization
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, "This data string will be written to the file as binary data");
fs.Close();

E.g. Deserializing
FileStream fr = new FileStream(@"c:\test_env\serialized.dat", FileMode.Open);
string strIn = string.Empty;
strIn = bf.Deserialize(fr) as string;

Q) How to create a class that can be serialized?
A) If you are satisfied with the default handling of serialization then [Serializable] Attribute to the class is enough, when a class is serialized, runtime serializes all the members including private members.

refer the below example for using various attributes with serialization.

Runtime calls GetObjectData during serialization and serialization constructor during deserialization

[Serializable] //Attribute for serializing and deserializing objects of custom class
class Test:IDeserializationCallback //implement OnDeserialization which will be called once serialization is complete
{
public int i;
public int j;
//total will not be serialized and deserialized, i.e. disable serialization of specific members only.
[NonSerialized] public int total;

//if changes are made to this class, but there are serialized object of
//the instance before this field was added, OptionalField attribute would
//not affect serialization, but during deserialization if the member was not serialized
//it will leave the members value as null rather than throwing exception
[OptionalField] public int offset;

void IDeserializationCallback.OnDeserialization(object sender)
{
total = i + j;
}
}


Two methods for formatting serialized data both of which implement IRemotingFormatter interface.
For BinaryFormatter : Only for .Net Framework
using System.Runtime.Serialization.Formatters.Binary;

For SoapFormatter add reference to "System.Runtime.Serialization.Formatters.Soap" Serialize objects that will be transmitted across network.
using System.Runtime.Serialization.Formatters.Soap;
Consumes 3 to 4 times more space.

XML Serialization:
Can serialize only public data, cannot serialize private data
Cannot serialize graphs, only objects.

E.g.
TestXMLS tm = new TestXMLS(10, 20);
XmlSerializer xm = new XmlSerializer(typeof(TestXMLS));
FileStream fs = File.Create(@"c:\test_env\test.xml");
xm.Serialize(fs, tm);

Thursday, October 25, 2007

DOT NET 2.0 Notes Part 1

Q) What is a Reference Type?
A) Reference type store the address of their data, also known as pointer on the stack, actual data is stored on the Heap.

Q) What are partial Classes?
A) Partial classes allows you to split a class definition accross multiple source files.

Q) Why to use Generics?
A) Casting causes boxing & unboxing which steals processor time and slows performance. Also compiler cannot detect type errors when you cast to and from Object class, instead will throw an runtime exception.

Q)What is an Interface?
A)Interface also known as contract, define common set of members that all classes that implement must provide.

Q) What is an Event?
A) An event is a message sent by an object to signal the occurance of an action.The one that raises the event is called Event Sender and the one that receives is called Event receiver.

Q) What is a Delegate?
A) A delegate is a class that holds reference to a method. A delegate class has a signature and it can hold reference to those method that matches with its signature. It is similar to typesafe pointer or callback.A delegate declaration is sufficient to declare a delegate class.
E.g.
public delegate void ButtonClicked(object sender, EventArgs args);


Note: TryParse, TryParseExact and TryCast are new to NET 2.0 previously you had to attemp parsing or conversion and catch the exception.


Conversion in Custom Type:
Implement System.IConvertible to enable conversion through System.Convert.


FileSystemWatcher Class:
FileSystemWatcher fsw = new FileSystemWatcher(@"c:\test_env");
fsw.NotifyFilter = NotifyFilters.LastWrite;
//WaitForChanged is a Synchronous method for watching a directory
//for changes and for returning a structure that contains all changes.
WaitForChangedResult wcr = fsw.WaitForChanged(WatcherChangeTypes.All);
Console.WriteLine(wcr.Name);

There are events like Created, Changed, Renamed, and Deleted.

File can be opened for writing using following.
File.Open(@"c:\test.txt", FileMode.Create, FileAccess.Write);


Stream class is the abstract base class from which all other stream classes derive from.
FileStream, MemoryStream, CryptoStream, NetworkStream, GZipStream

Different ways to open file for reading or writing using stream classes.
StreamReader sr = File.OpenText(@"c:\test.txt");
StreamWriter sw = File.AppendText(@"c:\test.txt");
FileStream fw = File.OpenWrite(@"c:\test.txt");
FileStream fr = File.OpenRead(@"c:\test.txt");

//reads a stream as a string and not series of bytes.
StreamReader srFile = new StreamReader(@"c:\test.txt");
StreamWriter swFile = new StreamWriter(@"c:\test.txt");



StreamReader is derived from Abstract class TextReader and StreamWriter is derived from Abstract class TextWriter.

StringReader and StringWriter class reads or writes to inmemory strings.

BinaryReader and BinaryWriter:

Creating a binary file:
byte[] bt = new byte[]{95,96,97,98,99};
FileStream fbinw = File.Create(@"c:\temp\test.bin");
fbinw.Write(bt, 0, bt.Length);
fbinw.Flush();
fbinw.Close();

//using binarywriter
BinaryWriter brw = new BinaryWriter(fbinw);
brw.Write(bt);



MemoryStream:
Use StreamReader to read from MemoryStream and StreamWriter to write to MemoryStream.


ArrayList:
Add, AddRange, Insert, InsertRange Methods. Indexers to set item at specific position by overwriting the object at that position.
Remove, RemoveAt, RemoveRange
Clear to empty the collection
Supports IEnumerable interface, which allows to use foreach construct.
Implements interface ICollection derived from IEnumberable and IList derivied from ICollection.


Sequential Lists: Queue and Stack
Queue : FIFO
Stack : LIFO

Dictionary:
Map key to a Value, create a lookup tables.
To iterate using foreach you should cast the object to DictionaryEntry i.e. foreach(DictionaryEntry de in hstLookup).
All dictionary class Supports IDictionary Interface.
IDictionary Interface doesn't allow the access to item by index like IList, but only allows the access by key.
IDictionary Interface has Contains, ContainsKey and ContainsValue

Hashtable
SortedList: To create a list of items that can be sorted by key.

Hashtable is very efficient but has an overhead which for fewer than 10 items can impede performance, very useful for large collection.
ListDictionary: Implemented as simple array of items under the hood, useful for small collection.
HybridDictionary: If you do not know the size, internally it changes the listdictionary to hashtable as the list grows.
OrderdDictionary


BitArray:
No add or remove method, constructor takes the size and initializes all the items with false.
Xor Method of bitarray takes another bitarray object and result is another bitarray which is Xor of two bitarray.


StringCollection is Like an ArrayList except that it accepts only string, passing anything else with cause compilation error.
StringDictionary is like hashtable except that both key and value must be string.


using System.Collections.Specialized;
Hashtable ht = CollectionsUtil.CreateCaseInsensitiveHashtable();
ht.Add("a", "Apple");
ht["A"] = "APPLE";
Console.WriteLine("Count:{0}", ht.Count); // returns one

NameValueCollection appears like a StringDictionary class, but the Add method behaves differently.
The behaviour of Add and indexer is different, indexer will overwrite the previous value if the key supplied is same.

NameValueCollection nv = new NameValueCollection();
nv.Add("A", "apple");
nv.Add("A", "america");

foreach (string st in nv.GetValues("A"))
{
Console.WriteLine("Value for A : {0}", st);
}
Value for A : apple
Value for A : america



Questions:

Q) What type of collections can be made from CollectionsUtil class?
A) Case insensitive Hashtable and Case insensitive SortedList.

Q) What type of values can be stored in StringDictionary?
A) Strings.

Wednesday, October 24, 2007

undocumented stored procedure for SQL Server

sp_tempdbspace // without parameter
sp_MStablespace 'xyztable' //with table name.

size returned in MB

.NET 3.5 Language Enhancements

net-3.5-language-enhancements

Tuesday, October 23, 2007

Screen scraping OR HTML scraping

Screen scraping is a technique in which a computer program extracts data from the display output of another program. The program doing the scraping is called a screen scraper.

http://en.wikipedia.org/wiki/Screen_scraping

Monday, October 22, 2007

Microsoft Acropolis

Microsoft Code Name "Acropolis" is a toolkit for creating modular, business-focused Windows client applications. "Acropolis" builds on the.NET Framework, and includes a run-time framework, design-time tools, and out-of-the-box functionality. "Acropolis" enables you to build reusable, connectable components and assemble them into working applications that are easy to change.

http://windowsclient.net/

http://windowsclient.net/Acropolis/

Thursday, October 18, 2007

IIS 7

In IIS 7.0, bindings can apply to any protocol. The Windows Process Activation Service (WAS) is the new service that makes it possible for IIS 7.0 to use additional protocols.

The Windows Communication Foundation (WCF) programming model is one such technology that can enable communication over the standard protocols of Transmission Control Protocol (TCP), Microsoft Message Queuing (MSMQ), and Named Pipes. This lets applications that use communication protocols take advantage of IIS features, such as process recycling, rapid fail protection, and configuration that were previously only available to HTTP-based applications.

IIS 7.0 supports HTTP and HTTPS by default, but you can use additional protocols.

ApplicationHost.config file (located at %windir%\system32\inetsrv\config \) after installing IIS on Windows Server codename "Longhorn."

New Things in VS2008

WYSIWYG designer provides:
  • Split View Support (the ability to have both HTML Source and design open simultaneously)
  • Extremely rich CSS support (CSS property window, CSS inheritance viewer, CSS preview, and CSS manager)
  • Dramatically improved view switching performance (moving from source->html design mode is now nearly instantaneous)
  • Support for control designers within source view (property builders, event wire-up and wizards now work in source view)
  • Richer ruler and layout support (better yet, values can be automatically stored in external CSS files)
  • Designer support for nested master pages
Code analysis and code metrics

Friday, October 12, 2007

dot net 3.0 CLR

.NET 2.0 and 3.0 share the same CLR, everything written in .NET 2.0 works in .NET 3.0
.NET 3.0 = .NET 2.0 + Windows Communication Foundation + Windows Presentation Foundation + Window CardSpace + Workflow Foundation

Thursday, October 11, 2007

RSA Alogrithm!!!

The name RSA is an acronym for the surnames of three inventors of this algorithm: Ron Rivest, Adi Shamir, and Len Adleman. They formed a company, RSA Security, which published several standard documents called Public Key Cryptography Standards (PKCS). These documents describe several aspects of cryptography.