post

Return additional info to the client using OAuth bearer tokens generation and Owin in WebApi

I am currently implementing token based authentication using ASP.Net Web Api 2, Owin and Identity. The client is implemented using ExtJS framework, and the login form itself (Ext.form.Panel) is requesting additional info in order to recognize if the action was successful. The additional info is consisted of one property named “success” whose value (true/false) is used to fire a proper event handler (success or failure);

In order to accomplish this task, one must adjust his OAuthAuthorizationServerProvider implementations GrantResourceOwnerCredentials method by creating additional AuthenticationProperties.

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{

context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

using (AuthRepository _repo = new AuthRepository())
{
IdentityUser user = await _repo.FindUser(context.UserName, context.Password);

if (user == null)
{
context.SetError("Invalid grant", "The user name or password is incorrect.");
return;
}
}

var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("sub", context.UserName));
identity.AddClaim(new Claim("role", "user"));

//added success parameter so that Ext.JS form can recognize action as successful
var props = new AuthenticationProperties(new Dictionary<string, string>
{
{
"success", "true"
}
});

var ticket = new AuthenticationTicket(identity, props);
context.Validated(ticket);

}

Additionally, you have to make sure that you override TokenEndPoint method to get those properties as a response when you obtain the token successfully. Without this end point the properties will not return in the response. Notice that i have removed all parameters with name that starts with dot so that “.expires” and “.issued” do not get added to the response (i do not need them).

public override Task TokenEndpoint(OAuthTokenEndpointContext context)
{
foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
{
//removed .issued and .expires parameter
if (!property.Key.StartsWith("."))
context.AdditionalResponseParameters.Add(property.Key, property.Value);
}

return Task.FromResult<object>(null);
}

That’s it. Hope it helps. Happy coding!

post

Download images from web using PowerShell script

So today I had to fetch some images from the certain website and save them in the dynamically generated folders. The image names were easily constructed from the ordinal number of the image so i thought i should create a small PowerShell script. I had to go with the PowerShell because the plain batch (.bat) script does not support wget command out of the box.

The image names were in the form 001s.jpg… 012s.jpg .. 123s.jpg so i had to build the filename first (with leading zeroes), and the other catch was that they had to be saved in the directory that is constructed using their ordinal number (and created before the fetch), and filename had to be “thumb.jpg”.

for($i=1; $i -le 143;$i++){
 $url = ("{0}{1}{2}" -f "https://www.youwebsitepath.com/Pics/", $i.ToString("d3"), "s.jpg")
 $dirname = ("{0}{1}" -f "C:\Users\yourusername\thumbs\thumbfolder ",$i.ToString())
 $dest = ("{0}{1}{2}" -f $dirname,"\","thumb.jpg")
 mkdir $dirname
 wget $url -OutFile $dest
}

Hope it helps,

Regards

 

Import shapefiles into SQL Server

Here’s a little tool for you that I’ve been using quite often lately. It can be used used to import Esri shapefiles into Microsoft SQL Server (2008 and 2012) while taking into account character encoding of the input data. The geospatial information is stored as SqlGeometry.
Import shape file to SQL Server
Nice thing about it is that it allows you to rename/remap destination table column names, choose the destination table name, and set the primary key for the table. And yeah, it has a user interface 🙂
The app is rather simple so I don’t think that further explanation about its usage is needed. If it turns out that I’ve been wrong, don’t hesitate to leave a comment.
I would  like to point out one thing though. If you are not sure which encoding codepage to use, check this link and look it up. The codepage default is 65001, which is the code page for UTF-8 encoding.
If you have any suggestions about improving the tool, or find a bug or something, leave a comment, I will be glad to update it.
Download exe from my Google Drive

EDIT: As there is some interest in this small app, and various different exceptions are thrown for different users, i am providing you with the source code so that you can see what is actually the problem. I was too lazy to catch every exception in the original program and were always returning the same message when the error occurs. The source code is hosted on GitHub, so that you can pull it or download as Zip.
If you update the code, please take time to push your changes back and help me update this small tool.

Modifying the previously released WP 7.0 version of the app is not possible once the Mango version is released!

Recently the folks from MS answered a very frequently asked question, and their answer is copied below. 

When you publish a Windows Phone ‘Mango’ update to an application you had previously published, the following will occur:
  • The WP 7.0 version of your application will remain available to all users on WP 7.0 devices.
  • The WP ‘Mango’ version of your application will be available to all users on WP ‘Mango’ devices.
  • WP ‘Mango’ users who previously installed your application will receive an update notification. This will occur even if they installed your application prior to updating to WP ‘Mango’
  • WP 7.0 users who have installed your application, but not updated to WP ‘Mango,’ will not receive an update notification.
  • The WP7.0 rankings & reviews that your application received will attach to your new updated WP ‘Mango’ version too.
  • The application metadata and screenshots for Windows Phone Marketplace submitted with the WP ‘Mango’ version of your application will be shared across both the WP 7.0 and WP ‘Mango’ versions of the application; i.e., a single set of metadata and screenshots will appear to both WP 7.0 and WP ‘Mango’ users.
  • Once you have released the WP ‘Mango’ version of your application, you will no longer be able to modify the previously released WP 7.0 version of your app. We realize that some of you may worry about this limitation, and so we’re actively working on ways to mitigate it. To improve the experience for users, it’s our preference not to have “duplicate versions” of your apps in the marketplace. We are also going to work hard to encourage our pre-existing users to enjoy the free upgrade to Mango as quickly as possible.
 
 
As you can see, we have a problem here! There is no way to update a pre-mango release after you have released the mango update! Since the majority of users still haven’t updated to Mango there is a need for frequent update of the pre-mango versions.
There is a workaround though, you can publish the pre-mango app which is using mango components if the app detects that the mango is available on the phone! This is done using the reflection, so if you are interested, knock yourselves out! Read more about it! 

Brush object serialization and Isolated Storage

You probably already know that you cant serialize Brush objects using Isolated storage default serialization engine, so there are a few ways you can overcome this simple problem. There are a few approaches to solving this problem and some of them include serialization of brushes Argb byte values, or brush Color values. I’m gonna show you how to create a simple serializable class in order to overcome this problem by serializing brushes Color.

using System.Windows.Media;
using System.Runtime.Serialization;

namespace TheTime.Model
{
    [DataContract]
    public class BindableBrush
    {
        private string _brushName;
        /// <summary>
        /// Initializes a new instance of the BindableBrush class.
        /// </summary>
        public BindableBrush(Color c, string name)
        {
            Color = c;
            _brushName = name;
           
        }

        [DataMember]
        public Color Color
        { get; set; }


        public SolidColorBrush Brush 
        {
            get
            {
                return new SolidColorBrush(Color);
            }
            set
            {
                Color = value.Color;
            }
        }

        [DataMember]
        public string BrushName
        {
            get
            {
                return _brushName;
            }
            set
            {
                _brushName = value;
            }
        }
    }
}

This simple solution serializes the Color object and creates a SolidColorBrush on request. Using this class you can bind to the Brush property without any problem…

Hope it helps!

Hiding the Windows Phone 7 keyboard (SIP) when enter key is typed

There is only one way to close the SIP (Soft Input Panel) by default in Windows Phone 7, and it is by changing focus from the TextBox that is being edited to something else on the screen. As an android user, I am used to close it by hitting the enter key once the text editing is done so I’m gonna show you how to do it and hope it will become a practice.
What we need to do here is change the focus to something other than the TextBox we are currently editing, and for that purpose the PhoneApplicationPage that contains this TextBox will do just fine. All we have to do first is make this page a TabStop so we can enable it to recieve the focus.

<phone:PhoneApplicationPage 
x:Class="PanoramaPivotControls.SettingsPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
IsTabStop="True">

...

</phone:PhoneApplicationPage>

Next thing to do is add the KeyUp event handler to the TextBox and implement it.

<TextBox KeyUp="TextBox_KeyUp">

 

private void TextBox_KeyUp(object sender, KeyEventArgs e)
{
     if (e.Key == Key.Enter)
     {
         this.Focus();
     }
}

 

And that’s it! The SIP is now closed when Enter key is typed in!

Hope you find it useful..

Disabling Windows Phone 7 lockscreen aka Idle detection

Ready for another really useful code snippet? 😀

This time its few lines about the prevention of the lockscreen appearance. Everyone knows about it, but not everyone is really sure how to use it and what are the consequences of its use.

First things first, lets learn how to use it.


Everything we need here is only one property, the UserIdleDetectionMode of the current phone application service. It can be set to either enabled or disabled, and is always recommended to store its current state before you change it, so that you can set it back to whatever value it had before you started messing with it. This is best done  by using a private variable in your App.xaml.cs. Launching and activating events should be used to store the original setting prior changing it to the mode you want, and deactivating and closing events for setting the original setting back.

 

private void Application_Launching(object sender, LaunchingEventArgs e)
{
    _originalMode =PhoneApplicationService.Current.UserIdleDetectionMode;
    PhoneApplicationService.Current.UserIdleDetectionMode= IdleDetectionMode.Disabled;
}

private void Application_Activated(object sender, ActivatedEventArgs e)
{
    _originalMode = PhoneApplicationService.Current.UserIdleDetectionMode;
   PhoneApplicationService.Current.UserIdleDetectionMode= IdleDetectionMode.Disabled; 
}

private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
   PhoneApplicationService.Current.UserIdleDetectionMode = _originalMode ;
}

 private void Application_Closing(object sender, ClosingEventArgs e)
{
    Microsoft.Phone.Shell.PhoneApplicationService.Current.UserIdleDetectionMode = _originalMode ;
}

And that’s it.. I’ve set the mode to disabled in the code snippet but you could set it to enabled it it suits your needs..

In the end, it is important to be very careful with switching this property of, as it could drain your battery in matter of hours as your app will never be deactivated by a lockscreen.. please take some time to examine the important notes on this page before you start playing with it.