Pages

Thursday, December 27, 2012

Open Explorer from command console or powershell

I was reading this post about how to open command line from an explorer window at the same path. This is very helpful to speed up works a little bit.

In order to open command line in current directory you just need to type 'cmd' in address bar. Also you can type 'powershell' if you need powershell.

However, in reverse if you want to open windows explorer from command line this is what you need to type in command line:

explorer .

note that if you miss explorer then it will open your user's documents folder.
And for powershell the command is:

ii .

note: ii is alias for invoke-item.


Friday, December 7, 2012

Introduction to DotNetAuth

Recently I have been working on implementation of OAuth protocol. The outcome was not that much bad, so I decided to make it available for others to use it free. Although I am still working on its features, it is fully functional. I have used it in several of my projects.

OAuth protocol is a protocol which is implemented by a lot of famous social networks and is the fundamental key to working with most of their APIs, specially to access to methods which requires some of identity of the requester. So if you want to integrate your website with Facebaook or Google Plus or LinkedIn etc probably your first step would be to handle OAuth protocol.

Also it is a common practice to use OAuth for authenticating user's in your website. Instead of the classic set of username/password credentials, you can simply deliver the user identification to these social networks and ask for user's primary set of information like name, date of birth, gender etc through their API.

OAuth protocol is a complete protocol as it considers all the parties(one which needs to authorize, one which need to make an authorized request, end user who authorizes) and all common scenarios in ways of communication between parties.

DotNetAuth is a an implementation of the OAuth protocol which only supports the consumption of protocol, and it is only for server side flow. So if you are the developing a website which wants to makes user-authorized requests to social network sites like Facebook or Google API this library is for. Also this library helps you take advantage of the OAuth protcol to identify users of your website and use OAuth for user membership(sign up, sign in features).

Source Code:
https://bitbucket.org/samnaseri/dotnetauth

Nuget Packages:

Install-Package DotNetAuth
Install-Package DotNetAuth.Profiles


Asp.Net MVC Sample:
This is just a sample to show what it would look like.
Just add above packages and then you can have the following methods in your ProfileController:

public class ProfileController : Controller
{
    ProfileProperty[] requiredProperties = new[] { ProfileProperty.Email, ProfileProperty.DisplayName, ProfileProperty.UniqueID, ProfileProperty.DisplayName };
    // GET: /Profile/
    [HttpGet]
    public ActionResult Index()
    {
        return View();
    }
    public RedirectResult Login()
    {
        var userProcessUri = Url.Action("Callback""Profile"null, protocol: Request.Url.Scheme);
        var provider = LoginProvider.Get(LoginProviderRegistry.Facebook.Fullname);
        var authorizationUrl = DotNetAuth.Profiles.Login.GetAuthenticationUri(provider, new Uri(userProcessUri), new DefaultLoginStateManager(Session), requiredProperties);
        authorizationUrl.Wait();
        return Redirect(authorizationUrl.Result.AbsoluteUri);
    }
    // GET: /Process
    [HttpGet]
    public ActionResult Callback(string providerName)
    {
        var userProcessUri = Url.Action("Callback""Profile"null, protocol: Request.Url.Scheme);
        var provider = LoginProvider.Get(LoginProviderRegistry.Facebook.Fullname);
        var profile = DotNetAuth.Profiles.Login.GetProfile(provider, Request.Url, userProcessUri, new DefaultLoginStateManager(Session), requiredProperties);
        profile.Wait();
        return Content(profile.Result.ToString());
    }
}

And that's it.

Friday, November 30, 2012

Bundling using Cassette in Asp.Net MVC

I am a big fan of Cassette library. It is an ending to lots of problems you will face in managing your web application scripts and style sheets. Basically what it does is serving JavaScript files and CSS files in a much more efficient and manageable way.

