Monday, November 15, 2010

Create e-Mail Massage

There are two steps to create a mail massage

1. Using MailMessage object and Creat email.
2. Send email Using SmtpClient object.

step 01 :
add System.Net.Mail namespace and System.Net Namespace to your project.

step 02 :
you need to Create MailMessage Object use following code.
MailMessage mail = new MailMessage();
//MailMessage constructor has 4 overload method
//1.string From/To
//MailMessage mail = new MailMessage("mgdhsandaruwan@yahoo.com","mgdhsandaruwan@gmail.com");

//2 MallAddress from/to
//3 string from/to/subject/body
//MailMessage mail = new MailMessage("mgdhsandaruwan@yahoo.com","mgdhsandaruwan@gmail.com","subject","body Details");

//4 no parameter

mail.From = new MailAddress("mgdhsandaruwan@yahoo.com", "Admin");
mail.To.Add(new MailAddress("mgdhsandaruwan@gmail.com","dinuka"));
// same way can be add many more address to mailaddress collection
//mail.Bcc.Add(); // same way to add bcc and cc
//mail.cc.add();
mail.Subject = " Mail subject";
mail.Body = "Mail body Content";

// mail.Attachments.Add(new Attachment("C:\windows..."));

if (chkAttach.Enabled)
{
Stream st = new FileStream(txtAttachFile.Text, FileMode.Open);
mail.Attachments.Add(new Attachment(st, "myFile.txt", MediaTypeNames.Application.Octet));
}

// see more details about MIME
follow these link


Create Html emails Massage

differences is that mail massage body is contain html tag .
ex :-
// Specify an HTML message body
mail.Body =
"My Message"This is an HTML message.";

mail.IsBodyHtml = true;

mail.header is also plain text. also email client ignore head section and client side scripting and do not download the image automatically web site.

There is special way to add image to the mail massage body without user downloaded image.

Embedded image to Mail massage body
First create html massage Using AlternateView and then add images using LinkedResource.
example :


mail.IsBodyHtml = true;


string bdy = "<"htmal"><"body">

" html body content "

<"br">
<"img src"=\"cid:Pic1\">"



AlternateView alv = AlternateView.CreateAlternateViewFromString(bdy, null, MediaTypeNames.Text.Html);
LinkedResource lnkR = new LinkedResource("dinuka.gif", MediaTypeNames.Image.Gif);
lnkR.ContentId = "Pic1";

// Add the alternate views instead of using MailMessage.Body

alv.LinkedResources.Add(lnkR);
mail.AlternateViews.Add(alv);


// Send the message
// Create SmtpCline object and pass mail sever
SmtpClient client = new SmtpClient("mail.yourmailServer.net");
// send mail can be done in two different way as asynchronous and synchronous
// as syncronus follow this
client.Send(mail);
//as asyncronus
//client.SendCompleted +=new SendCompletedEventHandler(client_SendCompleted);
client.SendAsync(ms,null);

// as synchronous way u need to get status of massage after sending it using sendCompleted event.




Tuesday, September 28, 2010

Object Serialization Using C# .net

Serialization is the Process of Converting an object into a linear Sequence of byte that can be Transferred or stored.
Desterilizing is the process of converting Serialized byte stream into a object.

Choosing serialization Format
There are 2 type of Serialization object .
  1. Binary Formatter -: this will located on System.Runtime.Serialization.Formatters.Binary Namespase. This is most efficient way to do that. But it can read only in the .net framework
  2. SoapFormatter -: this located on System.Runtime.Serialization.Formatters.Soap names pace. This is xml based formatter and most reliable way to serializable object that transmit across net work. This can be read non .net framework. This is successfully traversal across firewall than binary formatter. This is not support version compatibility of .net framework.
Object Serialization Step:

  • Create a stream object to hold serialized output.
  • Create a binary formatter object (its locate in System.Runtime.Serialaization.Formatter.Binary)
  • Call the BinaryFormatter or SoapFormatter Serialize Method to Serialized object and output result to the stream.

C# Code :


FileStream fs = new FileStream("SerializedData.Dat", FileMode.Create);

