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:
Tags: , | Categories: Code Snippets Posted by Vitaly Zayko on 1/15/2011 4:55 PM | Comments (0)

Although Windows Phone 7 Apps keep their data in an isolated storage which is not easy find outside of Application, I still prefer to keep all sensitive data (such as user names/passwords etc.) encrypted so they won’t be compromised in case if the phone will be lost or stolen.

This function encrypt a string using given password and salt:

 /// <summary>
 /// Encrypt a string using AES
 /// </summary>
 /// <param name="Str">String to encrypt</param>
 /// <param name="Password">Encryption password</param>
 /// <param name="Salt">A salt string</param>
 /// <returns>Encrypted string in case of success; otherwise - empty string</returns>
 public  static  string  EncryptString(string  Str, string  Password, string  Salt)
 {
     try
      {
         using  (Aes  aes = new  AesManaged ())
         {
             Rfc2898DeriveBytes  deriveBytes = new  Rfc2898DeriveBytes (Password, Encoding .UTF8.GetBytes(Salt));
             aes.Key = deriveBytes.GetBytes(128 / 8);
             aes.IV = aes.Key;
             using  (MemoryStream  encryptionStream = new  MemoryStream ())
             {
                 using  (CryptoStream  encrypt = new  CryptoStream (encryptionStream, aes.CreateEncryptor(), CryptoStreamMode .Write))
                 {
                     byte [] utfD1 = UTF8Encoding .UTF8.GetBytes(Str);
                     encrypt.Write(utfD1, 0, utfD1.Length);
                     encrypt.FlushFinalBlock();
                 }
                 return  Convert .ToBase64String(encryptionStream.ToArray());
             }
         }
     }
     catch
      {
         return  "" ;
     }
 }
 

And this one – decrypt your data back:

 /// <summary>
 /// Decrypt encrypted string
 /// </summary>
 /// <param name="Str">Encrypted string</param>
 /// <param name="Password">Password used for encryption</param>
 /// <param name="Salt">Salt string used for encryption</param>
 /// <returns>Decrypted string if success; otherwise - empty string</returns>
 public  static  string  DecryptString(string  Str, string  Password, string  Salt)
 {
     try
      {
         using  (Aes  aes = new  AesManaged ())
         {
             Rfc2898DeriveBytes  deriveBytes = new  Rfc2898DeriveBytes (Password, Encoding .UTF8.GetBytes(Salt));
             aes.Key = deriveBytes.GetBytes(128 / 8);
             aes.IV = aes.Key;
 
             using  (MemoryStream  decryptionStream = new  MemoryStream ())
             {
                 using  (CryptoStream  decrypt = new  CryptoStream (decryptionStream, aes.CreateDecryptor(), CryptoStreamMode .Write))
                 {
                     byte [] encryptedData = Convert .FromBase64String(Str);
                     decrypt.Write(encryptedData, 0, encryptedData.Length);
                     decrypt.Flush();
                 }
                 byte [] decryptedData = decryptionStream.ToArray();
                 return  UTF8Encoding .UTF8.GetString(decryptedData, 0, decryptedData.Length);
             }
         }
     }
     catch
      {
         return  "" ;
     }
 }
 

Technorati Tags: ,

Tags: | Categories: Code Snippets Posted by Vitaly Zayko on 1/8/2011 3:08 PM | Comments (0)

If you ever programmed for Windows Mobile 6.x OS and earlier, you should be noticed that SIP supports Hide/Show methods when you would like to rise up or close its virtual keyboard. For a whatever reason the modern Microsoft OS doesn't support such operation directly but as always there is a way around: just move input focus to somewhere else, for example to the page:
this.Focus();
and SIP will be closed immidiately.

Technorati Tags:
Tags: | Categories: Code Snippets Posted by Vitaly Zayko on 11/23/2010 10:48 PM | Comments (0)

I was looking for a snippet to add a custom header to WCF service request. Why? For example, to add authentication header to add Basic Authentication support. (Yes – WCF supports Basic Authorization by itself but didn’t find how to use it without SSL).

Here is the shortest way.

Use this snippet on your client side:

 using  (MyServ.ServiceClient  proxy = new  MyServ.ServiceClient ())
 {
     using  (new  System.ServiceModel.OperationContextScope (proxy.InnerChannel))
     {
         MessageHeader  head = MessageHeader .CreateHeader("Authorization" , "http://mynamespace.com/v1" , data);
         OperationContext .Current.OutgoingMessageHeaders.Add(head);
     }
 }
 

