Friday, January 16, 2009

AppDomain : Listing Assemblies within the Current AppDomain and Creating an new AppDomain (Code Snippet)

using System.Reflection;

private void Form1_Load(object sender, EventArgs e)
{
AppDomain dom = AppDomain.CurrentDomain;

Assembly[] loadedAssembly = dom.GetAssemblies();
foreach (Assembly a in loadedAssembly)
listBox1.Items.Add(a.GetName().Name );
}

private void btnCreateAppDomain_Click(object sender, EventArgs e)
{
AppDomain aDo = AppDomain.CreateDomain("Shalvin");

Assembly[] loadedAssembly = aDo.GetAssemblies();
foreach (Assembly a in loadedAssembly)
listBox2.Items.Add(a.GetName().Name);
}










Related Blogs
Reflection in .Net
.Net Intermediate Language

.Net Remoting Walkthrough

Remoting is the process of two pieces of software communicating across application domains.
Start a Class Library call it say ShalvinObject. Create a class that inherits from MarshalByRefObject.

namespace ShalvinObject
{
class RemoteObject : MarshalByRefObject
{
public int Mul(int i, int j)
{
return i * j;
}
}

Now we are going to host the service. This can be done with Console, Windows Forms or Web Service.
Letsuse Windows Forms.
Add to a reference to the previously created dll, ie. ShalvinObject.dll and System.Runtime.Remoting.


using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;

private void Form1_Load(object sender, EventArgs e)
{
TcpChannel c = new TcpChannel(900);
ChannelServices.RegisterChannel(c);
RemotingConfiguration.RegisterWellKnownServiceType(typeof(ShalvinObject.RemoteObject), "Shalvin", WellKnownObjectMode.Singleton);
}

Now for testing the service lets create another Windows Application. Here too set references to ShalvinObject.dll and System.Runtime.Remoting.


using ShalvinObject;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;


private void Form1_Load(object sender, EventArgs e)
{
TcpChannel c = new TcpChannel();
ChannelServices.RegisterChannel(c);
object obj = Activator.GetObject(typeof(ShalvinObject.RemoteObject), "tcp://localhost:900/Shalvin");
RemoteObject ro = (RemoteObject)obj;
int intRes = ro.Mul(56, 45);
MessageBox.Show(intRes.ToString());
}


Related Blog
Currency Conversion Web Service with Asp .Net

Creating and Consuming Class Library in C#, Object Initializer

Monday, January 12, 2009

Hashtable and DictionaryEntry

HashTable Class of System.Collections namespace represents a collection of key/value pairs that are organized based on the hash code of the key.


using System.Collections;

Hashtable ht = new Hashtable();
private void Form1_Load(object sender, EventArgs e)
{
	ht.Add("Am", "Ambily");
	ht.Add("Di", "Divya");
	foreach (DictionaryEntry de in ht)
	{
		listBox1.Items.Add(de.Key);
		listBox2.Items.Add(de.Value);
	}
}

private void button1_Click(object sender, EventArgs e)
{
	ht.Add(textBox1.Text, textBox2.Text);
	ShowHashTable();
}

private void ShowHashTable()
{
	listBox1.Items.Clear();
	listBox2.Items.Clear();
	foreach (DictionaryEntry de in ht)
	{
		listBox1.Items.Add(de.Key);
		listBox2.Items.Add(de.Value);
	}
}

VB .Net







Dim ht As New Hashtable
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
	ht.Add("Am", "Ambily")
	ht.Add("Di", "Divya")
	ShowHT()
End Sub
Private Sub ShowHT()
	ListBox1.Items.Clear()
	ListBox2.Items.Clear()
	For Each de As DictionaryEntry In ht
		ListBox1.Items.Add(de.Key)
		ListBox2.Items.Add(de.Value)
	Next
End Sub
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
	ht.Add(txtKey.Text, txtValue.Text)
	ShowHT()
End Sub
Related Blog ReadOnlyCollectionBase Class Generics and Collection Initializer in .Net

Thursday, January 8, 2009

ReadOnlyCollectionBase Class

Provides the abstract base class for a strongly typed non-generic read-only collection.This class makes the underlying collection available through the InnerList property.
Since ReadOnlyCollectionBase implements IEnumerable Interface you can iterate through the collection.

//class
using System.Collections;
class ShalvinBlogs : ReadOnlyCollectionBase

{
public void Add(String value)
{
InnerList.Add(value);
}
public string this[int index]

{
get
{
return (string)InnerList[index];
}
}
}

//Forms
ShalvinBlogs sb = new ShalvinBlogs();

private void Form1_Load(object sender, EventArgs e)
{
sb.Add("Shalvinpd.blogspot.com");
sb.Add("DotNetShalvin.blogspot.com");
foreach (string str in sb)
listBox1.Items.Add(str);
}
private void button1_Click(object sender, EventArgs e)

{
textBox1.Text = sb[0];
}

Related Blogs
Generics and Collection Initializer in .Net
Hashtable and DictionaryEntry

Monday, December 15, 2008

ServiceController Class for Managing a service

You can use the ServiceController class (System.ServiceProcess) to connect to and control the behavior of existing services.

Enumerating services

using System.ServiceProcess;

private void Form1_Load(object sender, EventArgs e)
{
foreach (ServiceController s in ServiceController.GetServices())
listBox1.Items.Add(s.DisplayName );
}

You can then use the class to start, stop, and otherwise manipulate the service.

Here I am using ServiceController class to start and stop Sql Server 2000 Service.

using System.ServiceProcess;
ServiceController sc = new ServiceController();
private void Form1_Load(object sender, EventArgs e)
{
sc.ServiceName = "MSSqlServer";
}

private void btnStart_Click(object sender, EventArgs e)
{
if (sc.Status == ServiceControllerStatus.Stopped sc.Status == ServiceControllerStatus.Paused )
{
sc.Start();
MessageBox.Show("Service started");
}
else
MessageBox.Show("Service already started");
}

private void btnStop_Click(object sender, EventArgs e)
{
if (sc.Status == ServiceControllerStatus.Running )
{
sc.Stop();
MessageBox.Show("Service stopped");
}
else
MessageBox.Show("Service alredy in stopped state");
}
}

