Friday, 29 July 2011

Getting the Enums Description

Some times we need to enums for strongly typed strings in place of normal string values. But while displaying the enums we need the space between two words at that time we uses the enum description as follows
public enum MenuOptions
{
[Description("Park Vehicle")]
ParkVehicle = 1,
[Description("Exit Vehicle")]
ExitVehicle = 2,
[Description("Check Slot is Empty")]
CheckSlotIsEmpty = 3,
[Description("Parked Vehicles List")]
ParkedVehiclesList = 4,
[Description("Exit")]
Exit = 5
}

Code to get the Enum Description:
public String GetEnumDescription(Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes =
(DescriptionAttribute[])fi.GetCustomAttributes
(typeof(DescriptionAttribute), false);
return (attributes.Length > 0) ? attributes[0].Description : value.ToString();
}

The usage of enum description as follows
public static void GetNavigation()
{
foreach (int i in Enum.GetValues(typeof(MenuOptions)))
Console.WriteLine("{0}. {1}", i,GetEnumDescription((Enum)Enum.Parse(typeof(MenuOptions),Enum.GetName(typeof(MenuOptions), i))));
}

Declaring and using delegates in csharp

The following is the simple way to declare and using delegates
using System;
using System.Drawing;
using System.Windows.Forms;

// custom delegate
public delegate void Startdelegate(); //we can pass any type of parameter ex StartDelegate(string x);

class Eventdemo : Form
{
// custom event
public event Startdelegate StartEvent;

public Eventdemo()
{
Button clickMe = new Button();

clickMe.Parent = this;
clickMe.Text = "Click Me";
clickMe.Location = new Point(
(ClientSize.Width - clickMe.Width) /2,
(ClientSize.Height - clickMe.Height)/2);

// an EventHandler delegate is assigned
// to the button's Click event
clickMe.Click += new EventHandler(OnClickedMe);
// our custom "Startdelegate" delegate is assigned
// to our custom "StartEvent" event.
StartEvent += new Startdelegate(OnStartEvent);

// fire our custom event
StartEvent(); // if pass the parameters while declaring then call like StartEvent("hello")
}

// this method is called when the "StartEvent" Event is fired
public void OnStartEvent()
{
MessageBox.Show("I Just Started!");
}
//this method is called when button is clicked
public void OnClickedMe(object delSender, EventArgs delE)     
    { 
       MessageBox.Show("You Clicked My Button!");  
     };

 static void Main(string[] args)
{
Application.Run(new Eventdemo());
}
}

Note: EventHandler is a builtin type delegate. We can write our own delegates to handle events.

Querying xml using LINQ

LINQ to XML

Suppose that instead of hard-coding our suppliers and products, we’d used the following XML file:
<?xml version="1.0"?>
<Data>
<Products>
<Product SupplierID="1">
<Name> West Side Story</Name>
<Price>9.99</Price>
</Product>
<Product SupplierID="2">
<Name>Assassins</Name>
<Price>14.99</Price>
</Product>
<Product SupplierID="1">
<Name>Frogs</Name>
<Price>9.99</Price>
</Product>
</Products>
<Suppliers>
<Supplier SupplierID="1">
<Name>Solely Sondheim</name>
</Supplier>
<Supplier SupplierID="2">
<Name>CD-by-CD-by-Sondheim</name>
</Supplier>
</Suppliers>
</Data>

The file is simple enough, but what’s the best way of extracting the data from it? How do we query it? Join on it?. The following listing shows how much work we have to do in LINQ to XML.
XDocument doc = XDocument.Load("data.xml");
var filtered = from p in doc.Descendants("Product")
join s in doc.Descendants("Supplier")
on (int)p.Attribute("SupplierID")
equals (int)s.Attribute("SupplierID")
where (decimal)p.Element("Price") > 10
orderby (string)s.Element("Name"),
(string)p.Element("Name")
select new
{
SupplierName = (string)s.Element("Name"),
ProductName = (string)p.Element("Name")
};
foreach (var v in filtered)
{
Console.WriteLine("Supplier={0}; Product={1}",
v.SupplierName, v.ProductName);
}

Browser fixes for Styles in CSS

To apply any styles specific to the  all IE browsers append \o/ (use zero) to the styles before the semicolon as follows
.class{ padding-top:10px \o/; }

