Monthly Archives: November 2010

Entity Framework Connection String

 

Code Snippet
  1. using System.Data.EntityClient;
  2.  
  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.                 }
  15.  
  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.                 }
  12.  
  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

http://bytes.com/topic/c-sharp/answers/631036-getting-currently-logged-user