Friday, December 12, 2008

Isolated Storage (Code Snippets)

using System.IO;
using System.IO.IsolatedStorage;

private void button1_Click(object sender, EventArgs e)
{
this.Text = textBox1.Text;
IsolatedStorageFile f = IsolatedStorageFile.GetMachineStoreForDomain();
IsolatedStorageFileStream i = new IsolatedStorageFileStream("co.col", System.IO.FileMode.Create, f);
StreamWriter sw = new StreamWriter(i);
sw.Write(this.Text);
sw.Flush();
sw.Close();
}


private void Form1_Load(object sender, EventArgs e)
{
IsolatedStorageFile f1 = IsolatedStorageFile.GetMachineStoreForDomain();
IsolatedStorageFileStream i1 = new IsolatedStorageFileStream("co.col", FileMode.Open, f1);
StreamReader sr = new StreamReader(i1);
this.Text = sr.ReadToEnd();
sr.Close();
}

Courtesy : Saji P Babu, IndiaOptions, Kochi.

Related Blog
System.IO Namespace in .Net

Wednesday, December 10, 2008

Linq to Xml (Code Snippets)

Linq to Xml enables you to query an Xml document using the familiar LINQ syntax. Linq to Xml features and found within System.Xml.Linq namespace.
System.Xml.Linq introduces a series of objects such as XDocument, XElement and XAttributes which makes creating XML document a breeze.

XAttribute
private void btnXElement_Click(object sender, RoutedEventArgs e)
{
XElement xe = new XElement(new XElement("Shalvin",
new XElement("Students",
new XElement("Name", "Shalvin"))));
textBox1.Text = xe.ToString();

}


XElement


using System.Xml.Linq;

private void Form1_Load(object sender, EventArgs e)
{
XElement xml = new XElement("contacts",
new XElement("contact",
new XAttribute("contactId", "2"),
new XElement("firstName", "Shalvin"),
new XElement("lastName", "PD")
),
new XElement("contact",
new XAttribute("contactId", "3"),
new XElement("firstName", "Praseed"),
new XElement("lastName", "Pai")
)
);
textBox1.Text = xml.ToString();
}


XDocument

using System.Xml.Linq;

protected void Page_Load(object sender, EventArgs e)
{
XDocument xd = new XDocument();
XElement contacts =
new XElement("contacts",
new XElement("contact",
new XElement("name", "Shalvin"),
new XElement("Location", "Kochi")
),
new XElement("contact",
new XElement("name", "Viju"),
new XElement("Location", "Trichur")
)
);
xd.Add(contacts);
xd.Save("c:\\Shalvin.xml");
System.Diagnostics.Process.Start("iexplore", "c:\\Shalvin.xml");
}

Output

<?xml version="1.0" encoding="utf-8"?>
<contacts>
<contact contactId="2">
<firstName>Shalvin</firstName>
<lastName>P D</lastName>
</contact>
<contact contactId="3">
<firstName>Praseed</firstName>
<lastName>Pai</lastName>
</contact>
</contacts>

XDocument Parse