In short these are benefits of using Cassette:
  • bundling assets
    • multiple files concatenation into single file, so fewer HTTP requests
    • reference management
    • avoiding including unnecessary assets in a page 
  • performance improvements
    • assets auto versioning and caching 
    • performance achievements through caching 
    • HTTP compression
  • good transforms
    • script minification
    • support for CoffeeScript
    • support for SASS 
    • support for LESS 
    • support for hogan html templates which means precompiled html templates 
    • embedding small images into CSS files 
  • a little bit of access control over script files. 
  • debug friendly
Although Cassette is for both JavaScript and style sheets, if you do it for JavaScript files the same process is for style sheets and HTML templates. So, let start by JavaScript files.

Setting up the Cassette in your web project

First of all we need to do a little work to make Cassette features working in our web projects.

The automatic way:

Using nuget package, just run the following command:
install-package cassette.aspnet

The manual way:

You may be a control freak like me, I need to do the things manually in order to make sure that I do know what is happening in my web application, and hence I know what is wrong in case of a failure.

So here are the things that should be done to make Cassette working:
  1. Configuring web.config to 
    1. add required HTTP module and HTTP handler 
    2. add Cassette.Views to razor page namespaces, you have to do this step for areas manually, even if using nuget package. 
  2. Adding CassetteConfiguration class 
  3. Add references to required assemblies:
    • Cassette
    • Cassette.Views
    • Cassette.Aspnet
    • AjaxMin
      For all the features:
    • Cassette.CoffeeScript
    • Cassette.Sass
    • Cassette.Hogan
    • IronRuby
    • IronRuby.Libraries
    • IronRuby.Libraries.Yaml
    • Jurassic
This is the HTTP module you need to add to configuration>system.web>httpModules:

<add name="CassetteHttpModule" type="Cassette.Aspnet.CassetteHttpModule, Cassette.Aspnet" />
You may add the same to configuration>system.webServer>httpModules.


This is the HTTP handler you need to add to configuration>system.web>httpHandlers

<add name="CassetteHttpHandler" path="cassette.axd" preCondition="integratedMode" verb="*" allowPathInfo="true" type="Cassette.Aspnet.CassetteHttpHandler, Cassette.Aspnet" />
You may add the same entry to  configuration>system.webServer>httpHandlers.

And you have to include Cassette.Views in configuration>system.web>pages>namespaces:

<add namespace="Cassette.Views" />
If you are using Asp.Net MVC Areas, Add the above namespace to every area's web.config.

How to implement Cassette

Simply there is only three steps:
1. create bundles to bundle a set of scripts together by writing the following line in CassetteConfiguration:

bundles.Add<ScriptBundle>("lib/js");
This will create a bundle named lib/js which bundles all files in lib/js folder.

2. reference bundles to specify which script is required in your razor page by writing:

Bundles.Reference("lib/js");
It records a flag that bundle lib/js should be rendered when rendering scripts.

3. create the script tag(s) to load all the referenced libraries. in your razor page you write:

@Bundles.RenderScripts();
It renders all the so far mentioned bundles into one or several script tags.

Step 1. Creating and configuration of bundles

In step one you specify which files to be included in a bundle called "lib/js", you may also specify more advanced setting for bundle, like how to search for files, which files should be ignored, etc.

When bundling you specify a folder path, then according to some rules, script files within that path will be added to the bundle. Default rules exclude -vsdoc.js files and also if alternative .min or .debug file exists, then only one file is picked.

Step 2. Adding references to scripts

In step two you only mention that the specified bundle is required, you can do this 'referencing bundles' anywhere, it could be the layout page, a partial view. So you ask for a bundle to be included only when it is required and at the place that requirement is raised. For example you have a partial view that requires a specific script, so you add a reference to that script in that partial view. Assuming that no other view or partial view has a demand for that script, then that script only will be loaded for pages which contains that partial view.

The reference you specify is a bundle path. So if you write @Bundles.Reference("X") then you should have bundles.Add("X") in your Cassette configuration, or you should have a bundles.Add("Y") where X can be find in Y.

Step 3. Rendering the actual script tags

