Zayko in the Net

Personal blog of Vitaly Zayko

NAVIGATION - SEARCH

How to debug mobile web sites using IE9?

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.

How to convert an InputStream to String? (Java, Android)

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(); 
 }
 

WP7: Changing ApplicationBar visibility generates NullReference exception

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.

About using WCF RESTful services together with ASP.NET MVC projects

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: ,

Getting the Url to virtual root in ASP.NET (C#)

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:

How to Encrypt/Decrypt a String in Silverlight for Windows Phone 7?

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: ,

How to programmatically hide SIP (Software Input Panel - virtual keyboard) in Windows Phone 7?

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:

Adding a custom Http header to WCF request (C#)

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: ,

Flash a window in .NET (C#)

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: ,

 

Microsoft Ribbon for WPF (October 2010 update)

Now works with Visual Studo 2010 Express!

Other changes:

  • Ribbon Split Button is only half-highlighted when users mouse over the button
  • Ribbon Title is bottom-aligned, should be centered
  • Ribbon Quick Access Toolbar icons are clipped and top-aligned
  • Ribbon Contextual Tab header text is getting truncated if too long
  • Ribbon Gallery  Item does not stretch to fit its Parent Panel
  • Initial enabled state of Ribbon Split Menu Items can be incorrect if they have children
  • Ribbon Split Menu Item with sub-items is disabled if CanExecute=false
  • WPF Ribbon Dropdown does not close when CanAddToQuickAccessToolBarDirectly="False" was set at various level within the Ribbon
  • InvalidOperationException may occur when switching themes and the WPF Ribbon is Minimized
  • Ribbon Tab Header content may not appear when Ribbon starts out collapsed
  • RibbonTab.TabHeaderLeft & RibbonTab.TabHeaderRight are incorrect when Ribbon starts out hosted in a Collapsed control
  • Ribbon Tool Tip: Title and Footer Title gets clipped if the stringis too long
  • Vertical and horizontal alignments for the standard Ribbon controls should be centered, they were not.
  • After removing all items from the Quick Access Toolbar, phantom items remain visible
  • Right clicking on the System icon will not place the Context Menu properly
  • System Icon, Title and Quick Access Toolbar are not displayed correctly when Ribbon Windows is maximized
  • A minimized Ribbon will render on top of the window when a Popup is opened.
  • RibbonWindow.Icon does not pick appropriate small size icon from *.ico  Icon file.
  • IndexOutofRange Exception would pop when removing a Tab from an Observable Collection.
  • WPF Ribbon can use ClearType when targeting .NET Framework 4.0 control.

Click here to download.

Technorati Tags: ,