Category Archives: Visual Studio

VS 2010, 2008

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…


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.

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.         }

Value does not fall within the expected range –VS2008 Webpart Deploy Error

Visual Studio 2008 comes with the WebPart project template. It’s easy now to create a webpart for SharePoint. But often we want to reuse the WePart created by others over the net. When we reuse the webpart from internet we would directly compile and start to deploy it to MOSS 2007. Sometime we might encounter "Value does not fall within the expected range" when try to deploy to the MOSS server. This error happens when an existing webpart project is reused and deployed. This error happens because there is already a package folder with the different url deployed already. Rename or delete the folder from the Project. Rebuild and deploy again it should work. Make sure you specify the URL for the project in the Project->Properties->Debug->Start Brower with URL field

Package folder

Deploy URL for WebPart