Good article to detect the status of a windows service using a ServiceController class in .Net - Detect Windows Service Status
Detect Windows service status .Net
Posted by Techie Cocktail | 1:39 PM | .Net, C-Sharp, References | 0 comments »Displaying culture specific date formats
Posted by Techie Cocktail | 6:20 PM | .Net, C-Sharp | 0 comments »Different countries use different date formats. Hard-coding different date formats in a multi-lingual application is definitely a bad choice. To display the date in the date format as used for a country, .net has ToShortDateString() function.
ToShortDateString() is culture-sensitive and outputs the date which is specific to the current culture set. Below example shows its use.
class Program
{
static void Main(string[] args)
{
//get the current culture and display its date format.
DateTime _date = DateTime.Now;
CultureInfo _currentCulture = Thread.CurrentThread.CurrentCulture;
Console.WriteLine("Current Culture: {0}: ", _currentCulture.Name);
Console.WriteLine(_date.ToShortDateString());
//set the current culture to french & display the french date format
Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");
Console.WriteLine("French Culture: {0}", _date.ToShortDateString());
//set the current culture to italian & display the italian date format
Thread.CurrentThread.CurrentCulture = new CultureInfo("it-IT");
Console.WriteLine("Italian Culture: {0}", _date.ToShortDateString());
//set the current culture to german & display the german date format
Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");
Console.WriteLine("German Culture: {0}", _date.ToShortDateString());
//set the current culture to spanish and display the spanish date format
Thread.CurrentThread.CurrentCulture = new CultureInfo("es-ES");
Console.WriteLine("Spanish Culture: {0}", _date.ToShortDateString());
//set back to the original date format
Thread.CurrentThread.CurrentCulture = _currentCulture;
Console.WriteLine("Back to original Culture: {0}", _date.ToShortDateString());
Console.Read();
}
}
Get list of Cultures
If you are not aware of the culture names then you can use the following function to get the complete list of available cultures. You can use CurrentTypes enum that defines the types of culture lists that can be retrieved. The below example gets the list of all the cultures that ship with .NET Framework, including neutral and specific cultures, cultures installed in Windows OS and custom cultures created by the user.

static void GetAllCultures()
{
string specificCultureName = "";
CultureInfo[] arrCultureInfo = CultureInfo.GetCultures(CultureTypes.AllCultures);
foreach (CultureInfo ci in arrCultureInfo)
{
try
{
specificCultureName = CultureInfo.CreateSpecificCulture(ci.Name).Name;
}
catch { }
Console.WriteLine(ci.Name + ": " + specificCultureName + ": " + ci.EnglishName);
specificCultureName = "----";
}
Console.Read();
}
.Net provides an object called 'Random' to generate random numbers. It is contained in System namespace.
Using the Random object we can generate random integers, bytes and doubles. The Random object contains 3 methods called Next, NextBytes and NextDouble for this purpose. To use the object create an instance of the Random class and call its methods.
Random ranGen = new Random();
Methods
a. Next:
Takes an integer number as the maximum number and returns a random non-negative number less than the maximum number supplied.
int number = ranGen.Next(10);
b. NextBytes:
Takes the buffer of byte[] and fills the buffer elements with random byte numbers.
byte[] buffer = new byte[10];
ranGen.NextBytes(buffer);
foreach (byte bte in buffer)
{
Console.WriteLine(bte.ToString());
}
c. NextDouble:
Returns a random double between 0.0 and 1.0 value.
double number = ranGen.NextDouble();
In C#, using statements are used to reference namespaces. We tend leave unused spaces as is many times without bothering if any extra using statements are left out. But we do not need to bother at all now because visual studio 2008 has given us one handy option/tool integrated within the VS IDE in the source code unit.
Right click anywhere in the source code unit -> Organize Usings -> Remove Unused Usings.
This removes the unused usings statements, leaving behind the usings references of only those namespaces whose classes are being used in your code.
As seen in the above figure, you can also sort Usings or Remove and Sort both. This option is available both for windows and web projects.
Insert and Delete sql table records - LINQ to SQL
Posted by Techie Cocktail | 5:17 PM | C-Sharp, Linq, SQL Server | 0 comments »In the LINQ to SQL Overview, we saw the internals of LINQ to SQL with a simple example showing how to retrieve data from SQL. In this article we will see how to insert and delete records in a SQL table using LINQ to SQL.
Lets take the same example as in the Overview article and insert to and delete records from the Countries table.
Insert Records
To insert records to the table, the LINQ provides two methods -
InsertOnSubmit() - Used insert single record to the database.
InsertAllOnSubmit() - Used to insert multiple records to the database.
These inserts are actually commited to the database when SubmitChanges() method of the DataContext is called. Lets insert Australia, Germany & Russia to the Countries table.
Note: The insert, delete and update operations won't work if the table does not have a primary key set.
public static void InsertCountries()
{
//Create the Countries DataContext object.
CountriesDataContext _countriesDataContext = new CountriesDataContext();
//Create the List of type Country.
//This list would contain the new countries that we will insert in the database.
List
//New country objects
Country _1stCountry = new Country();
_1stCountry.CountryId = 7;
_1stCountry.CountryName = "Russia";
lstCountry.Add(_1stCountry);
Country _2ndCountry = new Country();
_2ndCountry.CountryId = 8;
_2ndCountry.CountryName = "Germany";
lstCountry.Add(_2ndCountry);
Country _3rdCountry = new Country();
_3rdCountry.CountryId = 9;
_3rdCountry.CountryName = "Australia";
lstCountry.Add(_3rdCountry);
//Use InsertAllOnSubmit method to insert the new country list.
_countriesDataContext.Countries.InsertAllOnSubmit(lstCountry);
//Commit to the database.
_countriesDataContext.SubmitChanges();
}
Delete Records
To delete records, we use DeleteOnSubmit() or DeleteAllOnSubmit() methods followed by SubmitChanges() method of the DataContext.
Lets delete few countries from the Country table. Lets say, we want to delete all the countries with CountryId > 5.
public static void DeleteCountries()
{
CountriesDataContext _countriesDataContext = new CountriesDataContext();
var cntries = from c in _countriesDataContext.Countries
where c.CountryId > 5
select c;
_countriesDataContext.Countries.DeleteAllOnSubmit(cntries);
_countriesDataContext.SubmitChanges();
}
There are many insert, delete or update scenarios that people can encounter. MSDN provides good reference - LINQ to SQL Samples covering most of the scenarios.
Add/Remove nodes or elements to an XML Document
Posted by Techie Cocktail | 11:12 PM | C-Sharp, XML | 4 comments »In the article, Update nodes and attributes in Xml document, we saw how to update an element or an attribute value in an Xml Document. It requires you to have a pointer to the node or attribute to update before you can update its value.
Lets say you want to add a new node section to an existing Xml document. For example lets take the same Xml file as used in the earlier article. It contains list of books, each having its name, author and price values. Say you want to add a new book & its details to the existing list of books.
Xml File: books.xml
<?xml version="1.0"?>
<books>
<book name="asp.net">
<author>John</author>
<price>35</price>
</book>
</books>
To add a new node, you don't require to have any pointer using XPath. XMLDocument, XMLElement and its properties and method does it all. We will first see how to add a new book section. After that we will remove the first one using C#.
Add a new node
static void Main(string[] args)
{
string fileName = @"d:\books.xml";
XmlTextReader _xmlTextReader = new XmlTextReader(fileName);
XmlDocument _xmlDocument = new XmlDocument();
_xmlDocument.Load(_xmlTextReader);
//Note: Close the reader object to release the xml file. Else while saving you will get an error that it is
//being used by another process.
_xmlTextReader.Close();
addNode(fileName, _xmlDocument);
}
static void addNode(string fileName, XmlDocument xmlDoc)
{
XmlElement bookElement = xmlDoc.CreateElement("book");
bookElement.SetAttribute("name", "DotNet Made Easy");
XmlElement authorElement = xmlDoc.CreateElement("author");
authorElement.InnerText = "microsoft";
bookElement.AppendChild(authorElement);
XmlElement priceElement = xmlDoc.CreateElement("price");
priceElement.InnerText = "50";
bookElement.AppendChild(priceElement);
xmlDoc.DocumentElement.AppendChild(bookElement);
xmlDoc.Save(fileName);
}
Your Xml file should have new book added and should look like below.
Xml File: books.xml
<?xml version="1.0"?>
<books>
<book name="asp.net">
<author>John</author>
<price>35</price>
</book>
<book name="DotNet Made Easy">
<author>microsoft</author>
<price>50</price>
</book>
</books>
Remove a node
Now lets remove the book - 'asp.net' from the list. The deleteNode() method below will remove the book node whose name="asp.net". Using XPath query we create a pointer to the node that needs to be removed. As book is the child node of the books (root element), RemoveChild() helps to remove the book (child node) from the books (root element).
static void deleteNode(string fileName, XmlDocument xmlDoc)
{
XmlElement _xmlElement = xmlDoc.DocumentElement;
XmlNode _xmlNode = _xmlElement.SelectSingleNode("book[@name='asp']");
_xmlElement.RemoveChild(_xmlNode);
xmlDoc.Save(fileName);
}
As seen from these examples it has become easy to perform almost every Xml task with the use of XML classes in .Net. Happy Coding!
Update nodes and attributes in a Xml document
Posted by Techie Cocktail | 11:09 PM | C-Sharp, XML | 5 comments »Introduction
Xml is widely used in application systems to store and receive data, feeds or for some configuration details. There may be times when you need to update some node or element value or update an attribute value. In this article how you can update node or attributes values in an Xml document.
Approach
To update the value of a node or an attribute, you need to first create a pointer or a reference to that node containing the element or attribute that requires an update using XPath query. And once you get the pointer to that node, you can access the node or the attribute and set its value to the new value.
Example
Lets take a sample Xml file and try to update one of the elements and attributes value using C#.
Xml file: books.xml
<?xml version="1.0"?>
<books>
<book name="asp.net">
<author>John</author>
<price>40</price>
</book>
</books>
Lets see how to update an element and an attribute value as in the below sections. In C# the XML Classes can be found in System.Xml namespace.
Updating an element's value
Lets say you need to update the price of the book named asp.net, as in the above Xml document, to a promotional rate from 40 to 35. The below example shows it.
static void Main(string[] args)
{
string fileName = @"d:\books.xml";
//read the Xml file
XmlTextReader _xmlTextReader = new XmlTextReader(fileName);
//load the Xml file into the XmlDocument object
XmlDocument _xmlDocument = new XmlDocument();
_xmlDocument.Load(_xmlTextReader);
//Note: Close the reader object to release the xml file. Else while saving you will get an error that it is
//being used by another process.
_xmlTextReader.Close();
//update the element (price of the book - asp.net)
updateElement(fileName, _xmlDocument);
}
static void updateElement(string fileName, XmlDocument xmlDoc)
{
//get the root element of the document
XmlElement rootElement = xmlDoc.DocumentElement;
//create a pointer/reference to the price node for the book named 'asp.net'
XmlNode priceNode = rootElement.SelectSingleNode("/books/book[@name='asp.net']/price");
priceNode.InnerText = "35";
//save the Xml
xmlDoc.Save(fileName);
}
In the above example, as in the UpdateElement() method, first the pointer is created to the price node of the book named 'asp.net'. Using that pointer its value is updated by accessing its InnerText (get/set) property.
Updating an attribute's value
Lets say the book name has been changed from 'asp.net' to 'Asp.Net Made Easy'. Lets see how to update the name attribute to the new name in the above Xml.
static void Main(string[] args)
{
string fileName = @"d:\books.xml";
//read the Xml file
XmlTextReader _xmlTextReader = new XmlTextReader(fileName);
//load the Xml file into the XmlDocument object
XmlDocument _xmlDocument = new XmlDocument();
_xmlDocument.Load(_xmlTextReader);
//Note: Close the reader object to release the xml file. Else while saving you will get an error that it is
//being used by another process.
_xmlTextReader.Close();
//update the element (book name)
updateAttribute(fileName, _xmlDocument);
}
static void updateAttribute(string fileName, XmlDocument xmlDoc)
{
//get the root element of the document
XmlElement rootElement = xmlDoc.DocumentElement;
//Update the name attribute's value
XmlNode bookNode = rootElement.SelectSingleNode("/books/book[@name='asp.net']");
if (bookNode.Attributes["name"].Value.Equals("asp.net"))
{
bookNode.Attributes["name"].Value = "Asp.Net Made Easy";
}
//save the Xml
xmlDoc.Save(fileName);
}
Validate Xml using Xsd using C#.Net
Posted by Techie Cocktail | 9:54 PM | C-Sharp, XML | 1 comments »Say you have an application architecture that reads data from xml file, processes it and further renders or input data to another system. The xml element values should have correct data types, the attributes associated to the elements must have the correct types and should not be empty and so on. There can definitely be inconsistencies in the data.
You must ensure that the xml data that you receive is consistent so as not to break your application or further process invalid data. This article shows how you can validate your xml data source using XSD validation type before further processing it.
The first step is to prepare a schema definition file that sets or define rules for your xml source and based on these rules you can further build your application architecture. This conforms that your application will always receive valid xml data.
Lets see an example,
XML File Source: sites.xml
<?xml version="1.0"?>
<refSites>
<site name="techiecocktail">
<url>http://techiecocktail.blogspot.com</url>
<articles>100</articles>
</site>
<site name="xyz">
<url>http:///xyz.com</url>
<articles>50</articles>
</site>
</refSites>
The schema rules file defined for this xml is as below. You can have your own rules defined as per the requirements.
Schema File: siteSchema.xsd
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="generic" elementFormDefault="qualified" targetNamespace="generic">
<xsd:element name="refSites">
<xsd:complexType>
<xsd:sequence maxOccurs="unbounded">
<xsd:element name="site">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="url" type="xsd:string">
</xsd:element>
<xsd:element name="articles" type="xsd:int">
</xsd:element>
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>

