Category Archives: .NET

Multiple Silverlight Application to Web Application

Visual Studio 2010 allows to add multiple Silverlight Projects to the Solution. These silverlight projects can be added to the single web application project.

To add multiple Silverlight Project to the Web Application, select the Web Application and right click and go to Properties



In the properties page there will be a Silverlight Application Tab.


Click on the Add button to select the SIlverlight Project


LINQ to XML using join, group by order by query

We can use LINQ to write a complex query like join and group by operations. The below sample shows a simple join query and the group by command in 2 XML files. I use the 2 xml files firstxml.xml and secondxml.xml






Sample Code using LINQ


                XDocument first = XDocument.Load(“FirstXml.xml”);
                XDocument second = XDocument.Load(“SecondXml.xml”);

                XElement felement = first.Element(“dataroot”);
                XElement selement = second.Element(“dataroot”);


                var syns1 = from f in felement.Elements(“Names”)
                            join s in selement.Elements(“Info”) on f.Element(“NAME_ID”).Value equals
                            where f.Element(“PARENTS_NAME_ID”).Value == “Sen”
                            orderby (string)s.Element(“INFO_COMMENTS”) descending
                            group s by s.Element(“INFO_COMMENTS”).Value into g
                            select g;


The above query returns the comments from second xml file matches the ID and group by the comment and order by comments descending

Display blank page or no theme –aSP.NET MVC

I deployed my first ASP.NET MVC application to the Windows Server 2008 with IIS7.0. The package deployment was a great choice it deployed everything without any pain. But after I deployed when I try to access the URL it gave me  a blank page. I could not find out the issue. Then I came across this site to solve the issue.

Basically MVC pattern will try to hide all the error messages which is raised from the application for security reason. It’s a good idea but when it comes to the deployment we really don’t know what went wrong.

Later I enabled the HTTP ERROR and HTTP Redirection under Add Role Services in the Server Manager. Once I enable that I got to see the original error. In my case the application could not connect to SQL server. I fixed the issue.



After I fixed that error I could able to browse my site. But another problem came up. The site was naked without any css and images. I thought it’s a server browser which blocks the css. Later I tried in my machine it was still the same without css and images.

Later I found that Static Content was not enabled in the IIS Role. I enabled, it started to work…


How to Create Irregular Shape Controls Silverlight

To draw the irregular shape objects in Silverlight we can use the Polygon and Path. Polygon has multiple points separated by space. Using these points we can draw any shape. The other option is the path. Using path its easy to draw a curve and irregular objects.

Below XAML will draw two objects.

 Width=”640″ Height=”480″ >

 <Grid x:Name=”LayoutRoot”>
   <LinearGradientBrush EndPoint=”0.5,1″ StartPoint=”0.5,0″>
    <GradientStop Color=”Black” Offset=”0″/>
    <GradientStop Color=”#FF4B1818″ Offset=”1″/>
  <Polygon Points=”40,100 40,200 200,200 200,130 150,100″ Fill=”Orange”></Polygon>
  <Path Data=”M415,57 L413,143 L483,142 L484,76 L454,56 z” Fill=”#FFF4F4F5″ Margin=”0,131.5,30.5,38.5″ Stretch=”Fill” Stroke=”Black” UseLayoutRounding=”False” HorizontalAlignment=”Right” Width=”282″/>


Entity Framework Connection String


Code Snippet
  1. using System.Data.EntityClient;
  3.             EntityConnectionStringBuilder entityConString = new EntityConnectionStringBuilder()
  4.             {
  5.                 Metadata = @"res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl",
  6.                 Provider = "System.Data.SqlClient",
  7.                 ProviderConnectionString = new System.Data.SqlClient.SqlConnectionStringBuilder
  8.                 {
  9.                     InitialCatalog = dbname,
  10.                     DataSource = servername,
  11.                     IntegratedSecurity = false,
  12.                     UserID = user,
  13.                     Password = pwd
  14.                 }
  16.                 .ConnectionString
  17.             };
  18.             return entityConString.ToString();

Encrypting app.exe.config using C# code (Or) Modify app.config at runtime

Sometimes in the application there may be a configuration window to save the connection string to the app.config. Usually the windows application uses ApplicationName.exe.config to save the connection strings. Editing the app.config using the c# code may be eminent. The below code sample changes the connection string and saves it back to the application.exe.config file. But in my case the newly added string didn’t take effect unless I restart the application. The below code also demonstrates the encryption of app.config


Code Snippet
  1. System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration("windowsapp1.exe");
  2.             if (config != null)
  3.             {
  4.                 ConnectionStringsSection section = (ConnectionStringsSection)config.GetSection("connectionStrings");
  5.                 section.ConnectionStrings["NAME"].ConnectionString = "MY CON STRING HERE";
  6.                 if (section != null)
  7.                 {
  8.                     ////section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
  9.                     section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
  10.                     section.SectionInformation.ForceSave = true;
  11.                 }
  13.                 config.Save(ConfigurationSaveMode.Modified, true);
  14.                 ConfigurationManager.RefreshSection("connectionStrings");
  15.             }


The above code uses the DataProtectionConfigurationProvider. You can also use RsaProtectedConfigurationProvider. But the config file cannot be copied to the other machine if RsaProtectedConfigurationProvider is used because it uses the machine code to encrypt which is unique to each computer.

Get Logged In User while Impersonate or Run as Admin

Sometimes when a program is run as Administrator, using the System.Security.Principal.WindowsIdentity.GetCurrent().Name will return always System or NT Authority\System. This happens while running the exe under windows service or by Installer class in the windows application.

The below code will solve this issue.

Code Snippet
  1. public static string GetParentUser(int pid)
  2.         {
  3.             string parentUserAccount = null;
  4.             string queryString = String.Format("select ParentProcessId from win32_process where ProcessId={0}", pid);
  5.             using (ManagementObjectSearcher query = new ManagementObjectSearcher(new
  6.             SelectQuery(queryString)))
  7.             {
  8.                 foreach (ManagementObject mo in query.Get())
  9.                 {
  10.                     uint parentPid = (uint)mo.Properties["ParentProcessId"].Value;
  11.                     queryString = String.Format("select Handle from win32_process where ParentProcessId = {0}", parentPid);
  12.                     using (ManagementObjectSearcher subQuery = new ManagementObjectSearcher(new
  13.                     SelectQuery(queryString)))
  14.                     {
  15.                         foreach (ManagementObject mo1 in subQuery.Get())
  16.                         {
  17.                             string handle = (string)mo1.Properties["Handle"].Value;
  18.                             RelatedObjectQuery relatedQuery =
  19.                             new RelatedObjectQuery("associators of {Win32_Process.Handle=\"" + handle + "\"}");
  20.                             relatedQuery.RelatedClass = "Win32_LogonSession";
  21.                             using (ManagementObjectSearcher relQuery = new ManagementObjectSearcher(relatedQuery))
  22.                             {
  23.                                 foreach (ManagementObject mo2 in relQuery.Get())
  24.                                 {
  25.                                     RelatedObjectQuery relQuery2 =
  26.                                     new RelatedObjectQuery("associators of {Win32_LogonSession.LogonId='" +
  27.                                     mo2["LogonId"] + "'}");
  28.                                     relQuery2.RelationshipClass = "win32_LoggedonUser";
  29.                                     using (ManagementObjectSearcher searcher2 = new ManagementObjectSearcher(relQuery2))
  30.                                     {
  31.                                         foreach (ManagementObject mo3 in searcher2.Get())
  32.                                         {
  33.                                             parentUserAccount = String.Format(@"{0}\{1}", mo3["Domain"], mo3["Name"]);
  34.                                         }
  35.                                     }
  36.                                 }
  37.                             }
  38.                         }
  39.                     }
  40.                 }
  41.             }
  42.             return parentUserAccount;
  43.         }


You can download the code here


Hope the above code works. It works for me.

Thanks to the original post

Read Outlook email by filter criteria

Outlook object model provides a more extensible object collections to send and read items. This blog speaks about how to read a email from outlook default profile and process the attachment. The Outlook Item object has a method called Find which allows to filter the mail based on subject, To, cc etc. The below code will get all the mail item with the specified subject. If the item has an attachment it will save it to the path specified.

To begin with Add a Outlook interop assembly to the reference in the project


Once added please copy paste the below code to run the sample

