Posts Tagged ‘C#’
Named & Optional Parameter, C# 4.0 Part 2
In visual basic we were having optional parameter option which can help you to send only some parameter to methods and reset will take the default values. Same feature is part of C# 4.0 where you can have default values for the parameters.
But one more noticeable feature is “named parameter”. You might have seen in VB also that if you want to set any of the parameter no values then you have to leave all other parameters also which are defined after that variable. To sort this out you can use named parameter which specify the name of the parameter and value for it “seats:4” where seats is the parameter and 4 is the value.
Both of the features are shown below in sample
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ParameterFeatures
{
class Program
{
static void Main(string[] args)
{
Vehicle car = new Vehicle("V6");
Vehicle van = new Vehicle(seats:4);
Console.WriteLine("Engine : " + car.Engine);
Console.WriteLine("Seats : " + van.Seats.ToString());
Console.ReadLine();
}
}
class Vehicle
{
public string Engine { get; set; }
public int Seats { get; set; }
public Vehicle(string engine = "V8", int seats = 5)
{
Engine = engine;
Seats = seats;
}
}
}
Dynamic Lookup & dynamic Type, C# 4.0 Part 1
C# 4.0 is out once again with new set of features. Now we will see one of the new feature of it, which is know as Dynamic Lookup. It is new approach for invoking thing more dynamically than before. It gives big freedom and working with various different kind of objects like COM etc will be too easy.
Big question how. I have written one sample below where i am grabbing the object of excel instance which is already running and filling data in it. In the previous version of C# we used to do it with the help of InvokeMember funtions of the object. But in C# 4.0 story is differentM
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DynamicObjects
{
class Program
{
static void Main(string[] args)
{
dynamic excel = System.Runtime.
InteropServices.Marshal.GetActiveObject("Excel.Application");
//Display the name of the work book
Console.WriteLine(excel.ActiveWorkbook.Name);
//Select the range and place some data here
excel.Range("B2").Select();
excel.ActiveCell.FormulaR1C1 = "Sample Data";
//Wait for the input
Console.ReadLine();
}
}
}
It was so simple to use the dynamic object, That i have to just type out the properties and method in the front of dynamic object. At the time of getting that object it will be handled automatically and will map the functions and methods. Its really a great feature, which can save time and give more freedom to the developer.
Difference between VAR & DYNAMIC
VAR It is also know as local type inference feature of C#. This feature will allow you to remove the data type from the left hand side and create the type on the fly. But still you have to specify the type in the right hand side and var will be replaced by the new type which will be built at compile time.
DYNAMIC it is step ahead of the VAR. It will get the information of the object not at the compile time rather at the time of creation of that object. It is done at runtime only.
Captcha Control Sample (C#, ASP.NET, Server Control)
In various websites, Captcha control is used for validating the user input and protect web application from the program. Here is one of the sample control for Captcha. It is basic one which can be enhanced further by including more to the image generation and even including the timeout. Or you can add much more to it
This application has two parts
1. CaptchaControl
2. CaptchaControl Sample Project
Captcha control has three files.
1. CaptchaControl (Which is the main control)
2. CaptchaImage (Which generates the Captcha image)
3. CaptchaImageHandler (which will provide the image to browser from the cache).
You can download it from (Captcha Control Sample)
Listing All the references of Assembly
We can list all the references of the assembly in a recursive manner. Here i have avoided System Assemblies since those are not required & they are in circular references. Download the code from this link
private void btnList_Click(object sender, EventArgs e)
{
txtReferences.Text = "";
OpenFileDialog openFileDlg = new OpenFileDialog();
if (openFileDlg.ShowDialog() == DialogResult.OK)
{
txtAssemblyPath.Text = openFileDlg.FileName;
Assembly assembly = Assembly.LoadFrom(txtAssemblyPath.Text);
ListReferences("",assembly);
}
MessageBox.Show("Listing Completed");
}
public void ListReferences(string location, Assembly assembly)
{
//List all references
string name = assembly.GetName().Name;
string CurrentLocation = location;
txtReferences.Text += CurrentLocation + ">" + name + "\r\n";
location += "--";
if (!name.StartsWith("System.") && !Name.Equals("System"))
{
foreach (AssemblyName assemblyName in assembly.GetReferencedAssemblies())
{
assembly = Assembly.Load(assemblyName);
ListReferences(location, assembly);
Application.DoEvents();
}
}
}
Search your website (Microsoft Indexing Service, C#, ASP.NET)
You might have seen various website providing search capabilities to search content within their website. Implementing this in our web application is also easy and for that we have to just use the indexing service to create indexes of our pages. Microsoft is providing indexing service which we can utilise for this purpose.
To understand what is indexing service click this link
Now you might wonder how to get this service in your system. For that follow the steps
1. Goto Control Panel > Add Remove Programs
2. Click “add remove windows component”
3. from the screen select “Indexing service” and install
Now you have indexing service in your system. From computer management you can see the indexing service and can manage it. We need to create new catalog which will contain the indexes. To that catalog we will add the directories which are to be indexed.
There are other settings too like Indexing Service usage and etc. For that right click your indexing service node and select All Task > Tune Performance
We can now implement this in our web application to search the web pages. Below sample code is written for seaching and displaying the content in the ASP.Net Page
string connectionString ="Provider=MSIDXS;Data Source=MISSample;";
OleDbConnection connection = new OleDbConnection(connectionString);
connection.Open();
string query = @"SELECT Path, FileName, size, write, attrib, Characterization,
DocTitle FROM SCOPE() " +
"WHERE FREETEXT(Contents, '*" + txtQuery.Text + "*')";
OleDbCommand command = new OleDbCommand(query, connection);
OleDbDataAdapter adapter = new OleDbDataAdapter(command);
DataSet dataSet = new DataSet();
adapter.Fill(dataSet);
GridView1.DataSource = dataSet.Tables[0];
GridView1.DataBind();
connection.Close();
Sample Output
XML Serialization
Some time we need to save the data in the files which is nothing but the details of the object. For example i am having a application doing vector drawing and i want to save the details of the line object not the image file. How to save the line object and how to get it back. We can use serialization with which we can save our object in file directly and can load it too. Also we can use XML Serialization which is so popular these days.
We have to just mark out objects and class with certain Attributes like XMLRoot, XMLElement, XMLAttribute and so on.
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
namespace XMLSerialization
{
static class Program
{
static void Main()
{
DoSerialization();
}
private static void DoSerialization()
{
Student student1 = new Student { Name = "A", Marks = 23 };
Student student2 = new Student { Name = "B", Marks = 25 };
Students students = new Students();
students.StudentList.Add(student1);
students.StudentList.Add(student2);
XmlSerializer xmlSerialize = new XmlSerializer(students.GetType());
StreamWriter writer = new StreamWriter("a.xml");
xmlSerialize.Serialize(writer, students);
writer.Close();
StreamReader reader = new StreamReader("a.xml");
Students studentsfromFile = (Students)xmlSerialize.Deserialize(reader);
foreach (Student st in studentsfromFile.StudentList)
{
Console.WriteLine("Name : {0} Marks : {1}", st.Name, st.Marks);
}
Console.ReadLine();
}
}
[XmlRoot("Students")]
public class Students
{
[XmlElement("Student")]
public List<Student> StudentList = new List<Student>();
}
public class Student
{
[XmlElement("Name")]
public string Name;
[XmlElement("Marks")]
public int Marks;
}
}
Sample weather forecast WCF application.
Here is one WCF webservice sample developed for weather forecasting. Two projects are include one is web application another one is wcf application. Download and check out
Netstat in C#
Check out how to perform Netstat command functions of DOS in C#. It will list you all the current network connections of your System
using System;
using System.Net;
using System.Net.NetworkInformation;
namespace MyNetstat
{
class Program
{
static void Main(string[] args)
{
IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] endPoints = ipProperties.GetActiveTcpListeners();
TcpConnectionInformation[] tcpConnections = ipProperties.GetActiveTcpConnections();
foreach (TcpConnectionInformation info in tcpConnections)
{
Console.WriteLine("Local : " + info.LocalEndPoint.Address.ToString()
+ ":" + info.LocalEndPoint.Port.ToString()
+ "\nRemote : " + info.RemoteEndPoint.Address.ToString()
+ ":" + info.RemoteEndPoint.Port.ToString()
+ "\nState : " + info.State.ToString() + "\n\n");
}
Console.ReadLine();
}
}
}
Listing Domains, Groups, Schemas, User, Computer from DirectoryEntry
To list the Domains and their respective Groups, Schemas, User and Computer use DirectoryEntry and enumerate through the Children of the respective Entry. Check out the following code for more understanding
Include Reference to System.DirectoryServices in the project
using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
DirectoryEntry dirEntry = new DirectoryEntry("WinNT:");
foreach (DirectoryEntry de in dirEntry.Children)
{
if (de.SchemaClassName == "Domain")
{
Console.WriteLine("Domain : " + de.Name);
Console.WriteLine("=================\n");
foreach (DirectoryEntry de2 in de.Children)
{
Console.WriteLine(" Name : " + de2.Name + " \t\t Type : " + de2.SchemaClassName);
}
}
de.Dispose();
}
dirEntry.Dispose();
Console.ReadLine();
}
}
}
Google Contact Detail Listing (C# , Google API, ASP.NET)
Check out the following ASP.NET example for listing contact of a gmail account and adding a new contact to it. First download the Google Data API from the specified link and install it
http://code.google.com/p/google-gdata/
Then create a new project and include following references in it
Google.GData.Client.dll
Google.GData.Contacts.dll
Google.GData.Extensions.dll
Then i created the following class
using System;
using System.Collections.Generic;
using Google.GData.Contacts;
using Google.GData.Extensions;
///
/// Summary description for GoogleContactService
///
public class GoogleContactService
{
public static ContactsService GContactService = null;
public static void InitializeService(string username,
string password)
{
GContactService = new ContactsService("Contact Infomation");
GContactService.setUserCredentials(username, password);
}
public static List<ContactDetail> GetAllContact()
{
List<ContactDetail> contactDetails = new List<ContactDetail>();
ContactsQuery query = new ContactsQuery(ContactsQuery.
CreateContactsUri("default"));
ContactsFeed feed = GContactService.Query(query);
foreach (ContactEntry entry in feed.Entries)
{
ContactDetail contact = new
ContactDetail{Name = entry.Title.Text,
EmailAddress1 = entry.Emails.Count >= 1 ? entry.Emails[0].Address : "",
EmailAddress2 = entry.Emails.Count >= 2 ? entry.Emails[1].Address : "",
Phone = entry.Phonenumbers.Count >= 1 ? entry.Phonenumbers[0].Value : "",
Address = entry.PostalAddresses.Count >= 1 ? entry.PostalAddresses[0].Value : "",
Details = entry.Content.Content};
contactDetails.Add(contact);
}
return contactDetails;
}
public static void AddContact(ContactDetail contact)
{
ContactEntry newEntry = new ContactEntry();
newEntry.Title.Text = contact.Name;
EMail primaryEmail = new EMail(contact.EmailAddress1);
primaryEmail.Primary = true;
primaryEmail.Rel = ContactsRelationships.IsWork;
newEntry.Emails.Add(primaryEmail);
EMail secondaryEmail = new EMail(contact.EmailAddress2);
secondaryEmail.Rel = ContactsRelationships.IsHome;
newEntry.Emails.Add(secondaryEmail);
PhoneNumber phoneNumber = new PhoneNumber(contact.Phone);
phoneNumber.Primary = true;
phoneNumber.Rel = ContactsRelationships.IsMobile;
newEntry.Phonenumbers.Add(phoneNumber);
PostalAddress postalAddress = new PostalAddress();
postalAddress.Value = contact.Address;
postalAddress.Primary = true;
postalAddress.Rel = ContactsRelationships.IsHome;
newEntry.PostalAddresses.Add(postalAddress);
newEntry.Content.Content = contact.Details;
Uri feedUri = new Uri(ContactsQuery.CreateContactsUri("default"));
ContactEntry createdEntry = (ContactEntry)GContactService.Insert(feedUri, newEntry);
}
}
public class ContactDetail
{
public string Name { get; set; }
public string EmailAddress1 { get; set; }
public string EmailAddress2 { get; set; }
public string Phone { get; set; }
public string Address { get; set; }
public string Details { get; set; }
}
After that i create one webpage to list and create new contacts details in my gmail account. You can download the complete project from this location Download Here