In step three you actually create script tags. So the bundles you have mentioned so far using the @Bundles.Reference will be rendered into one or multiple script tags. If your compliation debug attribute is set to true, then Cassette does not join scripts and does not minify them, so you still can debug your scripts. In contrast, if debug="false", then Cassette concatenates scripts files into a single file and also minifies them.

It may be a little bit confusing, at least it was for me. As I described it here, the step one may seems unnecessary, but you should note that in step two "lib/js" does not refer to a scripts folder, but it is referring to the bundle we created at step one.

Rendering script tags is where you get the point of Cassette, the way that Cassette renders script tags and brings scripts into your page has several benefits. But before going forward to discuss the benefits, first let me describe some facts about how Cassette works, so then I can tell how those benefits are achieved.

  1. Cassette exposes a HTTP handler for sending back scripts to client.
  2. Cassette computes a hash for each bundle. If the scripts change, the hash value will change.
  3. Cassette will return a bundle even if you asked for a single script file. For example you asked for "lib/js/MySpecificLib.js", then Cassette will return bundle "lib/js".
  4. Cassette will include dependencies and order scripts based on their dependencies.

So the benefits are:

 - You can prevent direct access to your script libraries. So if you are using Cassette for all your resources  then you may restrict direct access to libraries folder.

 - Unless you created a bundle you can not reference to a script file. So there is a limited number of bundles all defined in CassetteConfiguration class. Each bundle is accessed via Cassette's HTTP handler and has a URL which is consisted of bundle's hash. So if you change the scripts then the hash changes and the URL changes, so the browser would not use the cached version and hence you forced browser to fetch the new version of bundle. And as long as the scripts are the same you can rely the browser caching. Here I have to point out an important guideline: put third parties libraries and your own libraries in different bundles, because they have different change frequencies  Your app's scripts change more often, so they bundle need to be reloaded more often.

 - When referencing you can be specific about exactly which scripts you need, you don't have to mention the bundle itself. If you specify a script file instead of a bundle, then cassette will render a script tag pointing to any bundle which contains that file, chances are that file already has been loaded once. However because you specified the file name rather than the bundle name, you can move that file to another bundle, for example make your bundles more granular and specific, without being worried about places which that bundle was referenced.

 - You only need to reference the scripts you directly need, you don't need to be worried about if you have included the required libraries which your scripts requires.

 - One important thing you should know is that the way script tags are rendered is dependent on compilation debug attribute. If it's value is true, Cassette will generate debug friendly script tags and script files are rendered as it is. In contrast, if debug value is false, then Cassette will generate efficient script tags and script files are concatenated and minified.

 - Probably you are using layout pages in a way that your pages are not concerned with the head section of html. Using Cassette you render scripts only in layout page and then reference the bundles in page whenever they are required, so when each page is served the scripts(bundles) related to that specific page is rendered.

Note: For simplicity, I have written this article for scripts. However the same story happens for style sheets, the only difference is that instead of ScriptBundle you use StylesheetBundle. And instead of @Bundles.RenderScripts() you will write @Bundles.RenderStylesheets() .

Targeted Bundles

When defining a bundle you can restrict it to a specific target. Actually, the Cassette itself referes to it as PageLocation, however you can use this feature beyond page location, so I named it targetted bundling.

Thursday, November 29, 2012

A behavior to keep DataGrid's SelectedItem into View

The following simple behavior will forces a DataGrid to keep its SelectedItem into view. The way that it works is simply hooking SelectionChanged event and calling DataGrid.ScrollIntoView method.



An advice : Remove code behind files in WPF

In WPF when using MVVM it is better to delete the code behind file straight away. Those almost empty code files are not necessary at all and the project will compile without them. Moreover, if you have removed the code behind file an press F7 key, then nothing happens. It matters to me because I have a habit to press F7 to navigate to code related to XAML, and doing so it always opens code behind file which is not desired.

Tuesday, August 7, 2012