BinaryFormatter bf = new BinaryFormatter(); // binary formatter

//SoapFormatter bf = new SoapFormatter(); // for soap Formatter

bf.Serialize(fs, System.DateTime.Now);

fs.Close();


Object are DeSerialization Step:

  1. Create a stream object to read the serialized output
  2. Create a Binary Formatter object.
  3. Create a new object to store the Deserialized data
  4. Call the BinaryFormatter.Deserialize method to deserialize the object, and cast it to the correct type.
Ex :
FileStream fsRead = new FileStream("SerializedData.Dat", FileMode.Open); BinaryFormatter bfR = new BinaryFormatter();
//SoapFormatter bf = new SoapFormatter(); // for soap Formatter
DateTime data;
data =(DateTime) bfR.Deserialize(fsRead);
fsRead.Close();
Console.WriteLine(data);
Console.ReadKey();

Note :

The runtime proceeds through the deserialization process sequentially, starting at the beginning and working its way through to the end. The process gets complicated if an object in the serialized stream refers to another object. If an object references another object, the Formatter queries the ObjectManager to determine whether the referenced object has already been deserialized (a backward reference), or whether it has not yet been deserialized (a forward reference). If it is a backward reference, the Formatter immediately completes the reference. However, if it is a forward reference, the Formatter registers a fixup with the ObjectManager. A fixup is the process of finalizing an object reference after the referenced object has been deserialized. Once the referenced object is deserialized, ObjectManager completes the reference.

Create a Class that can be serialized

Class can be Serialized and De-serialized by adding Serializable attribute to the class. When your class is serializable run time its all the attribute will be serialized include private variable.

[Serializable]

class ShoppingCartItem

{

public int ProductID;

public string ProductName;

public decimal Quantity;

private decimal total;

public decimal price;

public ShoppingCartItem(int _productId, string _productName, decimal _Quantity, decimal _price)

{

ProductID = _productId;

ProductName = _productName;

Quantity = _Quantity;

price =_price;

total = Quantity * price;

}

}

Above class all the attribute will be serialized. In the total calculated in the dynamic. So that we no need to serialized total. Then we can reduced the storage, bandwith requirement when object are serialized. Use following way to non Serialized to attribute in the class.

[NonSerialized] public decimal total;

When deserialized total does not be initialized. So that we need to calculated total before deserialized. We can be used initialized non serialized object before deserialized use IDeserializationCallback interface and implement IDeserializationCallback.OnDeserialization method.

[Serializable]

class ShoppingCartItem : IDeserializationCallback

{

public int ProductID;

public string ProductName;

public decimal Quantity;

[NonSerialized] public decimal total;

public decimal price;

public ShoppingCartItem(int _productId, string _productName, decimal _Quantity, decimal _price)

{

ProductID = _productId;

ProductName = _productName;

Quantity = _Quantity;

price =_price;

total = Quantity * price;

}

void IDeserializationCallback.OnDeserialization(Object sender)

{

total = Quantity * price;

}

}

Monday, April 26, 2010

Value type

Value type are variables that create directly in the memory which is called as stack, in the run time create, update and remove them quick and less overhead.
Three general value types:-
1. Built-In type,
2. User Defined (Structs or Structure),
3. Enumeration

Those values are defined from system.value base type

Built-in type Value Type:-
> All built-in numeric types are value type,
Type size range use for
System.SBytes (SByte/sbyte) 1 -128 to 127 signed byte values
System.Byte (Byte/byte) 1 0-255 Unsigned bytes
System.Int16 (Short/short) 2
Sytem.Int32(Integer/int) 4 whole number and counter
System.UInt32 (UInteger/uint) 4 all positive number
System.INT64 (Long/long) 8 large whole number
System.Singal(Single/float) 4 Floating point number
Double/double 8 large floating point numbers
Decimal/decimal 16 financial and Scientific calculations ..

• runtime optimized 32-bit integer (int32/UInt32) and floating point operations double is most efficient because those are optimized by hardware.

> Non – numeric value types -:
Char/char 2 single Unicode character
Boolean/bool 4 True/false
System.IntPtr platform dependent Pointer to memory address
System.DateTime 8 Moment in time

