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

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)
    if (e.NavigationMode == System.Windows.Navigation.NavigationMode.Back)
    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)

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

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)

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)
   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()
   grdInbox.DataSource = allMessages

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
        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
        return Encoding.GetString(outputStream.ToArray());                  // Get the string from unzipped bytes

Monday, November 21, 2011

MVC Tips #1, Passing HTML or Javascript as Data

Sometimes you need to render an html to output which the source of HTML is from your model. For security reasons rendering html directly from data requires to be explicitly requested, here is the 2 scenarios for doing so:

If your model has a property which contains HTML content you add the AllowHtml property before the property. By doing so you inform the MVC that you expect html content in that property.
Although the it is named AllowHtml it also works for JavaScript.

When rendering a Razor view to allow html content be rendered to output use @Html.Raw(Model.HtmlContent).

WARNING By using any of the above technique you need to make sure that the HTML or JavaScript content is safe. So if the data comes from some untrusted source you application will become vulnerable to attacks.

WARNING 2 Also pay attention to fact that AllowHtml also allows JavaScript, so dont assume that by applying this attribute only safe html code will be passed to client.

Note :
If you have a custom model binder and use pass the html values in your model, you may receive this exception:
A potentially dangerous Request.Form value was detected from the client
I found a solution for this problem at this Martijn Boland's blog post. which worked fine for me and you can learn about why this problem exists and how the solution works.

Tuesday, November 1, 2011

Asp.Net MVC : Setting Model as string and avoiding Illegal Characters in Path

If you for every reason need to set a page's model type to be string type, then you may face this exception:

Illegal Characters in path

Which seem to be weird, or you even may dont understand that the cause of the above problem is the Model type being string.
Actually the reason that you get the above exception is that in your Controller you as usual called the View method passing the model as the only argument and the model value is a string. But what you may have not pay attention to is that View method also has another override which accepts an string as the view name. So if you pass the model like this code:

return View("myStringModel");

In the above code you specified to go to page with the name "myStringModel" and such a page does not exists. Solution: My suggestion is to select the right overload by specifying the argument explicitly, like the below code:

return View(model: "myStringModel");

Monday, October 10, 2011

Ve Parser, A combinatory parser for .Net

A couple of years ago I tried to write a simple parser and I wanted to do it in the simplest way, I did not wanted to create a high performance compiler supporting lots of features, so instead of learning some already ready parser libraries I followed the recursive descent parsers technique and wrote the parser I wanted, then after doing some refactoring I end up with something that was different from a recursive descent parser. I searched through the net and I found out that the thing I made is called combinatory parser. Actually what I did was a simple library for creating combinatory parsers in .Net environment.

Last week I needed the parser for a current project, and then I brought back the source codes from my archive. I thought this would be a good idea to make it a public available(aka open source) library, so it would become more alive. I named the library Ve Parser and published the codes in codeplex: you can go and visit it in http://veparser.codeplex.com/.

Monday, October 3, 2011

A solution for User does not have permission to create new post

Developing a piece of code for sending content to a blog in Blogger I wrote the whole thing and then I tested and published my work. Then after a while without modifying the codes it becomes corrupted and by investigating the error logs I found this error message: "User does not have permission to create new post". If you search for this error you will see a lot of people having the same problem and nowhere there is no solution for it, or even an explanation about it.

I had a code like this

response = service.Insert(new Uri("http://myblogname.blogspot.com/feeds/posts/default"), newPost);

I just changed it to

response = service.Insert(new Uri("http://www.blogger.com/feeds/874763488093493674364/posts/default"), newPost);

In the above code, that number after 'feeds/' is the blog id which you can find it easily when you are in your blog's control panel, almost every url is consisted of your blog id. (For security and privacy reasons I wrote a fake id, but yours should look similar.)

Thursday, September 29, 2011

IsIn extension method

My motivation for writing blogs is to share my knowledge, although I am not a so professional developer. With the advent of extension methods I find it very helpful and started to use them everyday. Now I am going to share some of those small extension methods that may help you in writing your codes, maybe simply to make your codes pretty looking.