Meetup Invalid Authorization request

Trying to connect to Meetup.com API using OAuth2.0 I had a problem which I find out this is not documented in their API documentation.
The redirect_url parameter is case sensitive. So if this is the case then you will recieve the error message :


Invalid Authorization request

If you were directed here by another application, contact its developer


So make sure that the redirect uri of your application defined at http://www.meetup.com/meetup_api/oauth_consumers/ exactly(case wise) matches the redirect_uri parameter you pass in your authorization request.

Monday, April 23, 2012

Automata and Compilers courses from coursera

I did write ve parser without any technical knowledge about parsing algorithms, I always wanted to improve my knowledge in this area and now I have the chance to do it.
I am very excited to start two online free courses today. These courses are Automata and Compilers.

There are some other computer science courses available on coursera.org. Have a look at it, there is also courses in other fields.

Thursday, March 29, 2012

WPF Grid Layout Simplified Using Rows and Columns Attached Properties

A major problem with WPF and XAML is that XAML code tends to be very cluttered and after a little your XAML code gets too much complicated. In a recent project I suggested to define new controls by deriving from existing controls, so you can assign a shorter name to them or avoiding setting the same property the same value for thousand of time(e.g. Horizontal orientation stack panel).

Here is another tip to make you XAML code less cluttered. One area that you may find it hard to write and read and maintain is Grid layout control. Defining RowDefinitions and ColumnDefinitions waste too much space and adds too unnecessary lines of code. Hence it become too complicated to handle it.
The solution I am sugessting here is to use some attached properties to define RowDefinitions and ColumnDefinitions in a smarter way.
You can fetch the code for attached properties here: https://gist.github.com/2234500
This code adds these attached properties to Grid

  • Grid.Rows
  • Grid.Columns

and adds these attached properties to UIElemnet

  • Cell

Grid.Rows and Grid.Columns are same thing but one is for specifying rows and one is for columns. These two properties are simply text value which you can set it according to the following Rules:
  • Separate items with semi colon(;) , Example "auto;auto;*"
  • Use auto for adding an Auto sized row or column , Example "auto;auto"
  • Specify * for adding an star sized row or column, Example "1*,2*, *"
  • Specify only a number for adding a fixed size row or column, Example "200,200,100"
  • Append # followed by a number to add multiple rows and columns of same sizing. "1*#4,auto"
  • The number of starts in an item will multiplies star factor. Example "**,***,*" instead of "2*,3*,*"

XAML Sample:

<Grid s:Grid.Rows="auto;1*;auto;auto" s:Grid.Columns="*#5;auto"> ... </Grid>

Adds 4 rows to grid which are all Auto sized except the second row which occupies all remained space. Also adds 5 star columns followed by an Auto sized column.
Implementaion
As I said this is simply 3 attached properties which allows you to specify the rows and columns using a textual representation. Here is the function which converts the textual value into a GridLength value:

public static GridLength ParseGridLength(string text)
{
    text = text.Trim();
    if (text.ToLower() == "auto")
        return GridLength.Auto;
    if (text.Contains("*"))
    {
        var startCount = text.ToCharArray().Count(c => c == '*');
        var pureNumber = text.Replace("*""");
        var ratio = string.IsNullOrWhiteSpace(pureNumber) ? 1 : double.Parse(pureNumber);
        return new GridLength(startCount * ratio, GridUnitType.Star);
    }
    var pixelsCount = double.Parse(text);
    return new GridLength(pixelsCount, GridUnitType.Pixel);
}

And here is the function which makes # operator working:

public static IEnumerable<GridLength> Parse(string text)
{
    if (text.Contains("#"))
    {
        var parts = text.Split(new[] { '#' }, StringSplitOptions.RemoveEmptyEntries);
        var count = int.Parse(parts[1].Trim());
        return Enumerable.Repeat(ParseGridLength(parts[0]), count);
    }
    else
    {
        return new[] { ParseGridLength(text) };
    }
}

