Tags: , , | Categories: General Posted by Vitaly Zayko on 7/7/2015 1:50 PM | Comments (0)

Don't get me wrong: Hyper-V is very great technology. But, unfortunately, in case when Hyper-V is active, you won't be able to run other virtualization. Why you might need that? For example, if you decide to work with Docker locally, or you need to run Android emulators. Here is how to disable Hyper-V in one simple command:

dism.exe /Online /Disable-Feature:Microsoft-Hyper-V

And, of course, the apposite action:

dism.exe /Online /Enable-Feature:Microsoft-Hyper-V /All

Please, be prepared to reboot your PC after these actions.

Tags: | Posted by Vitaly Zayko on 7/10/2013 7:53 PM | Comments (0)

Move your mouse over vertical scroll bar, press right button and choose "Scroll Bar Options...". In opened windows select option "Use map mode for vertical scroll bar". Also you might want to activate check box "Show preview tooltip". Hit OK when you done. Observe that vertical scroll bar becomes thumbnail copy of the current code window. If you move your mouse over this bar, Visual Studio will show you pice of code normal size code block like in spy glass. Very handy! And you you know what is the best part? This scroll bar is still works like a scroll bar Laughing

Tags: | Categories: Visual Studio Tip Posted by Vitaly Zayko on 7/6/2013 9:02 AM | Comments (0)

Microsoft Visual Studio 2013 will be released just about year after of VS2012. Nevertheless, it has lots of new great features. Here is one of my favorite.
In addition to well known Go to Definition (F12), which finds and opens source of a given class in separate windows, Microsoft added Peek Definition (Alt-F12). This command shows definitions in small embedded window without need to finding your recent window back after you check a definition.

Categories: Code Snippets, General Posted by Vitaly Zayko on 7/3/2013 12:37 PM | Comments (0)

CSV (Comma-separated values) files are very handy for using in self-generated tabular reports as they extremely easy to create in any programming language. But to be opened correctly in Microsoft Excel, the separator should depend on Windows Regional settings: in some countries it could be comma whereas in others – semicolon etc. Fortunately there is an easy way how to let Excel know what separator you use in a given file. Just put sep=<separator symbol> as the very first string in your file (get rid of <>  chars, just put a symbol). It could any symbol that is not used in your data guaranteed, even invisibles such as TAB (ASCII 9).

Tags: | Categories: Visual Studio Tip Posted by Vitaly Zayko on 6/27/2013 10:56 AM | Comments (0)

If for whatever reason your dev environment turned up to be behind of a web proxy server (for instance, if you work with the cloud hosted TFS), you won't be able to check-in/check-out without proper proxy settings in your Visual Studio. Unfortunately, VS doesn't use system settings. There are few "unofficial" methods how to do this. One of them is to manually add some settings to your devenv.exe.config file but I prefer do not touch system settings in such way especially because there is another one and more natural.
In your Visual Studio 2012 environment open menu Tools -> Extensions and Updates and choose Updates – > Product Updates on the left. If proxy wasn't setup yet, VS will prompt you to enter required information and you will be able to work with TFS. As a side effect, your environment will be able to check updates automatically. So this is 2-in-1 suggestion Winking smile .

setup_proxy_vs2012

Tags: | Categories: Code Snippets Posted by Vitaly Zayko on 4/26/2013 2:45 PM | Comments (0)

Let's say you need to create a folder on behalf of a user and protect it from access by anyone but this user. Use DirectorySecurity.SetAccessRuleProtection procedure like this:

 DirectoryInfo  dir = new  DirectoryInfo (DirPath);
 if  (!dir.Exists)
 {
     dir.Create();
     DirectorySecurity  ds = dir.GetAccessControl();
     ds.SetAccessRuleProtection(true , false );
     ds.AddAccessRule(new  FileSystemAccessRule (DomainName + "\\\\"  + UserName,
         FileSystemRights .FullControl, AccessControlType .Allow));
     dir.SetAccessControl(ds);
 }
 

Please be noted that local administrator could request and get access rights even for protected folders. Admins are admins.

Tags: , , , | Categories: Code Snippets Posted by Vitaly Zayko on 7/31/2012 11:45 AM | Comments (0)

When you try to connect your client App to a server through self-signed SSL certificate (which is normal during development, but obviously is not in production), by default you will get a security exception because such certificate could not be validated. The good approach is to warn user and let him choose whatever he wants to take this risk or not. Add the following code to your class/form to give him such choise. The good idea is to store his response in a local variable and use it to skip this warning in future requests.

 ServicePointManager .ServerCertificateValidationCallback = (s, cert, ch, er) =>
 {
     // Check is this case has been valuated:
      if  (Program .IsCertVerified)
         return  true ;
 
     if  (er == System.Net.Security.SslPolicyErrors .None)
         return  true ;
     else
      {
         // Warn user:
          if  (MessageBox .Show(String .Format("Certificate \\"{0}\\" could not be verified! Do you want to continue?" ,
             cert.Subject), "Certificate Warning" ,
             MessageBoxButtons .YesNo, MessageBoxIcon .Warning) == System.Windows.Forms.DialogResult .Yes)
         {
             // Set the local variable to skip this dialog:
              Program .IsCertVerified = true ;
             return  true ;
         }
         else
          {
             Program .IsCertVerified = false ;
             return  false ;
         }
     }
 };
 

