Wednesday, January 14, 2009

Serialization and deserialization of object

Public Function add() As TestClass
Dim obj As TestClass
obj = New TestClass

//Test is a propert of class TestClass

//Populate the object
obj.Test = "Hello"
Dim serializer As New XmlSerializer(GetType(TestClass))
Dim st As String = TestClassXml(obj)
Dim fileExists As Boolean
fileExists = My.Computer.FileSystem.FileExists("C:\Test.xml")
If fileExists Then
My.Computer.FileSystem.DeleteFile("C:\Test.xml", FileIO.UIOption.OnlyErrorDialogs, FileIO.RecycleOption.DeletePermanently)
End If
My.Computer.FileSystem.WriteAllText("C:\Test.xml", st, True)
Dim fileContents As String
fileContents = My.Computer.FileSystem.ReadAllText("C:\Test.xml")

stream = New IO.StringReader(fileContents)
' read xml data
reader = New XmlTextReader(stream)
' create reader
Return DirectCast(serializer.Deserialize(reader), TestClass)
End Function


------------------------------------
Function to convert object to xml

-------------------------------------

Public Function TestClassXml(ByVal obj As TestClass) As String
Dim stream As IO.MemoryStream = Nothing
Dim writer As IO.TextWriter = Nothing
stream = New IO.MemoryStream()
' read xml in memory
writer = New IO.StreamWriter(stream, Encoding.UTF8)
' get serialise object
Dim serializer As New XmlSerializer(GetType(TestClass))
serializer.Serialize(writer, obj)
' read object
Dim count As Integer = CInt(stream.Length)
' saves object in memory stream
Dim arr As Byte() = New Byte(count - 1) {}
stream.Seek(0, IO.SeekOrigin.Begin)
' copy stream contents in byte array
stream.Read(arr, 0, count)
Dim utf As New UTF8Encoding
' convert byte array to string
Return utf.GetString(arr).Trim()
End Function


Monday, December 1, 2008

Reflection to get classes,methods,properties of dll(vb.net)

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim asm As Assembly = Assembly.LoadFrom("yourdllpath.dll")
Dim typ() As Type = asm.GetTypes()
Dim dt As DataTable = New DataTable("Class Information")
Dim className As DataColumn = New DataColumn("Class")
Dim methodName As DataColumn = New DataColumn("MethodName")
dt.Columns.Add(className)
dt.Columns.Add(MethodName)
className.AllowDBNull = True
methodName.AllowDBNull = True
For Each cls As Type In typ
Dim fieldInfo() As FieldInfo = cls.GetFields()
For Each fieldInf As FieldInfo In fieldInfo
DropDownList1.Items.Add(fieldInf.Name)
Next
Dim memInf() As MethodInfo = cls.GetMethods()
For Each mem As MethodInfo In memInf
Dim dr As DataRow = dt.NewRow()
dr(0) = cls.Name.ToString
dr(1) = mem.Name.ToString
dt.Rows.Add(dr)
Dim paramInfo() As ParameterInfo = mem.GetParameters()
For Each param As ParameterInfo In paramInfo
DropDownList1.Items.Add(param.Name)
Next
Next
Dim memInfor() As PropertyInfo = cls.GetProperties()
For Each mem As PropertyInfo In memInfor

DropDownList2.Items.Add(mem.Name)

Next

Next
GridView1.DataSource = dt
GridView1.DataBind()

End Sub
End Class

Tuesday, November 25, 2008

Create Custom Attribute in .net

/* class to create custom attribute .The custom attribute class must be inherited from Attribute which is an abstract class
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
[AttributeUsage(AttributeTargets.All,Inherited=true,AllowMultiple=true)]
class AuthorAttribute:Attribute
{
private string authorFirstName = string.Empty;
private string authorLasttName = string.Empty;
private string authorCreationDate = string.Empty;
public AuthorAttribute(string firstName, string lastName)
{
this.authorFirstName = firstName;
this.authorLasttName = lastName;
}
public AuthorAttribute(string firstName, string lastName,string creationDate)
{
this.authorFirstName = firstName;
this.authorLasttName = lastName;
this.authorCreationDate = creationDate;
}
public string AuthorName
{
get
{
return (this.authorFirstName + " " + authorLasttName);
}
}

public string CreationDate
{
get
{
return (this.authorCreationDate);
}
}

}
}

//Implement Custom Attribute

using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
[Author("Nitendra Singh","raghuwanshi","25/11/2008")]
class Program
{
static void Main(string[] args)
{
Program pr = new Program();
DisplayAttributes(pr.GetType());
Console.ReadLine();
}
static void DisplayAttributes(Type type)
{
AuthorAttribute author = null;
foreach (object objAttribute in type.GetCustomAttributes(false))
{
author = objAttribute as AuthorAttribute;
if (author == null)
continue;
Console.WriteLine("Name :" + author.AuthorName);
Console.WriteLine("Date :" + author.CreationDate);
}
}
}
}

Monday, November 24, 2008

Sorting Array of Strings Alphabetically without using inbuilt dotnet methods

//Main function to print sorted array
static void Main(string[] args)
{
Program pr = new Program();

//Array of element.
string[] array = { "nitendra","abhijit","nsr","manish","rahul","zaheer","abhishek","msdfDS","xyz","123"};
pr.sort(array);
for (int i = 0; i <= array.Length-1 ; i++)
{
Console.WriteLine(array[i]);
}
}

//Function to compare two strings

public int Compare(string str1, String str2)
{
int len1, len2, i;
len1 = str1.Length;
len2 = str1.Length;
for (i = 0; i < len1 && i < len2; i++)
{
if (str1[i] < str2[i])
return -1;
else if (str1[i] > str2[i])
return 1;
}
return 0;
}

//Function to sort array of strings

public void sort(String[] array)
{
int i, j;
String temp;
int sortTheStrings = array.Length-1;
for (i = 0; i < sortTheStrings; ++i)
for (j = 0; j < sortTheStrings; ++j)
if (Compare(array[j],(array[j + 1])) > 0)
{
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}