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();
}
0a0f90a6-1dcf-4337-8c6d-d73f16ce6013|0|.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.
66eb7d14-deed-41f1-baca-cf2d4afa944c|0|.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:
ASP.NET MVC,
RESTful
88cbd550-99c3-49c1-930a-f48376486b9f|1|5.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.
a9e95bdc-5211-4c3c-92e8-4bd48b6b8142|0|.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:
silverlight,
wph7
0f687cc3-0312-435d-b5d7-f0acdf8e17d8|5|5.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.
7a971b73-00f2-46db-8b3c-e3ccddc8faa8|0|.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.
7d745302-c6c7-471e-a8b0-1b2a0adb569b|1|5.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);
57c3d67b-815d-4666-8464-b2d1aa8246b4|0|.0
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:
WPF,
Ribbon
feb9e8f5-593f-4ba7-b4f9-6aa68b5bfe4c|0|.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.

<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.


5944cc27-d395-4b9d-a084-5253856d5d27|1|5.0