.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”);
}
How to compress Data with compression stream November 13, 2006
Posted by addisu in MCPD Web Developer, Software - .NET 2.0, Software - Certifications.add a comment
public void CompressFiles()
{
string inFileName;
string outFileName;
FileStream sourceFile = File.OpenRead(inFileName);
FileStream destFile = File.Create(outFileName);
DeflateStream compStream = new DeflateStream(destFile, CompressionMode.Compress);
//Or we can use the other compression stream as well
//GZipStream compStream = new GZipStream(destFile, CompressionMode.Compress);
int theByte = sourceFile.ReadByte();
while (theByte != -1)
{
compStream.WriteByte((Byte)theByte);
theByte = sourceFile.ReadByte();
}
}
what i learnt today, system types and collections… November 13, 2006
Posted by addisu in MCPD Web Developer.add a comment
Nothing here is really new except the “TypeForwardTo” attribute class.
Value types include:
All numeric data types
Boolean, Char, and Date
All structures, even if their members are reference types
Enumerations, since their underlying type is always Byte, Short, Integer, or Long
Reference types include:
String
All arrays, even if their elements are value types
Class types, such as Form
Delegates
Nullable Types (C# Programming Guide)
Nullable types are instances of the System.Nullable struct. A nullable type can represent the normal range of values for its underlying value type, plus an additional null value. For example, a Nullable<Int32>, pronounced “Nullable of Int32,” can be assigned any value from -2147483648 to 2147483647, or it can be assigned the null value. A Nullable<bool> can be assigned the values true or false, or null. The ability to assign null to numeric and Boolean types is particularly useful when dealing with databases and other data types containing elements that may not be assigned a value. For example, a Boolean field in a database can store the values true or false, or it may be undefined.
Attributes (C# Programming Guide)
Attributes provide a powerful method of associating declarative information with C# code (types, methods, properties, and so forth). Once associated with a program entity, the attribute can be queried at run time using a technique called Reflection.
Attributes exist in two forms: attributes that are defined in the Common Language Runtime’s base class library and custom attributes that you can create, to add extra information to your code. This information can later be retrieved programmatically.
[System.AttributeUsage(System.AttributeTargets.Class |
System.AttributeTargets.Struct)
]
public class Author : System.Attribute
{
private string name;
public double version;
public Author(string name)
{
this.name = name;
version = 1.0;
}
}
Generics (C# Programming Guide)
Generics are a new feature in version 2.0 of the C# language and the common language runtime (CLR). Generics introduce to the .NET Framework the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code. For example, by using a generic type parameter T you can write a single class that other client code can use without incurring the cost or risk of runtime casts or boxing operations, as shown here:
// Declare the generic class
public class GenericList<T>
{
void Add(T input) { }
}
class TestGenericList
{
private class ExampleClass { }
static void Main()
{
// Declare a list of type int
GenericList<int> list1 = new GenericList<int>();
// Declare a list of type string
GenericList<string> list2 = new GenericList<string>();
// Declare a list of type ExampleClass
GenericList<ExampleClass> list3 = new GenericList<ExampleClass>();
}
}
Generics Overview
- Use generic types to maximize code reuse, type safety, and performance.
- The most common use of generics is to create collection classes.
- The .NET Framework class library contains several new generic collection classes in the System.Collections.Generic namespace. These should be used whenever possible in place of classes such as ArrayList in the System.Collections namespace.
- You can create your own generic interfaces, classes, methods, events and delegates.
- Generic classes may be constrained to enable access to methods on particular data types.
- Information on the types used in a generic data type may be obtained at run-time by means of reflection.
One of the attributes that the Microsoft exam 70-356 is going to cover is the new attribute, TypeForwardedTo that was introduced in .NET 2.0. This attribute allows you to forward a type from one assembly to another assembly giving you the ability to rearrange your assemblies as needed without effecting any applications that reference your first assembly.
Type forwarding is a tool that you use to redirect a type at runtime, to look not in the expected assembly, but in a new assembly. So for instance, let’s say you have a an Assembly with the name Company with a class in it named Employee. You later decide that the employee class shouldn’t be in the Company assembly, but you would rather create a separate assembly named Corporation. You move your class file into the new assembly, however any program that was using the Company.Employee type will now fail because of this move. We don’t want to require all programs to change their code and recompile, so you forward the type to the new assembly.
Let’s provide some code to see this in action. First create the Company assembly and create a class called Employee. You can see this here:
namespace MyNamespace
{
public class Employee
{
public Employee()
{
Console.WriteLine(“in the Company assembly”);
}
}
}
Pretty straightforward, added a console.writeline stating where I am at so we can see what happens when I move the Employee class.
Next, create a test application and add a reference to the Company assembly you just created. Add these lines of code and run the application.
using System;
using MyNamespace;
namespace TestTypeForward
{
class Test
{
static void Main(string[] args)
{
Employee empl = new Employee();
}
}
}
OUTPUT:
in the Company assembly
Again, nothing new here and our output is expected. Now, we want to move the Employee class to a new assembly, the corporate assembly. Create the new assembly and add a reference in the Company assembly to the new Corporate assembly. Remove the Employee class in the old Company assembly and add it to the Corporate assembly, changing the WriteLine so we know where we are at.
using System;
namespace MyNamespace
{
public class Employee
{
public Employee()
{
Console.WriteLine(“in the Corporate assembly”);
}
}
}
Compile both assemblies and then try to run the Test app again. You get an error “Cannot load type” because the reference to the Company assembly, MyNamespace.Employee is gone. To get around this, add this line to the top of your Company class:
[assembly: TypeForwardedTo( typeof( Employee ) )]
Now compile the Company assembly again, which will compile the Corporate assembly and run test again without compiling it. You should see the output changed to “in the Corporate assembly” even though our references to the Company assembly has no Employee class.
Music in Ethiopia… November 10, 2006
Posted by addisu in Music - General.2 comments
I’ve been to a couple of Jazz shows in 2000 and 2001. Coffee house was the popular host for those shows. There were a couple guys who were pioneers for this new thing in Ethiopia. Amoung these are Girum Mezmur, Yohannes (Jhonny) Tona, Elias Melka and so on. I was previlaged to see one of the shows that Henok Temesgen was guest. But after five years this practice is even more escalated to be hosted in Sheraton hotel from that small restorant. I recently saw an article that people are getting more aware of this kind of music.