Code Snippet
  1. try
  2.             {
  3.                 Microsoft.Office.Interop.Outlook.Application MyApp = new Microsoft.Office.Interop.Outlook.Application();
  4.                 Microsoft.Office.Interop.Outlook.NameSpace MailNS = MyApp.GetNamespace("mapi");
  5.                 MailNS.Logon(MyApp.DefaultProfileName, Missing.Value, false, true);
  7.                 Microsoft.Office.Interop.Outlook.MAPIFolder MyInbox = null;
  8.                 MyInbox = MailNS.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
  9.                 Microsoft.Office.Interop.Outlook._MailItem InboxMailItem = null;
  11.                 Microsoft.Office.Interop.Outlook.Items oItems = MyInbox.Items;
  12.                 ////string Query = "[Subject] = '" + Properties.Settings.Default.EmailSubject + "'";
  14.                 string Query = "[Subject] = 'my sample search text'";
  15.                 InboxMailItem = (Microsoft.Office.Interop.Outlook._MailItem)oItems.Find(Query);
  16.                 while (InboxMailItem != null)
  17.                 {
  18.                     ListViewItem myItem = lvwMails.Items.Add(InboxMailItem.SenderName);
  19.                     myItem.SubItems.Add(InboxMailItem.Subject);
  20.                     string AttachmentNames = string.Empty;
  21.                     foreach (Microsoft.Office.Interop.Outlook.Attachment item in InboxMailItem.Attachments)
  22.                     {
  23.                         AttachmentNames += item.DisplayName;
  24.                         ////item.SaveAsFile(this.GetAttachmentPath(item.FileName, Properties.Settings.Default.ReceiveAttachmentPath));
  25.                         item.SaveAsFile(this.GetAttachmentPath(item.FileName, "c:\\test\\attachments\\"));
  26.                     }
  27.                     myItem.SubItems.Add(AttachmentNames);
  28.                     InboxMailItem.Delete();
  29.                     InboxMailItem = (Microsoft.Office.Interop.Outlook._MailItem)oItems.FindNext();
  30.                 }
  32.                ////MailMsg.Send();
  33.                 MailNS.Logoff();
  34.                 MailNS = null;
  35.                 MyInbox = null;
  36.                 InboxMailItem = null;
  37.                 ((Microsoft.Office.Interop.Outlook._Application)MyApp).Quit();
  38.                 ////MyApp.Quit();
  39.                 MyApp = null;
  40.             }
  41.             catch (Exception ex)
  42.             {
  43.                 MessageBox.Show(ex.Message);
  44.             }

the getattachmentpath method implementation is below. This method will check for any existing attachment with the same name and adds running number if exists

Code Snippet
  1. private string GetAttachmentPath(string AttachfileName, string AttachPath)
  2.         {
  3.             string filename = Path.GetFileNameWithoutExtension(AttachfileName);
  4.             string ext = Path.GetExtension(AttachfileName);
  5.             int app = 0;
  6.             if (File.Exists(AttachPath + filename + ext))
  7.             {
  8.                 while (File.Exists(AttachPath + filename + app + ext))
  9.                 {
  10.                     app++;
  11.                 }
  12.                 filename = filename + app;
  13.             }
  14.             return AttachPath + filename + ext;
  15.         }

.NET Remoting – Communicate between application

There are situation we need to communicate between application over network or in the same machine. There are several ways to implement the functionality. To communicate between application we have few options like .NEt Named Pipes, MSMQ, Enterprise services and Remoting.

Depends on the requirement we can select the communication option. In this blog i will discuss how to implement kind of chat application using .NET Remoting.

.NET Remoting Overview 

The .NET remoting infrastructure is an abstract approach to inter-process communication. Objects that can be passed by value, or copied, are automatically passed between applications in different application domains or on different computers. Mark your custom classes as serializable to make this work.

Can read more on Remoting here.

Sample Code

The sample application which i am posting here has 3 major component to it

  1. Remoting Server
  2. Remoting Client
  3. Remoting Library

Remoting Server:

The Remoting Server module will open the connection using Tcp Channel on the specified port. The server also can send message to multiple client which are connected to receive the message.


Server Application Exe

Remoting Client:

The Remoting client will try to connect to the server and respond back with the message.


Client Application Exe

Remoting Library:

Remoting Library will have the Remotable Type object with the Message Response and the Message Transfer class type. Both the class types are serializable

Full source is here