System.Collections namespace in a .NET Framework December 4, 2006
Posted by addisu in MCPD Web Developer, Software - .NET 2.0, Software - .NET General, Software - C#, Software - Certifications.add a comment
Manage a group of associated data in a .NET Framework application by using collections. (Refer System.Collections namespace)
- ArrayList class
- Collection interfaces
- Iterators
- Hashtable class
- CollectionBase class and ReadOnlyCollectionBase class
- DictionaryBase class and DictionaryEntry class
- Comparer class
- Queue class
- StoredList class
- BitArray class
- Stack class
Summary
The Array List is a dynamically allocated collection of objects. It will automatically increase its capacity as objects are added. Since it holds objects, items inserted into it are boxed, and must be cast back to their specific type.
The collection interfaces include IList, ICollection, and IDictionary.
Iterators are new to .Net 2.0. They enable you to support foreach iteration without implementing the entire IEnumerable interface. The method must return IEnumerable or IEnumerator. It uses the keyword yield return to return each element. You can implement the GetEnumerator Method in the IEnumerable interface to implement the default iterator for the class, or just expose a named method of Type IEnumerable and even accept parameters. The Following example is from msdn.
public class DaysOfTheWeek : System.Collections.IEnumerable
{
string[] m_Days = { "Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat" };
public System.Collections.IEnumerator GetEnumerator()
{
for (int i = 0; i < m_Days.Length; i++)
{
yield return m_Days[i];
}
}
}
class TestDaysOfTheWeek
{
static void Main()
{
// Create an instance of the collection class
DaysOfTheWeek week = new DaysOfTheWeek();
// Iterate with foreach
foreach (string day in week)
{
System.Console.Write(day + " ");
}
}
}
The Hashtable Class is a Collection that uses key value pairs stored in a Dictionary Entry object. They keys are hashed when items are entered. See the Resources if you are unfamiliar with this object.
The CollectionBase class is the abstract base class for strongly typed collections. By Inheriting from this class you can expose the basic collection operators (add, insert, remove, index, this, etc) using Strong Types to create a collection that wraps the base List object to expose strongly typed functionality. See the resources for details. The ReadOnlyCollectionBase is a readonly version of this abstract class that can access members through its innerlist property instead of List property.
The DictionaryBase class is the abstract base class for strongly typed collections of key value pairs. Each entry is stored in a DictionaryEntry object.
The Comparer Class is the default implementation of the IComparer Interface. It is used to compare strings and accepts a CultureInfo object in its constructor. It can be used as a parameter to Array.Sort to sort a collection.
The Queue class is used to represent a first in first out collection. Use the Enqueue method to add items to the collection.
The SortedList class is used to maintain a HashTable like collection of name value pairs, but sort the collection based on an IComparable implementation of a class that compares the keys.
The BitArray Class is used to hold a compact array of bits, represented as Boolean values.
The Stack class is used to represent a last in first out collection. Use the push method to add items to the collection and pop to remove and return the last item added.
Other Resources & Links:
ArrayList Class
http://msdn2.microsoft.com/en-us/library/7×4b0a97(en-US,VS.80).aspx
Getting to know .Net Collections
http://builder.com.com/5100-6373-1045372.html
Iterators (C# Programming Guide)
http://msdn2.microsoft.com/en-us/library/dscyy5s0.aspx
HashTable Class
http://msdn2.microsoft.com/en-us/library/system.collections.hashtable.aspx
CollectionBase Class
http://msdn2.microsoft.com/en-us/library/7a03ybbb(en-US,VS.80).aspx
ReadOnlyCollectionBase Class
http://msdn2.microsoft.com/en-us/library/system.collections.readonlycollectionbase.aspx
DictionaryBase Class
http://msdn2.microsoft.com/en-us/library/sa198xea(en-US,VS.80).aspx
DictionaryEntry Structure
http://msdn2.microsoft.com/en-us/library/9kth4sbk(en-US,VS.80).aspx
Comparer Class
http://msdn2.microsoft.com/en-us/library/system.collections.comparer.aspx
Queue Class
http://msdn2.microsoft.com/en-us/library/055sfc3z(en-US,VS.80).aspx
SortedList Class
http://msdn2.microsoft.com/en-us/library/w1xa3kh1(en-US,VS.80).aspx
BitArray Class
http://msdn2.microsoft.com/en-us/library/w1xa3kh1(en-US,VS.80).aspx
Stack Class
http://msdn2.microsoft.com/en-us/library/c8hws30f(en-US,VS.80).aspx
.NET Serialization November 15, 2006
Posted by addisu in MCPD Web Developer, Software - .NET 2.0, Software - .NET General, Software - C#, Software - Certifications.1 comment so far
Why Serialization?
- To store the content of the object to file (to save the state of the object)
- To send an object to another process
- To transmit the object across network
Serializing is the process of converting an object into a linear sequence of bytes that can be stored or transferred.
Deserializing is the process of converting previously serialized sequence bytes into an object.
How to serialize an object
- Create a stream object to hold the serialize output
- create a BinaryFormatter object
- Call the BinaryFormatter.Serialize method to serialize the object, and output the result to the stream
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;
public void serializeToFile()
{
string data = “This must be stored in the file”
//Create file to save the data to
FileStream fs = new FileStream(“SerializedString.data”, FileMode.Create);
//Create a BinaryFormatter object to
//perform the serialization
BinaryFormatter bf = new BinaryFormatter();
//Use the BinaryFormatter object to
//serialize the data to the File
bf.Serialize(fs, data);
//Close the file
fs.Close();
}
How to deserialize
- Create a stream object to read the serialized output
- Create a BinaryFormatter object
- Create a new object to store the deserialized data
- Call the BinaryFormatter.Deserialize method to deserialize the object, and cast it to the correct type.
using System.Runtime.Serialization
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;
public void deserializeFromFile()
{
//Open file to read the data from
FileStream fs = new FileStream(“Serializedstring.data”, FileMode.Open);
//Create a BinaryFormatter object
//to perform the deserialization
BinaryFormatter bf = new BinaryFormatter();
//Create the object to store the
//deserialized data
string data = “”;
//Use the Binaryformatter object to
//deserialize the data from the File
data = (string)bf.Deserialize(fs);
//Close the file
fs.Close();
//Display the deserialized string
Console.WriteLine(data);
}
Create a Class that can be serialized
[Serializable]
class ShopingCartItem : IDeserializationCallback
{
public int productId;
public decimal price;
public int quantity;
[NonSerialized] public decimal total;
[OptionalField] public Boolean taxable;
public ShopingCartItem(int _prodId, decimal _price, int _quantity)
{
productId = _prodId;
price = _price;
quantity = _quantity;
total = price * quantity;
}
#region IDeserializationCallback Members
public void OnDeserialization(object sender)
{
total = price * quantity;
}
#endregion
}
Choosing serialization
- BinaryFormatter: Located in the System.Runtime.Serialization.Formatters.Binary namespace, this is the most efficient way to serialize objects that will be read by only .NET Framework-based applications.
- SoapFormatter: Located in the System.Runtime.Serialization.Formatters.Soap namespace, this XML-based formatter is the most reliable way to serialize objects that will be transmitted across a network or read by non- .NET Framework applications. SoapFormatter is more likely to successfully traverse firewalls than BinaryFormatters. Note: you have to manually add the reference the Soap dll unlike Binary.
XML Serialization
- It only serializes the public members.
- We can control the serialization using XML attributes if we want to alter the default naming of XML serialization, other default behaviors
Finally – Types of serialization
- Binary Serialization
- Soap Serialization
- XML Serialization
- Custom Serialization
Working with isolated storage November 14, 2006
Posted by addisu in MCPD Web Developer, Software - .NET 2.0, Software - .NET General, Software - C#, Software - Certifications.1 comment so far
The need for isolated storage comes because we are running application in a limited privilege environment. Running the application in a limited privilege has many benefits such as protecting users from predators who are foisting users with viruses and Spy Ware. But what can we do when we want to persist the state or other data with out using the database or cache? With limited privilege we don’t have a full access to the hard drive.
By using isolated storage to save our data, we will have access to a safe place to store information without needing to restore to having users grant access to specific files or folders in the file system. Therefore the main benefit of using isolated storage is that your application will run regardless of whether it is running under partial, limited, or full-trust.
The IsolatedStorageFile Class
The IsolatedStorageFile Class provides the basic functionality to create files and folders in isolated storage.
Static members of the IsolatedStorageFile Class
- GetMachineStoreForApplication: Obtains machine-scoped isolated storage corresponding to the calling code’s application identity.
- GetMachineStoreForAssembly: Obtains machine-scoped isolated storage corresponding to the calling code’s assembly identity.
- GetMachineStoreForDomain: Obtains machine-scoped isolated storage corresponding to the application domain identity and the assembly identity.
- GetStore: Overloaded. Obtains isolated storage corresponding to the given application domain and assembly evidence objects and isolated storage scope.
- GetUserStoreForApplication: Obtains user-scoped isolated storage corresponding to the calling code’s application identity.
- GetUserStoreForAssembly: Obtains user-scoped isolated storage corresponding to the calling code’s assembly identity.
- GetUserStoreForDomain: Obtains user-scoped isolated storage corresponding to the application domain identity and assembly identity.
Public Properties of the IsolatedStorageFile Class
- ApplicationIdentity: Gets an application identity that scopes isolated storage.
- AssemblyIdentity: Gets an assembly identity used to scope isolated storage.
- CurrentSize: Gets the current size of the isolated storage.
- DomainIdentity: Gets a domain identity that scopes isolated storage.
- MaximumSize: Gets a value representing the maximum amount of space available for isolated storage within the limits established by the quota.
Public Methods of the IsolatedStorageFile Class
- CreateDirectory: Creates a directory in the isolated storage scope.
- DeleteDirectory: Deletes a directory in the isolated storage scope.
- DeleteFile: Deletes a file in the isolated storage scope.
- GetDirectoryNames: Enumerates directories in an isolated storage scope that match a given pattern.
- GetFileNames: Enumerates files in isolated storage scope that match a given pattern.
How to create a store
Before you can save data in isolated storage, you must determine how to scope the data you want in your store.
Assembly/Machine: specific to the calling assembly and the local machine. This is useful for creating application-level data.
IsolatedStorageFile machineStorage = IsolatedStorageFile.GetMachineStoreForAssembly();
Assembly/User: specific to the calling assembly and the current user. This method is useful for creating user-level data.
IsolatedStorageFile userStorage = IsolatedStorageFile.GetUserStoreForAssembly();
IsolatedStorageFileStream Class
The IsolatedStorageFileStream Class encapsulates a stream that is used to create files in isolated storage. This class is derived from the FileStream class, so its usage after creation is almost identical to the FileStream class.
Reading and writing Data to Isolated Storage
It is pretty much similar to the normal file system after creating the Stream reader or writer.
IsolatedStorageFile userStorage = IsolatedStorageFile.GetUserStoreForAssembly();
IsolatedStorageFileStream userStream = new IsolatedStorageFileStream(“setting.set”, FileMode.Create,userStorage);
StreamWriter userWriter = new StreamWriter(userStream);
userWriter.WriteLine(“Sample User Setting”);
userWriter.Close();
Reading…
Preparing to read the data back is as simple as creating a stream object by opening the file
IsolatedStorageFileStream userStream = new IsolatedStorageFileStream(“setting.set”, FileMode.Open, userStorage);
To check if the file exist in the storage…
IsolatedStorageFile userStorage = IsolatedStorageFile.GetUserStoreForAssembly();
IsolatedStorageFileStream userStream = new IsolatedStorageFileStream(“setting.set”, FileMode.Open, userStorage);
string[] files = userStorage.GetFileNames(“*.set”);
if (files.Length == 0)
{
Console.WriteLine(“There is no User file in the specified storage”);
}
else
{
//…
}
Creating stream with Directory…
IsolatedStorageFile userStorage = IsolatedStorageFile.GetUserStoreForAssembly();
IsolatedStorageFileStream userStreamWithDir = new IsolatedStorageFileStream(@”SomeDir\setting.set”, FileMode.Create, userStorage);
//OR we can use this but making sure if the directory name
//already exists
string[] directories = userStorage.GetDirectoryNames(“SomeDir”);
if (directories == 0)
{
userStorage.CreateDirectory(“SomeDir”);
}