And finally the attached property change callback:

var grid = d as System.Windows.Controls.Grid;
var oldValue = e.OldValue as string;
var newValue = e.NewValue as string;
if (oldValue == null || newValue == null)
    return;
 
if (oldValue != newValue)
{
    grid.ColumnDefinitions.Clear();
    newValue
        .Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
        .SelectMany(Parse)
        .Select(l => new ColumnDefinition { Width = l })
        .ToList().ForEach(grid.ColumnDefinitions.Add);
}

The above code is for Columns attached property but this is the same for Rows attached property as well.

The whole source code for these attached properties:

Tuesday, March 27, 2012

GitHub Gist

Love sharing? Are you a social coder? A lot of times you may wanted to share piece of code but you give up just because it was going to be a cumbersome process to create a project on CodePlex or GitHub.
I just see a simple feature of GitHub, named Gist. It's a simple method for sharing your code that you find useful for others. For example, having to implement online payment functionality for my Asp.Net MVC website I ended up with a simple PaymentController which I just shared it with GitHub.
Here is my first gist:

Monday, March 26, 2012

Why Invalid Object Name 'dbo.__MigrationHistory'?


Unfortunately I am using  Entity Framework in my project. After migration support added to Entity Framework I thought using this feature may help me feel a little better about  Entity Framework . But the way migration is implemented in EF shows that nothing has changed. Migration has lots of problems and bugs.
After carefully doing all the required cumbersome procedures  Entity Framework migration failed to work and I found no workaround until I strangely faced the exception 'Invalid Object Name 'dbo.__MigrationHistory''. This exception give me  a clue about the cause of my problems.
It seems that Entity Framework team do not use appropriate testing methods and they only care about the main courses and are very negligent about alternative cases. For example in this case they presumed that always the default schema is dbo. It creates __MigrationHistory on the default schema, but queries for it on the dbo schema.
After a while I find another problem. Entity Framework also tries to insert rows into __MigrationHistory without specifying schema name.

Ok, I wrote this code to make Entity Framework script generator apply 'dbo.' before the __MigrationHistory. I know this is naive solution but at least it works.


A WPF Technique: Decorating controls by deriving from standard control

I always consider StackPanel as Vertical StackPanel as it is Vertical by default, but why there is no layout control that is horizontal by default?. I believe it does not worth for the WPF framework to introduce one as it is very easy to write if you need one. In this post I am going to describe how easy is to create a HorizontalStackPanel and a couple of related useful notes.

Define types by deriving from WPF controls.
The simplest way to write your own controls is to derive from existing ones. You do not need to do anything else. Yes, that it, you have the same control with the same functionalities but with a different Type. For example you may derive a class from TextBlock, it still is a TextBlock but it has its own specific type, so it is behave in a slightly different in some cases, mostly when you refer the types like in a TargetType of a Style.
Here is a summary of benefits of doing so:
  • Defining some common behaviour in code and not using the styles
  • Easier targeting them in styles
  • More readable XAML code
  • Very helpful for code sharing between Silverlight and WPF
HorizontalStackPanel as an example
For example you may define a HorizontalStackPanel by deriving a type from StackPanel and setting its Orientation to Horizontal in its constructor. Actually it is not a horizontal stackpanel but it is InitialyHorizontalStackPanel as the users have the opportunity to change the orientation later using XAML or code.
Also the HorizontalAlignment in StackPanel has a default value of Stretch, you need to set it back to Left and do the same for VerticalAlignment.


public class Horizontal : StackPanel
{
    public Horizontal()
    {
        Orientation = Orientation.Horizontal;
    }
}
public class Vertical : StackPanel
{
    public Vertical()
    {
        Orientation = Orientation.Vertical;
    }
}


So now you can write these XAML code

<StackPanel>
  <StackPanel Orientation="Horizontal">
      
  </StackPanel>
</StackPanel>

This way

<s:Vertical>
  <s:Horizontal>
      
  </s:Horizontal>