private void button3_Click(object sender, RoutedEventArgs e)
{
XDocument xd = XDocument.Parse(@"<contacts>
<contact contactId='2'>
<firstName>Shalvin</firstName>
<lastName>P D</lastName>
</contact>
<contact contactId='3'>
<firstName>Praseed</firstName>
<lastName>Pai</lastName>
</contact>
</contacts>");

textBox1.Text = xd.ToString();

}


Querying an Xml Document














using System.Xml.Linq;
private void Form1_Load(object sender, EventArgs e){
XDocument xmlFile = XDocument.Load("c:\\Shalvin.xml");
var query = from c in xmlFile.Elements("contacts").Elements("contact").Elements("name")

select c;
foreach (XElement nam in query)

{
listBox1.Items.Add(nam);
}

}

Related Blogs
Linq to Objects
Linq to Sql
.Net Working with Xml

Monday, December 8, 2008

Linq to Objects

LINQ (Language Integrated Query) is a Microsoft .NET framework component that adds native data querying capabilities to C# and Visual Basic .NET (VB.NET) programming languages.
It allows developers to write database-like queries against various data sources including in-memory objects, SQL databases, and XML data sources.
LINQ enables developers to perform queries in a more concise, readable and expressive way, compared to traditional loops and conditional statements.
This blog assumes that you are know Type Inference in C#, Generics and Collection Initializer.

private void Form1_Load(object sender, EventArgs e)
{
List<string> interests = new List<string>{"Music", "Singing", "Swimming"};
var result = from w in interests
where w.Contains("ing")
select w;

foreach (string s in result)
listBox1.Items.Add(s);
}


Lambda
protected void btnLambda_Click(object sender, EventArgs e)
{
   List<string> interests = new List<string>{"Music", "Singing", "Swimming"};
   var result = interests.Where(p => p.Contains("ing"));
        
   foreach (string s in result)
     ListBox1.Items.Add(s);
}


The Linq query retrives all values form Generic List that ends with "ing". You can use Linq with any objects that implements IEnumerable or Generic IEnumerable interface.

StartsWith
private void btnStartsWith_Click(object sender, RoutedEventArgs e)
{
listBox1.Items.Clear();
var ms = from p in interests
            where p.StartsWith("M")
            select p;
foreach (string s in ms)
    listBox1.Items.Add(s);
}

EndsWith
private void btnEndWith_Click(object sender, RoutedEventArgs e)
{
listBox1.Items.Clear();
var ms = from p in interests
            where p.EndsWith("g")
            select p;
foreach (string s in ms)
    listBox1.Items.Add(s);
}


Equals
private void btnEquals_Click(object sender, RoutedEventArgs e)
{
listBox1.Items.Clear();
var ms = from p in interests
            where p.Equals("Music")
            select p;
foreach (string s in ms)
    listBox1.Items.Add(s);
}


First
First can be used to extract only the first item in the collection.
private void btnFirst_Click(object sender, RoutedEventArgs e)
{
listBox1.Items.Clear();
var ms = (from p in interests
            select p).First();
listBox1.Items.Add(ms);
}

Last
private void btnLast_Click(object sender, RoutedEventArgs e)
{
listBox1.Items.Clear();
var ms = (from p in interests
            select p).Last();
listBox1.Items.Add(ms);
}

Count
Using the Count operator I am taking a counts of items inside the Generic List. I will get a value 3.

private void btnCount_Click(object sender, RoutedEventArgs e)
{
listBox1.Items.Clear();
var ms = (from p in interests
            select p).Count();
listBox1.Items.Add(ms);
}

Count of EndsWith
Here I am taking a count of items ending with "ing". I will get an output of 2 ie. the count of "Swimming" and "Singing".

private void btnCountEndWithIng_Click(object sender, RoutedEventArgs e)
{
listBox1.Items.Clear();
var ms = (from p in interests
          where p.EndsWith("ing")  
          select p).Count();
listBox1.Items.Add(ms);
}

Count Equals

private void btnCountEquals_Click(object sender, RoutedEventArgs e)
{
listBox1.Items.Clear();
var ms = (from p in interests
where p.Equals("Music")
          select p).Count();
listBox1.Items.Add(ms);
}

Linq and Generic List of Integer
Having seen working with Generic List of string let's turn out attention to Generic List of Inteters. 


List<int> gliMarks = new List<int> { 98, 56, 88, 79, 96 };

GreaterThan Operator

private void btnShowGreaterThan90_Click(object sender, RoutedEventArgs e)
{
listBox1.Items.Clear();
var G90 = from p in gliMarks
    where p > 90
    select p;
listBox1.ItemsSource = G90;
}


Sum

private void btnSum_Click(object sender, RoutedEventArgs e)
{
    listBox1.Items.Clear();
           
    var vSum = (from p in gliMarks
                select p).Sum();
    listBox1.Items.Add(vSum);
}



Average

private void btnAverage_Click(object sender, RoutedEventArgs e)
{
    listBox1.Items.Clear();
    var Avg = (from p in gliMarks
                    select p).Average();
    listBox1.Items.Add(Avg);
}

Max

private void btnMaximum_Click(object sender, RoutedEventArgs e)
{
listBox1.Items.Clear();
var Maxi = (from p in gliMarks
            select p).Max();
listBox1.Items.Add(Maxi);
}

Or

private void btnSOr_Click(object sender, RoutedEventArgs e)
{
listBox1.Items.Clear();
var vOr = from p in gliMarks
    where p== 98 | p == 88 
    select p;
listBox1.ItemsSource = G90;
}



Linq on Collection of Objects

class Session
{
public string Speaker { get; set; }
public string SessionName { get; set; }
}

List<Session> glSessions = new List<Session>{
new Session{Speaker = "Shalvin P D", SessionName= "Entity Framework 4"},
new Session{Speaker="Arun Kumar", SessionName="Powershell"}};

var G = from p in glSessions
where p.Speaker == "Shalvin P D"
select new { p.Speaker, p.SessionName };


dataGrid1.ItemsSource = G.ToList();
}