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);

Generating xml using linq query

The sample code for generating xml using linq query as follows
List<Contact> contacts = Contact.SampleData();
List<CallLog> callLog = CallLog.SampleData();
var q = from call in callLog
where call.Incoming == true
group call by call.Number into g
join contact in contacts on
g.Key equals contact.Phone
orderby contact.LastName, contact.FirstName
select new XElement(”contact”,
new XElement(”lastName”,
contact.LastName),
new XElement(”firstName”,
contact.FirstName),
new XElement(”count”,
g.Count()),
new XElement(”totalDuration”,
g.Sum(c => c.Duration)),
new XElement(”averageDuration”,
g.Average(c => c.Duration))
);
// create the XML document and add the items in query q
XDocument doc = new XDocument(
new XComment(”Summarized Incoming Call Stats”),
new XElement(”contacts”, q)
);
Console.WriteLine(doc.ToString());

output for the above query is as follows
<!—Summarized Incoming Call Stats—> 
<contacts>
<contact> 
<lastName>Gottshall</lastName> 
<firstName>Barney</firstName> 
<count>4</count> 
<totalDuration>31</totalDuration> 
<averageDuration>7.75</averageDuration>
</contact> 
... (records cut for brevity) 
<contact>
<lastName>Valdes</lastName> 
<firstName>Armando</firstName> 
<count>2</count> 
<totalDuration>20</totalDuration> 
<averageDuration>10</averageDuration>
</contact> 
</contacts>

Thursday, 28 July 2011

Grouping list of objects

There are two methods for grouping list of  objects in c sharp. one is using  Dictionary and other one is using linq to objects

Using StoredDictionary
// group by state (using a sorted dictionary)
SortedDictionary<string, List<Contact>> groups =
new SortedDictionary<string, List<Contact>>();
foreach (Contact c in contacts)
{
if (groups.ContainsKey(c.State))
{
groups[c.State].Add(c);
}
else
{
List<Contact> list = new List<Contact>();
list.Add(c);
groups.Add(c.State, list);
}
}
// write out the results
foreach (KeyValuePair<string, List<Contact>>
group in groups)
{
Console.WriteLine(”State: “ + group.Key);
foreach (Contact c in group.Value)
Console.WriteLine(” {0} {1}”,
c.FirstName, c.LastName);
}

Using Linq to objects:

Linq to objects works from 3.0 .net frame work

var query = from c in contacts group c by c.State;
// write out the results
foreach (var group in query)
{
Console.WriteLine(”State: “ + group.Key);
foreach (Contact c in group)
Console.WriteLine(” {0} {1}”,
c.FirstName, c.LastName);
}

Sorting a list of object in c sharp

There are three methods to sort list of  objects in c sharp. one is using Deletages, second Implementing IComparer interface, and other one is using linq to objects

Implementing IComparer(C#1.0)
class ContactNameComparer : IComparer
{
public int Compare(Contact x, Contact y)
{
return x.Name.CompareTo(y.Name);
}
}
...
List<Contact> contacts=Contact.SampleData();
contacts.Sort(new ContactNameComparer());
foreach (Contact contact in contacts)
{
Console.WriteLine(contact);
}


Using  inline delegates(from C#2.0)

List<Contact> contacts = Contact.SampleData();
// sort by last name
contacts.Sort(
delegate(Contact c1, Contact c2)
{
if (c1 != null && c2 != null)
return string.Compare(
c1.LastName, c2.LastName);
return 0;
}
);

Using Linq to Objects(From C#3.0)

List<Contact> contacts = Contact.SampleData();
// perform the LINQ query
var query = from c in contacts
orderby c.State, c.LastName;

Friday, 22 July 2011

Regular Expression for password strength validation

Shown below is the regular expression for password strength with n number of digits, upper case, special characters and at least 6 characters in length.
(?=^.{6,25}$)(?=(?:.*?\d){2})(?=.*[a-z])(?=(?:.*?[A-Z]){2})(?=(?:.*?[!@#$%*()_+^&}{:;?.]){1})(?!.*\s)[0-9a-zA-Z!@#$%*()_+^&]*$
Explanation:
  • (?=^.{6,25}$) -- password length range from 6 to 25, the numbers are adjustable
  • (?=(?:.*?[!@#$%*()_+^&}{:;?.]){1}) -- at least 1 special characters (!@#$%*()_+^&}{:;?.}) , the number is adjustable
  • (?=(?:.*?\d){2}) -- at least 2 digits, the number is adjustable
  • (?=.*[a-z]) -- characters a-z
  • (?=(?:.*?[A-Z]){2}) -- at least 2 upper case characters, the number is adjustable

Wednesday, 13 July 2011

HTML 5 support for all non supported IE browsers or HTML5 in IE

Many of time you have seen that few HTML 5  tags are not supported by Internet Explorer. The solution for this is only <script> tag.

The <script> tag is very useful to define client side script but in this code I used it for only to make my Internet Explorer compatible to represent HTML5  tags.
To work with html5 tags in IE write the following code in <script> tag in header section.
<script type="text/javascript">  
document.createElement('nav');
document.createElement('menu');
.........................
.........................
</script>

Like the above what are the tags you want use just write single statement for each tag. or write as below
<!--[if IE]>
<script type="text/javascript">
var html5elements =
"menu,nav,output,progress,section,time,video,...........etc".split(',');
for (var i = 0; i < html5elements.length; i++)
document.createElement(html5elements[i]);
</script>
<![endif]-->