To apply any styles specific to the  all IE7  append  either // or  * to the styles before the style as follows
.class{ //padding-top:10px; }

.class{ *padding-top:10px; }

To apply any styles specific to the  safari browser append write the styles as follows
 @media screen and (-webkit-min-device-pixel-ratio:0) 
{
   //write your styles here
}

Ex:

 @media screen and (-webkit-min-device-pixel-ratio:0)
{
    .class {font-size:15px; margin-top:3px;}
}

To apply the styles specific to IE9 then the style declaration for IE9 as follows

Ex:
:root #dvtest { left:300px\o/;}

How to Get the Index Position of the LINQ Query Results

Select  and SelectMany  expose an overload that surfaces the index position (starting at zero) for each returned element in the Select projection. It is surfaced as an overloaded parameter argument of the selector lambda expression and is only accessible using the extension method query syntax(Lamda Expression). The following sample code demonstrates how to access and use the index position value in a Select projection.
List<CallLog> callLog = CallLog.SampleData();
var q = callLog.GroupBy(g => g.Number)
.OrderByDescending(g => g.Count())
.Select((g, index) => new
{
number = g.Key,
rank = index + 1, //one is added because it is zero based index
count = g.Count()
});

Creating an Xml document using XmlWriter in C Sharp

The following is the sample code to create xml document using c sharp
FileStream fs = new FileStream("products.xml", FileMode.Create);

XmlWriter w = XmlWriter.Create(fs);

w.WriteStartDocument();
w.WriteStartElement("products");

w.WriteStartElement ("product");
w.WriteAttributeString("id", "1001");
w.WriteElementString("productName", "Gourmet Coffee");
w.WriteElementString("productPrice", "0.99");
w.WriteEndElement();

w.WriteStartElement("product");
w.WriteAttributeString("id", "1002");
w.WriteElementString("productName", "Tea Pot");
w.WriteElementString("productPrice", "12.99");
w.WriteEndElement();

w.WriteEndElement();
w.WriteEndDocument();
w.Flush();
fs.Close();

We can write it also by using XmlTextWriter. the following is the sample code is using XmlTextWriter
// prepare and write XML document
using (StringWriter writer = new StringWriter())
{
using (XmlTextWriter doc = new XmlTextWriter(writer))
{
// prepare XML header items
doc.Formatting = Formatting.Indented;
doc.WriteComment(”Summarized Incoming Call Stats”);
doc.WriteStartElement(”contacts”);
// join calls with contacts data
foreach (Contact con in contacts)
{
if (callGroups.ContainsKey(con.Phone))
{
List calls = callGroups[con.Phone];
// calculate the total call duration and average
long sum = 0;
foreach (CallLog call in calls)
sum += call.Duration;
double avg = (double)sum / (double)calls.Count;
// write XML record for this contact
doc.WriteStartElement(”contact”);
doc.WriteElementString(”lastName”,
con.LastName);
doc.WriteElementString(”firstName”,
con.FirstName);
doc.WriteElementString(”count”,
calls.Count.ToString());
doc.WriteElementString(”totalDuration”,
sum.ToString());
doc.WriteElementString(”averageDuration”,
avg.ToString());
doc.WriteEndElement();
}
}
doc.WriteEndElement();
doc.Flush();
doc.Close();
}
Console.WriteLine(writer.ToString());
}

Declaring and using anonymous types

The following is the way of declaring and using anonymous types
// simple anonymous type declaration
Console.WriteLine(”- Simple Anonymous Type -”);
var item = new { Name = ”Car”, Price = 9989.00 };
Console.WriteLine(”Type: {0}, Name: {1}, Price: {2}”,
item.GetType().ToString(), item.Name, item.Price);

 

// declaring and working with array of anonymous types
Console.WriteLine();
Console.WriteLine(”- Iterating Anonymous Types Array -”);
var list = new[] {
new { LastName = ”Magennis”,
DateOfBirth = new DateTime(1973,12,09)
},
new { LastName = ”Doherty”,
DateOfBirth = new DateTime(1978,1,05)
}
};
foreach (var x in list)
Console.WriteLine(”{0} ({1})”,
x.LastName, x.DateOfBirth);