> Value type has implicit constructor assign default constructor as null or 0
> C# are case sensitive
Nullable - this is new for .net 2.0
Declara value type as nullable
Nullable b = null or bool ? b = null

Use HasVale to check whether or not a vale has been set.
If (b.HasVale){ Console.writeLine(“b is vale {0}.” , b.value); }
else {Console.WriteLine(“b has no value”);}

User Defined Type (Struct)

Structure behave identically as a Class (class reference type struct value type)
Ex -: following example create a type of circle which given minimum and maximum number set by constructor
// ----------------------------
static void Main(string[] args)
{
cycle degree = new cycle(0, 359);
cycle Quater = new cycle(1, 4);

for (int i = 0; i < 8;i++ )
{
degree += 90;
Quater += 1;
Console.WriteLine("degree ={0}, and Quater ={1}", degree, Quater);
}
Console.Read();
}
struct cycle
{
int val;
int min;
int max;
public cycle(int minV, int maxV)
{
val = minV;
min = minV;
max = maxV;
}
public int Value
{
get {return val;}
set
{
if(value >max)
{
val = min;
}
else
{
if (value < min)
{
val = max;
}
else
{
val = value;
}
}
}
}
public override string ToString()
{
return Value.ToString();
}
public int toInteger()
{
return Value;
}
public static cycle operator +(cycle arg1, int arg2)
{
arg1.Value += arg2;
return arg1;
}
public static cycle operator -(cycle arg1, int arg2)
{
arg1.Value -= arg2;
return arg1;
}
}
//----------------------------


struct cycle
// can be chane struct to class it automaticaly be a reference type
{
// declar varible , defind method and operations
}
Above example cycle value type can be easily convert to reference type changing struct key word to class key word then cycle class be allocate in the heap rather than 12 byte on the stack,
 Structures are more efficient than class ,
 Following criteria should be meet for structures
o Logically represent single value;
o Has an instance size less than 16 byte;
o Will not be change after creation;
o Will not be cast to the reference type;

Create Enumeration

This is specific type symbol that have fixed value;
Ex: enum Titles : int {MR,MRS,MS,DR};
Titles t = Titles.DR;
 This is simplify coding and code readability

Monday, February 8, 2010

Input/Output (I/O)

File System Class

this file system class are inside the system.IO namespace. it use to manipulate and navigate file, directories and drivers. those class can be categorized in to two type of class file system info and utility.
C# code for get file system information
FileInfo fl = new FileInfo("C:/setup.log");
if (fl.Exists)
{
Console.WriteLine("file Name " + fl.FullName);
}

Enumerate file in directory
DirectoryInfo df = new DirectoryInfo("C:/");
foreach( FileInfo file in df.GetFiles())
{
Console.WriteLine("file Name " + file.FullName);
}
fleSystemwatcher class is used to monitoring file system in the specific path,and can be register event and monitor file changes information.

C# Framework Fundamentals

1. Common Reference Type
i) String and String Builder
Strings are immutable, which mean in the run time it will create the new string and abundant the old one,
ex :-
String s = new String();
s+="string1";
s+="string2";

string Builder class is mutable it will create at dynamicaly and we can defined its length what ever we want.
ex :- System.Text.StringBuilder sb = new System.Text.StringBuilder(30);
sb.Append("string1");
sb.Append("string2 ");
string s = sb.Tostring();


Generics
reduced runtime error,
improve runtime performance

example : OBject class without Genarics :-

Class Object (){
public Object t;
public object u;
public object(object t1, object u1){
t = t1;
u = u1; }
}
add two string to object class
Object obj = new Object("string1","string2");
console.writeline((string)obj.t + (string)obj.U);

the above way can be used using genarics
class gen
{
public T t;
public U u;
public gen(T t1, U u1){
t =t1;
u = U1;}
}

add two string to Gen class
Gen gen = new Gen("string1","string2");
console.writeline(gen.t + gen.U);
//above methode no need to object cast , also it does not occur runtime error, (int double cast error);

Introduction

Let's start to share C# knowledge