</s:Vertical>

Which is much more readable and less cluttered.


Wednesday, February 15, 2012

Entity Framework 4.3 Released

Just read this announcement about the release of Entity Framework 4.3. Despite some fixes, the only great feature added to this version is the Entity Framework Migration. So now using Entity Framework 4.3 you can keep your data after changing your data model. In the past, you need to drop and recreate database or handle database upgrade manually.

Saturday, January 14, 2012

Using third party web services in your applications

Reading a question in StackOverflow website I thought I have to write about my suggestion to Windows Phone developers regarding the way you should use third party web services in your applications:


Adding a layer of indirection is considerable
It is very common that you need to consume a web service from a third party to show some information to your users or provide some functionality for them. So the easiest way is to add a reference to their web service in your application and call methods.
In certain scenarios you have to employ this method. But I am thinking of not adding a direct dependency to a third party web services. Ans I suggest to add a layer of indirection by implementing your own web service by dispatching the request from your applications to the third party web service.
Application Vulnerability to changes in web service definition
By adding a direct dependency to a third party web service and considering the fact that the web service owners may change the web service definition, all the installed instance of your application may fail to work if such a change happens. Then you have to provide an updated version of your application and wait users to install the update. Some users may not be happy with the situation and decide to uninstall the application instead of updating.
The chance of adding your own functionality
If you directly call the third party web service you are limited to functionalities provided by that web service, for example imagine that you call web service to receive a list of addresses. Now if you want to pin them on a map, you need the latitude and longitude of the addresses which is not provided by the web service. I believe in most of the cases you will be much more productive if you have some power to do the things in your own way.
Performance and efficiency considerations
As the designers of third party web service have thought about some specific scenarios the set of methods they provided may not match your exact needs. For example you may have to make two or three calls to receive all the required data and no single method gives all the response you needed. And the result from the first calls is not enough to provide any feedback to user . Or as an another example you may only need to show a part of received data and have nothing to do with the whole given data. As can be clearly seen by this examples there could be two kind of problems with third party web services, extra round-trips and extra bandwidth consumption, which avoiding them can increase your application performance.
Logging and tracking
Generally a good method for logging and other cross cutting concerns is to have an indirection layer, which receives requests and dispatches them. And here in our topic about third party web services, if we do not sit in user's way to access to data and services we have no chance to track them and have a report of it. So create a web service and dispatch the request to third party web service and meanwhile collect some useful data like error exceptions, calls count, performance logging, caching. And do not forget to be respectful to users privacy. If your application is mostly calling the web service then you could have a nice report your application usage.

Some disadvantages
No need to say, writing your own web service has its own disadvantages. First it is costly, you have to develop, test, maintain the web service. Also you have to pay for hosting, if you do not have a spare web space. And your hosting may not be as powerful and fast as the third party web service is, so your app would not be as fast as it could be. Also there are legal issues about using third party web services, some web services specifically forbidden not using their services directly. I am not very into security, but I have a vague idea about there may be some security issues.

What do you think?
Also there may be some other advantages and disadvantages, I would like to hear about them, so do not hesitate to leave a comment.



Wednesday, January 11, 2012

Assigning null to anonymouse type properties

Just a quick note about handling an issue for anonymous types, if you wanted to assign a null value to a property you will face a compile error which says Cannot assign <null> to anonymous type property, and the easy solution for this is to write to cast the null to desired type, this is important specially if you are creating an array of anonymouse typed objects.

Here is a sample code:

return new[] { 
    new { Name = "Fixed Value", ViewModel = (objectnew B_FixedValue_EditViewModel() } ,
    new { Name = "Fixed List", ViewModel =  null as object} ,
    new { Name = "Calculation on one value", ViewModel = null as object } ,
    new { Name = "Calculation on two values", ViewModel = null as object } ,
    new { Name = "Loading a value from database", ViewModel = null as object } ,
    new { Name = "Conditional Value Provision", ViewModel = null as object} ,
};

Tuesday, December 20, 2011

Showing a modal and continue to execution of calling window

Again some bits of code. For a couple of reason you may consider not using the ShowDialog method of a window, one is that the calling method does not continue the execution and it blocks until the dialog window becomes closed. I have written my MVVM tool set in a way that this behaviour causes some problems. The other reason is ShowDialog blocks all other windows in your application, so what if you want to open a window over another window in a way that only the calling window becomes blocked. Here is the solution I came up with:

public static class WPFWindowExtensions
{
    public static void ShowNonBlockingModal(this Window window)
    {
        var parent = window.Owner;
        EventHandler parentDeactivate = (_, __) => { window.Activate(); };
        parent.Activated += parentDeactivate;
        EventHandler window_Closed = (_, __) => { parent.Activated -= parentDeactivate; };
        window.Show();
    }
}

I tried to keep it simple to be more readable, however you may add a check for the window.Owner to have a value and throw an exception if it is null, or you may automatically set the owner with the current active window as described in this blog post.


Friday, December 16, 2011

OnNavigatedTo will be called after selecting a date using DatePicker

Long Story:
During developing my Windows Phone application I faced a strange problem. At first I thought that the problems is related to DatePicker Value binding is not working properly. I tried several things and then finally I relaized that OnNavigatedTo method is being called when the user selects a data or presses the back button and then when this method is executed again I override all the bindings. And the solution is very simple, just check for NavigationMode of event args to not be NavigationMode.Back, here is a sample code:

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
 
    if (e.NavigationMode == System.Windows.Navigation.NavigationMode.Back)
        return;
 
    viewModel = new AddWeightViewModel();
    viewModel.Date = DateTime.Today;
 
    this.DataContext = viewModel;
}


Short Story:
Always make sure that you add the following lines of code to the OnNavigatedTo method, specially if you have a DatePicker on your page:

    if (e.NavigationMode == System.Windows.Navigation.NavigationMode.Back)
        return;

By adding the above code to the beginning of OnNavigatedTo you prevent from resetting your page data. Keep in mind although the OnNavigatedTo is called, the page is still has its own values.








Thursday, December 15, 2011

Solution to a problem in Application Bar and Binding on the same page

Just a quick share of a useful code I found in MSDN forums for when application bar button invokes the event handler before binding on the current element takes place.
The problem is that if you add a textbox to the page and then user presses a button on the application bar, then if user presses that button just after filling that textbox, then unexpectedly you will not receive the updated value for that textbox's binding target, whatever the reason is the solution for this is to update binding manually knowing the fact that the textbox is the current focused control, here is the code:

public static class Utilities
{
    public static void MakeSureBindingsApplied()
    {
        var focusObj = FocusManager.GetFocusedElement() as TextBox;
        if (focusObj != null)
        {
            var binding = focusObj.GetBindingExpression(TextBox.TextProperty);
            binding.UpdateSource();
        }
    }
}

Then what you have to do is just to call it in the event handler for application bar button, make sure that you call this method before reading data from binding's targets.

private void saveButton_Click(object sender, System.EventArgs e)
{
    Utilities.MakeSureBindingsApplied();
}


Wednesday, December 7, 2011

Library for reading emails from a POP3 server

I needed to get the list of messages in a the inbox, so I can process them and save them into a database. After searching a while I found out a good free library for this purpose is OpenPop. Net . This library has a good interface and easy to use. Also is well documented, plus lots of useful examples. And one important thing, it supports SSL, so, for example you can read your emails in your gmail or live accounts.

This is a simple sample code for having your inbox in an Asp.Net page:
No need to say, you have to change the third line with your own gmail credentials:


   Dim client = New OpenPop.Pop3.Pop3Client
   client.Connect("pop.gmail.com", 995, True)
   client.Authenticate("mygmailaccountid@gmail.com""mypassword")
   Dim messageCount = client.GetMessageCount()
   Dim allMessages = New List(Of Net.Mail.MailMessage)(messageCount)
   For i = 1 To Math.Max(10, messageCount)
        Dim message = client.GetMessage(i)
        Dim mailMessage = message.ToMailMessage()
        allMessages.Add(mailMessage)
   Next
   grdInbox.DataSource = allMessages
   grdInbox.DataBind()
   client.Dispose()