And just in case, here is how to retrieve this information from Http header on the server side:

 string  auth = OperationContext .Current.
     IncomingMessageHeaders.
     GetHeader<string >("Authorization" , "http://mynamespace.com/v1" );
 

More about OperationContextScope Class here.

Technorati Tags: ,
Tags: | Categories: Code Snippets Posted by Vitaly Zayko on 11/5/2010 3:48 PM | Comments (0)

For a reason .NET lacks FlushWindowEx function so glad we can PInvoke it.

Declare FlushWindowEx and its dependencies:

 [StructLayout (LayoutKind .Sequential)]
 public  struct  FLASHWINFO
  {
     public  UInt32  cbSize;
     public  IntPtr  hwnd;
     public  Int32  dwFlags;
     public  UInt32  uCount;
     public  Int32  dwTimeout;
 }
 
 [Flags ]
 public  enum  FlashMode
  {
     FLASHW_STOP = 0,
     FLASHW_CAPTION = 1,
     FLASHW_TRAY = 2,
     FLASHW_ALL = (FLASHW_CAPTION | FLASHW_TRAY),
     FLASHW_TIMER = 4,
     FLASHW_TIMERNOFG = 12
 }
 
 [DllImport ("user32.dll" )]
 static  extern  Int32  FlashWindowEx(ref  FLASHWINFO  pwfi);
 

then just call it like this:

 FLASHWINFO  fw = new  FLASHWINFO ();
 fw.cbSize = Convert .ToUInt32(Marshal .SizeOf(typeof (FLASHWINFO )));
 fw.hwnd = this .Handle;
 fw.dwFlags = (Int32 )FlashMode .FLASHW_ALL;
 fw.uCount = 5;
 FlashWindowEx(ref  fw);
 

 

Technorati Tags: ,

 

Tags: | Categories: Code Snippets Posted by Vitaly Zayko on 10/22/2010 5:47 PM | Comments (0)

Playing with most recent Windows Phone 7 Tools I found that custom icons don’t appear in emulator by default although they exist in a solution.

wp7_no_icons

 <shell:ApplicationBarIconButton IconUri="/Images/add.png" Text="Add" Click="AddClick" />
 <shell:ApplicationBarIconButton IconUri="/Images/remove.png" Text="Remove" Click="RemoveClick"/>

This happens because pictures adding with “Resource” as default build action. To make this work, select your recently added picture in Solution Explorer, switch to Properties and change Build Action to “Content”. After recompiling you will get your icons in place.

vs_menuwp7_with_icons

Technorati Tags:
Categories: Code Snippets Posted by Vitaly Zayko on 10/20/2010 1:57 PM | Comments (0)

I'm pretty sure you all noticed that when you move your cursor under an App in Windows 7 Task bar, small window copy (aka Thumbnail) appear and there are small buttons on some windows could be attached. Good examples are Windows Media Player or WinAmp.

Windows Player Thumbnail with buttons on it

There is a good reason to put such buttons there: using them you can manage this Application without necessity to open its window.
Here is how to add this functionality to your own WPF App.
Add reference to TaskBatItemInfo just like we did to add progress bar in this post.
Add references to ThumbButtonInfo, so you will see something like this:

 <Window.TaskbarItemInfo>
     <TaskbarItemInfo>
         <TaskbarItemInfo.ThumbButtonInfos>
             <ThumbButtonInfo ImageSource="/IconProgressDemo;component/Icon1.ico" Description="Play!" Click="ThumbButtonInfo_Click" />
             <ThumbButtonInfo ImageSource="/IconProgressDemo;component/Icon2.ico" Description="Stop!" Click="ThumbButtonInfo_Click" />
         </TaskbarItemInfo.ThumbButtonInfos>
     </TaskbarItemInfo>
 </Window.TaskbarItemInfo>
 

Now just handle Click event in way you want and you done!

 private  void  ThumbButtonInfo_Click(object  sender, EventArgs  e)
 {
     MessageBox .Show((sender as  System.Windows.Shell.ThumbButtonInfo ).Description);
 }
 
Technorati Tags: ,,