Now we have our xml source and its rules defined in the xsd file. Lets use this and build our xml validation logic in c# as below.
XML Valiation:
The required classes that you would require are XMLReaderSettings and XMLReader from System.Xml namespace.
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Schema;
namespace ValidateXML
{
class Program
{
static void Main(string[] args)
{
string appDir = System.AppDomain.CurrentDomain.BaseDirectory;
try
{
//Read the xml and xsd files
XmlTextReader _xmlTextReader = new XmlTextReader(appDir + @"..\..\sites.xml");
StreamReader _streamReader = new StreamReader(appDir + @"..\..\siteSchema.xsd");
//create schema object by reading the streamReader required by XMLReaderSettings object
XmlSchema _xmlSchema = new XmlSchema();
_xmlSchema = XmlSchema.Read(_streamReader, new ValidationEventHandler(_xmlReaderSettings_ValidationEventHandler));
//create XMLReaderSettings object and define the validation type
XmlReaderSettings _xmlReaderSettings = new XmlReaderSettings();
_xmlReaderSettings.ValidationType = ValidationType.Schema;
_xmlReaderSettings.Schemas.Add(_xmlSchema);
//define the callback eventhandler that will be called when there are validation errors
_xmlReaderSettings.ValidationEventHandler += new ValidationEventHandler(_xmlReaderSettings_ValidationEventHandler);
//create the XMLReader object by passing the XMLTextReader and XMLReaderSettings objects
//and read the complete xml file and validating it using the defined schema.
XmlReader _xmlReader = XmlReader.Create(_xmlTextReader, _xmlReaderSettings);
while (_xmlReader.Read()) ;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
//Callback EventHandler to display error message occured during validation.
static void _xmlReaderSettings_ValidationEventHandler(object sender, ValidationEventArgs e)
{
Console.Write(e.Message);
Console.Read();
}
}
}
Try to change any data in xml file that does not conform the schema rules. For example, in the xml file, if you change the 'articles' value to a string, the validation EventHandler will be called displaying the error details in the console window.
There are other available validation types such as DTD & XDR, schema validation being the most used one.
MSMQ is a wonderful, easy and powerful methods by which messages can be stored and retrieved from an independent location. This store is unlike databases or a file server where objects can be sent and received independently. This article explains the basics of installing and configuring MSMQ followed by message send and recieve process using an example. MSMQ is further vast in itself. At the end of this article reference sites are available for more information on MSMQ.
What is MSMQ? How it works?
MSMQ is a message queuing system that enables applications to send and receive messages (objects). It is a seperate independent location where messages are stored and retrieved by applications. The receiving application need not be connected at the time when the sender is storing the messages. Messages can be received at a later time when the sender has finished its processing.
Messages can be an xml document, text, images, or in any other format that the receiving application understands. Message Queues can be private or public. Private queues limit their access to the local computer. Public queues are published is the active directory and can be found and accessed by computers in the network.
Before the applications can use the queues for message exchange, they need to be created first. You can use either create them manually or programmatically.
Lets us first see how to install and configure MSMQ. After we install and configure the queue, we will see how to send and receive messages to and from the queue with a good example.
Configuring Messaging Queue:
1. Go to 'Add or Remove programs' through Control Panel.
2. Click on 'Add/Remove Windows Components'.
3. Search for 'Application Server' & click on Details button.
4. Check mark 'Messaging Queue' and hit OK and follow the wizard till the end.
The location for 'Messaging Queue' may be different on your box, just search for 'Messaging Queue', it must exist somewhere in 'Add/Remove Windows Components' window.
Once it is installed, you should see 'Message Queuing' under 'Services and Applications' in Computer Management snap-in as below.
Creating Queues:
Queues can be created manually or programmatically.
Manual Approach:
1. Open the computer management snap-in.
2. Go to the 'Message Queuing' under the 'Services and Applications'.
3. Right click on the 'Private Queues' -> New -> Private Queue. Enter queue name and hit OK. Your queue gets created.
Programmatic Approach:
.Net provides System.Messaging namespace that contains MSMQ related classes.
MessageQueue msgQueue = MessageQueue.Create(@".\Private$\MyQueue");
Now as we know how to create queues, lets see how to send & retrieve to/from our created queue.
As an example, lets create an XML file. Then create a sender application to read and send the XML file to our queue and a receiving application to read and process the XML file.
XML File:
Lets name this xml file to msg.xml, its content as below.
<?xml version="1.0" encoding="utf-8" ?>
<topic>
<name>MSMQ</name>
</topic>
Sender Application:
This application reads the XML file into XMLDocument object (System.XML namespace), copies the Xml into the message body, serializes it using XmlMessageFormatter, and sends it to the Message Queue.
as message to our queue.
static void Main(string[] args)
{
//Create a private queue
MessageQueue msgQueue = MessageQueue.Create(@".\Private$\MyQueue");
//Loads xml into XMLDocument object
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"d:\msg.xml");
//Get the xml into the message body
Message msg = new Message();
msg.Body = xmlDoc;
//serialize the message before sending it to the queue
msg.Formatter = new System.Messaging.XmlMessageFormatter();
msgQueue.Send(msg, "msg1");
}
After executing this code, you will see the msg1 created in the queue as below.

Receiving Application:
As we serialized the message before sending to the queue, at the receiving end the message would need to be deserialized after receiving it and before we could process it further.
static void Main(string[] args)
{
//create & define the message queue
MessageQueue msgQueue = new MessageQueue();
msgQueue.Path = @".\private$\MyQueue";
//Receive the message from the queue.
Message msg = new Message();
msg = msgQueue.Receive();
//define the type of the message being received to deserialize it in the same format as sent
Type[] targettype = new Type[1];
targettype[0] = typeof(XmlDocument);
msg.Formatter = new System.Messaging.XmlMessageFormatter(targettype);
//get the xml message in the XMLDocument object and further process it
XmlDocument xmldoc = new XmlDocument();
xmldoc = (XmlDocument)msg.Body;
Console.Write(xmldoc.InnerXml);
Console.Read();
}
The above example shows how to retrieve a single message. If you want to receive more then one message you can use GetAllMessages() method of the queue and iterate through each message and further process them.
References:
a. MSMQ FAQs: http://www.microsoft.com/windowsserver2003/techinfo/overview/msmqfaq.mspx for more details.
b. MSMQ Complete Reference: http://www.microsoft.com/windowsserver2003/technologies/msmq/default.mspx
Managing EventLogs in Event Viewer using .Net
Posted by Techie Cocktail | 5:58 PM | C-Sharp | 1 comments »Event Viewer (Start->Run->eventvwr) records the software or application specific, hardware, security events. It maintains log information about issues or errors occured on the system or any application. The information can be quite useful as it gives the date/time and the message and description about the issues which helps debug further.
Logging is one of the most crucial aspect of software programming. One can have custom logging mechanisms for their applications. Eventlog can also be used to log custom logs by defining them in custom application specific EventSources. In this article, we will see how to read/write entries, delete logs, create/delete EventSources. The logs can be written or accessed from a local or a remote machine.
To perform the above operations, we need EventLog class. They can be found in System.Diagnostics namespace.
Examples:
a. Read log entries from Application Log.
While reading LogEntries, you must specify the Log from where you want to read the messages. The example below displays only the messages. We can get complete log details from each entry.
static void Main(string[] args)
{
//Read EventLogEntries
EventLog _evtLog = new EventLog();
_evtLog.Log = "Application";
foreach (EventLogEntry entries in _evtLog.Entries)
{
Console.WriteLine("Entry: " + entries.Message);
Console.Read();
}
}
b. Write event log entries in the EventLog.
While writing Event Log entries, you must specify the EventSource against which your messages are written. Its good to create custom EventSource for your application which distinguishes your messages related to your application. You must also specify the EventLogEntryType (enum) which denotes the type of the message being logged.
static void Main(string[] args)
{
EventLog _evtLog = new EventLog();
try
{
//Check if the source already exists
if (!EventLog.SourceExists("testAppName"))
{
//create event source
EventLog.CreateEventSource("testAppName", "testLogName");
}
//write message
_evtLog.Source = "testAppName";
_evtLog.WriteEntry("testMessage", EventLogEntryType.Information);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.Read();
}
}
c. Delete the EventLogSource.
To delete the EventLogSource, you can use EventLog class's DeleteEventSource() static method.
static void Main(string[] args)
{
try
{
//Check if the source already exists
if (!EventLog.SourceExists("testAppName"))
{
//Delete event source
EventLog.DeleteEventSource("testAppName", "."); //deletes 'testAppName' Source from the local machine
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.Read();
}
}
In order to delete specific logs, you can get the list of logs using GetEventLog() method of EventLog class, filter them and delete using the Delete() method.
EventLog.Delete(logName);
Refer MSDN for more details.
Sequential lists are collections of objects that are stored and retrived as lists in a sequential fashion. In .net there are two types of sequential collections called Queue and stack. Both of these are found in system.collections namespace.
Queue
The Queue list is of FIFO (First-in-First-out) type of sequential collection i.e. the object that is stored first in the queue gets retrived first when the queue is dequeued. The items in the queue are added using Enqueue method and are removed using Dequeue method. Count property gets the number of items in the queue.
The below example shows how to add items into the queue.
static void Main(string[] args)
{
int queueCount;
Queue _queue = new Queue();
_queue.Enqueue("obj1");
_queue.Enqueue("obj2");
_queue.Enqueue("obj3");
_queue.Enqueue("obj4");
_queue.Enqueue("obj4");
_queue.Enqueue(null);
queueCount= _queue.Count;
Console.WriteLine(queueCount.ToString()); //count = 6
Console.Read();
}
As you can see in the above example, queue also accepts duplicates and null values.
Now lets see some of the methods and properties on the queue to check its count, access and remove them as in the following example.
static void Main(string[] args)
{
Queue _queue = new Queue();
//Add items to the queue
_queue.Enqueue("obj1");
_queue.Enqueue("obj2");
_queue.Enqueue("obj3");
_queue.Enqueue("obj4");
_queue.Enqueue("obj4");
_queue.Enqueue(null);
//Displays the queue count.
Console.WriteLine(_queue.Count.ToString()); //6
//Removes the first element from the queue.
Console.WriteLine(_queue.Dequeue()); //removes obj1
//displays the top most queue element but does not removes it from the queue.
Console.WriteLine(_queue.Peek()); //displays obj2
//count check after dequeue and peek.
Console.WriteLine(_queue.Count.ToString()); //5
Console.Read();
}
Stack
The stack class is LIFO (Last-in-First-Out) type of sequential list collection. It means that the object that is stored last is retrived first during retrieval operation. To add the item to the stack, it uses push() method and to retrieve items it uses pop() method.
Stack also uses count property and peek() method as in Queue and has similar uses.
Lets see an example to add and retrieve objects in Stack as in the below example.
static void Main(string[] args)
{
Stack _stack = new Stack();
//Add items to the queue
_stack.Push("obj1");
_stack.Push("obj2");
_stack.Push("obj3");
_stack.Push("obj4");
_stack.Push("obj4");
_stack.Push(null);
//Displays the queue count.
Console.WriteLine(_stack.Count.ToString()); //6
//Removes the first element from the queue.
Console.WriteLine(_stack.Pop()); //removes null
Console.WriteLine(_stack.Pop()); //removes obj4
//displays the top most queue element but does not removes it from the queue.
Console.WriteLine(_stack.Peek()); //views obj4
//count check after dequeue and peek.
Console.WriteLine(_stack.Count.ToString()); //4
Console.Read();
}
As we can see from the above examples, both Queue and Stack accepts duplicates and null values. You can perform validations checks while inserting items into these collections as required. Also, the items can be accessed only in sequential fashion, they dont have indexers in order to access items in the middle of the list as we do when using arrays or other collections.
This has always been a favorite topic in the interviews. Checkout some of their differences.
Abstract
a. An abstract class cannot be instantiated. To use the abstract class methods it needs to be derived and used.
b. Unlike interfaces, abstract class can contain constructors or destructors, fields, define or implement methods, properties.
c. Abstract class dont support multiple inheritance.
d. Abstract class supports public, private, internal access specifiers.
e. Abstract class are faster in performance compared to interfaces.
Lets see an example of abstract class implementation:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
class Program
{
public abstract class vehicle
{
public abstract void design();
public virtual void speed()
{
Console.WriteLine("Test the speed of the car");
}
}
public class sedan : vehicle
{
//Note if the design() class is not implemented here then you get an error.
public override void design()
{
Console.WriteLine("4 door design model");
}
}
static void Main(string[] args)
{
sedan _sedan = new sedan();
_sedan.speed();
_sedan.design();
Console.Read();
}
}
}
In the above example, vehicle class is an abstract class. It is defined using abstract keyword. It has two methods - design() & speed(). The design() method is abstract and is generic in nature. It imposes on the derived class to implement the design() method as per its purpose in the sedan class or any other derived class. The speed() method has the default implementation in the vehicle class and is virtual in nature. This means that the derived class can either inherit the speed() method as is in its base class or can override the speed method to update its implementation.
Interface
a. An interface on the otherhand can contain only abstract members. It cannot have method implementation, just the method definitions. The class that implements the interface must implement all the methods defined in that interface.
b. The interface cannot contain constructors or destructors, fields, or properties. And by default all the method definitions are public in nature.
c. The class can implement one or more interfaces thereby supports multiple inheritance.
d. Interface does not support any access modifiers like public, private.
e. Interface are comparitively slower in performance. It takes more time to find the corresponding class containing the requested method.
Lets see an interface example,
public interface IVehicle
{
void design();
void speed();
}
public class coupe : IVehicle
{
public void design()
{
Console.WriteLine("2 door design model");
}
public void speed()
{
Console.WriteLine("Test the speed of the car");
}
}
In the above example, IVehicle is the interface. The method definitions are by default public in nature and the class that implements this interface should declare the methods as public. Here the coupe class implements the methods that are mandated by the interface to use them in the class that implements it.
If you want to decide to choose between using an interface or an abstract class, refer MSDN for recommendations.
Difference between Method Overloading and Overriding
Posted by Techie Cocktail | 9:56 AM | C-Sharp | 1 comments »Both Method overloading and overriding are one of the strong features in object-oriented programming languages.
In a class when you have two methods performing similar functionality but they just require different signatures or types then you can overload them instead of giving them a new name. On the other hand, if your class method does not fulfill the required functionality, you can derive a new class from this base class and update the methods functionality in the derived class using overriding.
Lets see how this can be achieved and also understand their differences.
Method Overloading
a. Overloading means providing different function implementation with same name but with different signatures(return type and input arguments). Both the functions should be declared with the overload keyword.
b. Method overloading is done in the same class. Depending on the argument passed, .net picks up the respective function accordingly.
public class()
{
void myFunction(int i);
void myfunction(string s);
}
c. Overloading is resolved at compile time.
Method Overriding
a. Overriding means providing different function implementation in the derived class with same name and same signature. Overriding allows you to change the behaviour of the function in the child/derived class.
b. You can override a method in the derived class only if you declare the function as virtual in the base class. Method overriding is done in different classes - base class and derived class.
Base Class function
public virtual void myFunction();
Derived Class function
public override void myFunction();
c. Overriding is resolved at runtime.
Below are some differences:
Class
a. Classes are reference types. When the object of the class gets created, it gets the memory allocation in the heap.
b. Classes support inheritance.
They can be inherited from a class or a struct.
c. Class supports instance field initialization.
class myClass
{
int a =10; //no error.
public void func( ) {..//do something...}
}
d. Class objects can be assigned null value as they are of reference types.
e. Classes are passed by reference as a parameter to a function.
f. Classes can have explicit parameterless constructors.
class myClass
{
int a = 10;
myClass()
{
}
}
g. All fields of the class need not be initialized in its constructor.
As seen in the below code, its alright to initialize any or all fields of a class.
class myClass
{
int a;
int b;
myClass()
{
a = 10;
}
}
Struct
a. Structs are value types. They get the memory allocation depending on where they are declared. If declared within the function, they are placed on stack and if they are member of a reference type then they get allocated in the heap.
b. Struct does not support inheritance, hence a struct members cannot be protected & protected internal access specifiers.
c. Struct does not support instance field initialization.
struct myStruct
{
int a = 10; //syntax error.
public void func( ) {...//do something...}
}
d. Struct variables cannot be assigned null as they are value types.
e. Structs are passed by Val as a parameter to function.
f. Structs cannot have explicit parameterless constructors.
struct myStruct
{
int a;
int b;
public MyStruct() //error
{
a = 10;
b = 20;
}
}
g. It is mandatory for the fields of the struct to be initialized in the struct constructor.
The below code gives error because 'b' is not initialized in the struct constructor and get the following error:
"Field 'namespace.class.myStruct.b' must be fully assigned before control is returned to the caller"
struct myStruct
{
int a;
int b;
public myStruct(int x)
{
a = 10;
}
}
Difference between Finalize and Dispose methods
Posted by Techie Cocktail | 1:09 PM | C-Sharp | 0 comments »Both Finalize() and Dispose() methods are called to clean up unmanaged resources. Dispose method is user-driven unlike Finalize which is called when the Garbage collection happens hence it is unpredictable. Hence dipose is generally preferred over Finalize if you want to clean up unmanaged resources in your program thereby increasing the performance.
Following are some more points:
Finalize()
a. Finalize() method cannot be called by the user, it is called automatically by the Garbage collector when an object goes out of scope or inaccessible.
b. The finalize method is protected and hence it can be accessed through the containing class or its derived class.
c. As the class designer, it is always safe to provide the Finalize method. This is in case if the programmer fails to call the Dispose method on the unmanaged resoures, it would cause permanent leak of memory which can hamper performance. So to not to take the blame on yourself, providing Finalize method is always a good practise.
Dispose()
a. Dipose() method is called by the user to free up the unmanaged resources such as files, streams, database connections and handles.
b. When implementing dispose, after calling dispose, call GC.SupressFinalize method in order to prevent Finalize method from running to prevent performance issues.
c. The IDiposable interface contains the dipose method with no arguments and returns void.
Polymorphism is one of the powerful OOPs features in .Net. The word polymorphism means 'many forms', a type or a class can have different forms.
When a class is derived from a base class, it inherits the base class's members and methods.
There are two options here:
a. The derived class can replace the base class method completely with the new implementation. This is achieved by using 'new' keyword in the derived class method. The derived class method can be called using derived class's instance. Whereas the base class method can be called by casting the derived class instance to the base class.
Let’s see this by an example to understand clearly.
using System;
using System.Collections.Generic;
using System.Linq;
namespace Vehicle
{
class Program
{
class car
{
public car() { }
public virtual void body()
{
Console.WriteLine("Generic car model");
}
}
class sedan : car
{
public sedan() { }
public new void body()
{
Console.WriteLine("4 door car model");
}
}
class coupe : car
{
public coupe() { }
public new void body()
{
Console.Write("2 door car model");
}
}
static void Main(string[] args)
{
sedan _sedan = new sedan();
_sedan.body(); //prints "4 door car model"
//case derived class instance to base class to call the base class's method.
((car)_sedan).body(); //prints "Generic car model"
Console.Read();
}
}
}
b. The derived class can inherit the base class's method implementation completely. The derived class method can also add its own implementation in addition. This can be achieved by overriding the virtual base class method. That means that the base class method should be defined with the 'virtual' keyword and the derived class method should be defined using 'override' keyword.
using System;
using System.Collections.Generic;
using System.Linq;
namespace Vehicle
{
class Program
{
class car
{
public car() { }
public virtual void body()
{
Console.WriteLine("Generic car model");
}
}
class sedan : car
{
public sedan() { }
public override void body()
{
base.body();
Console.WriteLine("4 door car model");
}
}
class coupe : car
{
public coupe() { }
public override void body()
{
Console.Write("2 door car model");
}
}
static void Main(string[] args)
{
sedan _sedan = new sedan();
_sedan.body(); //prints "Generic car model" followed by "4 door car model"
Console.Read();
}
}
}
Difference between a Const and Readonly
Posted by Techie Cocktail | 12:28 AM | C-Sharp | 1 comments »Below are some differences:
Const
a. const member field must be initialized at the time of declaration.
b. const field can have only one value which is defined at the time of declaration.
c. const can't be static.
Readonly
a. readonly field can be initialized at the time of declaration or in the class's consructor.
b. The value of the readonly field once set at the time of declaration, can be updated at runtime.
c. readonly can be either instance-level or static.
Look at a const field to be a compile-time constant and readonly field as a runtime constant.
Difference between a thread and process
Posted by Techie Cocktail | 12:25 AM | C-Sharp | 0 comments »Below are some differences:
Process
a. A process is like an individual executing program having its own memory space & system resources.
b. Process has its own seperate memory space.
c. A process can contain a number of threads.
Thread
a. Thread are like an OS environment features which run in the context of a process. Threads are way to split different tasks of a program to improve performance.
b. Threads share resources of the process in which they resides.
c. Threads are contained within the process. Reverse is never possible.
Difference between Typed and Instance Constructors
Posted by Techie Cocktail | 12:53 PM | C-Sharp | 0 comments »Type Constructor:
a. Type constructor is also termed as class/static constructor or type initializers.
b. This constructor gets called when the class gets loaded into the memory and before any of its members are accessed or called.
c. Type constructors can only initialize the static fields in the class.
d. There can be only one type constructor per class and it cannot use vararg (variable argument) calling convention.
Instance Constructor:
a. Instance Constructors are executed when an instance or an object of a class is created.
b. This constructor gets executed after the class is loaded and before any of its members is accessed.
c. Instance constructors can initialize both static and instance fields of the class.
d. There can be multiple overloaded instance constructors with parameters. The return type must be void.
Lets see an example to understand better,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Constructors
{
class Program
{
class myClass
{
public static int _static; //static field.
public int _nonStatic; //non-static field.
//Type constructor
static myClass()
{
//initializes only static fields.
_static = 20;
//_nonStatic = 30; //gives error
}
//Instance constructor
public myClass()
{
//initializes both static and non-static fields.
_static = 30;
_nonStatic = 40;
}
}
static void Main(string[] args)
{
Console.WriteLine(myClass._static); //prints 20;
myClass _myClass = new myClass();
Console.WriteLine(myClass._static); //prints 30;
Console.WriteLine(_myClass._nonStatic); //prints 40;
}
}
}
Enjoy coding.
Partial class feature was introduced in .Net 2.0. Partial classes enable us to use multiple files to store the code of the same class. At the time of compilation all the pieces are clubbed together by the compiler and treated as a single class. Partial concept is also true for struct or an interface.
The developers must be careful doing this and must have good understanding of this feature else it may result in some design issues.
Advantages of using this feature are:
a. The .net available classes can be further extended based on your requirements.
b. Multiple developers can work on the same class simultaneously.
Lets see this using an example,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace clsPartial
{
partial class pCls
{
int a;
public int A
{
get { return a; }
set { a = value; }
}
}
partial class pCls
{
int b;
public int B
{
get { return b; }
set { b = value; }
}
}
class MainClass
{
public static void Main()
{
pCls ab = new pCls();
Console.WriteLine(ab.A + "," + ab.B);
}
}
}
There are some rules when implementing partial class that we must need to follow to avoid errors. Below are some of the important points to consider:
a. Every piece of the partial class must contain the partial keyword & must used the same class name.
b. All pieces of the partial class must be defined in the same assembly or a module.
c. If any of the pieces are declared as abstract, the whole class is considered as the abstract class.
d. All pieces of the partial class must use the same access specifier. For example, public, private etc.
e. If any of its pieces are declared as sealed, the complete class is considered to be a sealed class.
f. If any of its pieces inherits from a base class, the complete class inherits that base class.