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!

Tags: , | Categories: General Posted by Vitaly Zayko on 2/24/2012 5:49 PM | Comments (0)

If you are a web developer who works on a mobile web site, you need to test look and feel of your job at least in major mobile OS. It’s easy if you optimize your site just for iOS or Android and you have these devices physically or their emulators. But in case you can’t, you can use desktop browsers to make this job done by using different user-agent strings. Safari already has something that helps; Chrome (as I heard) has command line switchers; Firefox – a plugin. But what about IE?

IE9 also includes dev tool as well: just press F12 key to bring it on. This is the place where we will put custom user-agent strings. So…

  1. Open up IE development tools by pressing F12 in IE9 main window. step-1
  2. Click menu Tools -> Change user agent string -> Custom…
  3. Put a Friendly Name that will help you to recognize this string. step-2
  4. Finally put user-agent string to “User Agent String” field and you are done!

Now every time when you will need to test your site with different browsers mode, simply go to IE dev mode (F12), click Tools -> Change user agent string and select a user-agent from the very bottom menu part. Of course, this way just emulate another browser but script and rendering engines will stay the same but this realy helps especially when you need to debug your site when logic is depended from browser that connects to.

When you played enough with custom string, just close IE – user-agent string will return to default, no manual changes required.

Just one thing we left: where to get browser agent strings? I found many sites in the Internet which spread this data and this one is a good example.

Tags: , | Categories: Code Snippets Posted by Vitaly Zayko on 12/16/2011 1:25 PM | Comments (0)

If you call a Web service from your Android App (I believe this should work in other Java Apps as well but personally tested in Android), you probably will want to convert InputStream into a string which is not that simple. And here is simpliest way how to do that:

 HttpURLConnection conn = (HttpURLConnection)url.openConnection();
 if(conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
 	InputStream inStream = new BufferedInputStream(conn.getInputStream());
     // Here are we go:
  String res = new Scanner(inStream).useDelimiter("\\\\A").next(); 
 }
 

Tags: | Categories: Code Snippets Posted by Vitaly Zayko on 6/6/2011 7:01 PM | Comments (0)

Faced an interesting problem: when I want to change ApplicationBar visibility by by changing instance IsVisible property, I always get NullReference exception. To avoid this use static member instead:

 ApplicationBar.IsVisible = true;

Guess why? Because ApplicationBar is not a Silverlight element and general behavior doesn’t apply to it.

Update: the same happens when you want to add/remove a button – so use static Button property.

Tags: , , | Categories: Code Snippets Posted by Vitaly Zayko on 4/27/2011 7:47 PM | Comments (0)

When you gonna run an WCF REST service within an MVC project, you may noticed that you need to add this service to MVC routing table in Global.asax.cs file. By default it is suggested to be like this:

 routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 
 routes.Add(new ServiceRoute("MyRest", new WebServiceHostFactory(), typeof(MyRest)));
 
 routes.MapRoute(
     "Default", // Route name
     "{controller}/{action}/{id}", // URL with parameters
     new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
 );
 

But in this case each of your ordinary MVC Action Url will be replaced to this: /MyRest?action=Index&controller=Home which won’t work. If you put REST route to the bottom of RegisterRoutes procedure, your service will become unavailable and you’ll get 404 “Not Found” when you try to call it. Sounds like order does matter.

So the only way is to map all your routes together at the same time. Here is how your RegisterRoutes should look like:

 routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 
 routes.MapRoute(
     "Default", // Route name
     "{controller}/{action}/{id}", // URL with parameters
     new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
     new { controller = "^(?!MyRest).*" }
 );
 
 routes.Add(new ServiceRoute("MyRest", new WebServiceHostFactory(), typeof(MyRest)));
 

Quite tricky and not obvious at least to me. Have fun coding!

Technorati Tags: ,

Tags: , | Categories: Code Snippets Posted by Vitaly Zayko on 4/26/2011 8:48 PM | Comments (0)

Use this snippet when you need to get an Url to virtual root path in your ASP.NET projects. You may need this, for example, when you want to call dynamically a REST Web service which is part of the same project (my story). I have found few ways to do this including storing such kind of info in Web.config file. But below is more short and convenient way. Just don’t forget to add trailing slash to the end because this function doesn’t do it by its self.

 string baseUrl = Request.Url.GetLeftPart(UriPartial.Authority);

Hope this helps.

Technorati Tags: