Pages

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





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:

[AllowHtml]
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.

@Html.Raw(Model.HtmlContent)
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.

Name
IsIn
Purpose
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));
}

Usage
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);
            result.Add(currentTarget);
        }
    }

    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:
MyNamespace.MyClass.GetAllSubTexts("Sam")
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.