Lots of the time we use expressions like this:

if (x = value1 || x = value2 || x = value3 || x = value4 || x = value5) {

The problem with these codes are:
It's very dirty code and hard to understand, specially if the variables names and values are too long. which sometimes are.
If the if block contains other conditions it's bug prone to edit condition operators and if by mistake you change an or (||) operator with an and(&&) operator, you can't find the bug easily.
Extension Method
The code for extension method is very simple and straight. Most of the time extension methods that I wrote is just  a reversed version of another metohd which here the IsIn extension method simply call the Any method on the list of possible  values:
public static bool IsIn<T>(this T source, params T[] list)
    Func<T, T, bool> compare = (v1, v2) => EqualityComparer<T>.Default.Equals(v1, v2);
    return list.Any(item => compare(item, source));

Now you can easily use it very simple:
Before code:
if (x == 1 || x == 2 || x == 7 || x == 8)
    Console.WriteLine("X is a magic number");
After code:
if (x.IsIn(1 , 2 , 7 , 8))
    Console.WriteLine("X is a magic number");

Whole thing
If you just need to copy, this is the block of code you need to copy and paste in your class library and then you just need to correct the namespace with your own naming conventions:
using System;
using System.Collections.Generic;
using System.Linq;
namespace MyApp.Common
    public static class ExtensionMethods
        public static bool IsIn<T>(this T source , params T[] list)
            Func<T, T, bool> compare = (v1 , v2) => EqualityComparer<T>.Default.Equals(v1 , v2);
            return list.Any(item => compare(item , source));

Monday, May 30, 2011

Code Verification During Development

This post is not for people who use TDD or use unit test.

Here, I am going to talk about a simple idea that lots of you may know about it but aren't using it. And that is 'Immediate Window'.

Immediate window is not just about running simple expressions like '2+2', the subtle point is that you can refer to your objects in your codes.

Imagine you are going to develop a simple method to get all the possible substrings of a text:

public static List<string> GetAllSubTexts(string name)
    var result = new List<string>();
    var characters = name.ToCharArray();
    for (int from = 0 ; from < characters.Length - 1 ; from++) {
        for (int to = from + 1 ; to <= characters.Length ; to++) {
            var currentTarget = name.Substring(from , to - from);

    return result;
The above codes seems to work properly. So you may follow your coding without testing and forget this method. One reason developers usually do not do the testing is that it takes time and sometimes it is hard to reach an exact point in the code. But the method who uses it doesn't work properly, and you cant find the cause easily. because you have passed it a while ago.

Simply by calling the method in Immediate Window just after writing it, you probably had found the problem:
Count = 5
    [0]: "S"
    [1]: "Sa"
    [2]: "Sam"
    [3]: "a"
    [4]: "am"
You see, the 'm' is not included. So if you change the outter loop to continue to last index, it is solved.

By using TDD and unit testing practices you may find yourself wasting your time writing unit tests. but at least you can manually unit test your individual methods, specially those who contain complicated algorithms, before they cause problems.

Saturday, March 12, 2011

How to force visual studio to put content into designer file

Web development model in Visual Studio .Net has changed a lot from its first release. At the moment we have different project types for web development.
Recently I have begun working with a project initially developed many years ago and this project has an old structure. So I tried to convert it to a web project. One problem I faced was not having a seperate file for the designer generated codes, because the support for partial classes added later. It is not actually a problem but I wanted to know how I could easily force the visual studio to put designer generated stuff into a seperate file. After some struggling I found this simple method:
  • Just add a file with the name yourfilename.aspx.designer.cs to project.
  • Delete the auto generated codes in the main codes file.
  • Mark your page's class as partial.
  • Then when you save yourfilename.aspx the next time, visual studio will put the generated content into desginger file.

Friday, January 7, 2011

Entity Framework Designer Notes

To zoom : hold down Ctrl while rotating mouse wheels

To scroll horizontally : hold down Shift while while rotating mouse wheels