Sunday, December 4, 2011

Finally I started Windows Phone 7 development

A couple of weeks ago I attended in a Microsoft's workshop for Windows Phone 7 development just after buying my Samsung Omnia 7 phone, the workshop inspired me with the fact that Windows Phone 7 development is just fun.
So moving to Windows Phone 7 world I will be posting about Windows Phone 7 applications, games, news, development tips in the future.

For the beginning I would like to write about why moving to Windows Phone 7, of course,  from my perceptive. I have several reason but here is two of them that I can share. One is that its development is easy and the other one is that I hope in Windows Phone 7 future.

Reason 1 : Windows Phone 7 development is easy.
Now that I have wrote a couple of applications reading for publishing into market I am thinking of developing Windows Phone 7 application is even easier than writing Desktop or Web applications. For every functionality you desire to add to your application there is a too much simple API.
Also I attended in an Android development workshop at SystemGroup company. I was just pain. In two hours we only learnt how to add a button to UI and then handle it's click button. No need to say iPhone development is even harder than Windows Phone.

Reason 2 : Windows Phone 7 will beat both iPhone and Android in the near future
First of all I have to say I hate iPhone, I know iPhone is the favourite phone for most of you, but to me it never attracted me. I used iPhone as the company's phone, it was nothing special to me. iPhone seems too boring to me. To understand me you have to use both iPhone and Windows Phone for a while, then you will probably get this feeling. Also I am not inspired by the Siri as it is only a non practical funny feature.
Also there are some predictions that in the future Windows Phone will beat Android.

Wednesday, November 23, 2011

Compressing and Decompressing Text Strings using GZipStream

Simply wanted to pass a text to client and the receive it back again. Something like the old viewstate concept. I searched the web for ready to use piece of code that compress the text into byte[] and vice versa but I failed to find a working source code, so I wrote one.

Here it is:


public class Zip
{
    //public static Encoding Encoding = System.Text.Encoding.Unicode;
    public static byte[] Compress(string text, Encoding Encoding = null)
    {
        if (text == nullreturn null;
        Encoding = Encoding ?? System.Text.Encoding.Unicode;            // If the encoding is not specified use the Unicode
        var textBytes = Encoding.GetBytes(text);                        // Get the bytes according to the encoding
        var textStream = new MemoryStream();                            // Make a stream of to be feeded by zip stream
        var zip = new GZipStream(textStream, CompressionMode.Compress); // Create a zip stream to receive zipped content in textStream
        zip.Write(textBytes, 0, textBytes.Length);                      // Write textBytes into zip stream, then zip will populate textStream
        zip.Close();
        return textStream.ToArray();                                    // Get the bytes from the text stream
    }
 
    public static string Decompress(byte[] value, Encoding Encoding = null)
    {
        if (value == nullreturn null;
        Encoding = Encoding ?? System.Text.Encoding.Unicode;                // If the encoding is not specified use the Uncide
        var inputStream = new MemoryStream(value);                          // Create a stream based on input value
        var outputStream = new MemoryStream();                              // Create a stream to recieve output
        var zip = new GZipStream(inputStream, CompressionMode.Decompress);  // Create a stream to decompress inputStream into outputStream
        byte[] bytes = new byte[4096];
        int n;
        while ((n = zip.Read(bytes, 0, bytes.Length)) != 0)                 // While zip results output bytes from input stream
        {
            outputStream.Write(bytes, 0, n);                                // Write the unzipped bytes into output stream
        }
        zip.Close();
        return Encoding.GetString(outputStream.ToArray());                  // Get the string from unzipped bytes
    }
}