Tags: | Categories: Code Snippets Posted by Vitaly Zayko on 7/18/2012 4:28 PM | Comments (0)

Most programmers who work with remote HTTP services prefer to use WebClient over WebRequest/WebResponse because of its simplicity. The only WebClient's feature I missed is ability to customize request timeout interval but fortunatelly it is very easy to fix by creating own class derived from WebClient. Here is how....

 public  class  WebClientEx  : WebClient
  {
     // Timeout in milliseconds
      public  int  Timeout { get ; set ; }
 
     /// <summary>
      /// Sets default timeout
      /// </summary>
      public  WebClientEx()
         : base ()
     {
         this .Timeout = 10000;
     }
 
     /// <summary>
      /// Sets custom timeout
      /// </summary>
      /// <param name="timeout">Timeout in milliseconds</param>
      public  WebClientEx(int  timeout)
         : base ()
     {
         this .Timeout = timeout;
     }
 
     /// <summary>
      /// Overriding base method to set timeout
      /// </summary>
      /// <param name="address">Server Url</param>
      /// <returns>A WebRequest with a timeout assigned</returns>
      protected  override  WebRequest  GetWebRequest(Uri  address)
     {
         WebRequest  wr = base .GetWebRequest(address);
         wr.Timeout = this .Timeout;
         return  wr;
     }
 }
 

Tags: , | Categories: Code Snippets Posted by Vitaly Zayko on 5/3/2012 9:44 AM | Comments (0)

As you know, any Windows Service operates under certain rights. It could be Network Service, Local System or a specific user. IIS process is not an exception. However, sometimes it is necessary to refer to the operating system using a different user account. In such cases your calls to the resources should be impersonalized. Below I'm glad to offer a way you can do it.

 class UserImpersonation : IDisposable
 {
     private bool disposed = false;
 
     [DllImport("advapi32.dll")]
     public static extern int LogonUser(String lpszUserName,
         String lpszDomain,
         String lpszPassword,
         int dwLogonType,
         int dwLogonProvider,
         ref IntPtr phToken);
 
     [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
     public static extern int DuplicateToken(IntPtr hToken,
         int impersonationLevel,
         ref IntPtr hNewToken);
 
     [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
     public static extern bool RevertToSelf();
 
     [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
     public static extern bool CloseHandle(IntPtr handle);
 
     const int LOGON32_PROVIDER_DEFAULT = 0;
     const int LOGON32_LOGON_INTERACTIVE = 2;
 
     WindowsImpersonationContext wic;
     string _userName;
     string _domain;
     string _passWord;
 
     public UserImpersonation(string userName, string domain, string passWord)
     {
         _userName = userName;
         _domain = domain;
         _passWord = passWord;
     }
 
     public bool ImpersonateValidUser()
     {
         WindowsIdentity wi;
         IntPtr token = IntPtr.Zero;
         IntPtr tokenDuplicate = IntPtr.Zero;
 
         if (RevertToSelf())
         {
             if (LogonUser(_userName, _domain, _passWord, LOGON32_LOGON_INTERACTIVE,
                 LOGON32_PROVIDER_DEFAULT, ref token) != 0)
             {
                 if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                 {
                     wi = new WindowsIdentity(tokenDuplicate);
                     wic = wi.Impersonate();
                     if (wic != null)
                     {
                         CloseHandle(token);
                         CloseHandle(tokenDuplicate);
                         return true;
                     }
                 }
             }
         }
         if (token != IntPtr.Zero)
             CloseHandle(token);
         if (tokenDuplicate != IntPtr.Zero)
             CloseHandle(tokenDuplicate);
         return false;
     }
 
     private void CleanUp(bool disposing)
     {
         if (!this.disposed)
         {
             if (disposing)
             {
                 if (wic != null)
                     wic.Dispose();
             }
 
             RevertToSelf();
         }
 
         disposed = true;
     }
 
     public void Dispose()
     {
         CleanUp(true);
         GC.SuppressFinalize(this);
     }
 
     ~UserImpersonation()
    {
        CleanUp(false);
    }
 }

And here is how to use this class:

 using (UserImpersonation user = new UserImpersonation(UserName, Domain, Password))
 {
     if (user.ImpersonateValidUser())
     {
         // Do your work here.
  }
     else
  {
         // Something goes wrong. Check it here.
  }
 
 }
 

Tags: | Categories: Code Snippets Posted by Vitaly Zayko on 4/30/2012 5:10 PM | Comments (0)

Geolocation manipulations become quite often programming task. Below is a simple function that calculated distance between two coordinates in kilometers. If you prefer miles, simply multiply results by 0.6214.

 public  static  double  GetDistance(double  Lat1, double  Lon1, double  Lat2, double  Lon2)
 {
     int  R = 6371;
 
     double  rLat1 = ToRadian(Lat1);
     double  rLat2 = ToRadian(Lat2);
 
     double  dLat = rLat2 - rLat1;
     double  dLon = ToRadian(Lon2 - Lon1);
 
     double  a = Math .Pow(Math .Sin(dLat / 2), 2) + 
         Math .Pow(Math .Sin(dLon / 2), 2) *
         Math .Cos(rLat1) * Math .Cos(rLat2);
 
     double  b = 2 * Math .Atan2(Math .Sqrt(a), Math .Sqrt(1 - a));
 
     return  R * b;
 }
 
 public  static  double  ToRadian(double  Grad)
 {
     return  Math .PI * Grad / 180;
 }
 

Enjoy!