Monday 25 November 2013

Winforms - Update UI for Long running processes

If you have a long running process in your windows forms application you might try to update a message label in the UI to say "Processing. Please wait...". But as a matter or fact, the UI doesn't get updated till the process is completed. in this case it doesn't serve your purpose of notifying the user by updating a UI element.
private void btnAzerbaijanReportJob_Click(object sender, EventArgs e)
{
lblMessage.Text = "Please wait..";
IneedTime(); // Long running process.
lblMessage.Text = "Done.";
}
In the above case, lblMessage will never display the text "Please wait..", because IneedTime() method executes on the UI thread and UI will not be updated until IneedTime() methods finish executing.
To overcome this, there are 2 methods.
1) Run long running process (IneedTime() in the above code) in a separate thread. In case you dislike to make your app a multi thread app, you have a second option.
2) Second option is to force the UI to redraw the UI even before your long running method executes. For this you need to call the
Application.DoEvents() method. What this method does it that it will process all the windows messages currently in the message queue. So this queue will already have the paint message which was issued when we set the label (lblMessage) text.
private void btnAzerbaijanReportJob_Click(object sender, EventArgs e)
{
lblMessage.Text = "Please wait..";
Application.DoEvents();
IneedTime(); // Long running process.
lblMessage.Text = "Done.";
}
In case you see the UI is not updated as expected, you can also use the below code.
lbl.Invalidate();
lbl.Update();
Application.DoEvents();
or even
lbl.Refresh();
Application.DoEvents();
to redraw the label UI.

Monday 18 November 2013

Windows Phone - How to use Resource Files

Resource Files in Windows phone has the similar concepts as it was in Web Forms. It can be used for localization as well as store string values to be used across your apps. Resource files are a nice way to reduce hardcoding strings inside your application code.
The default resource file added to your solution when the project is created is "AppResources.resx" which is in the "Resources" folder at the root of your project folder hierarchy. This default file is called the "neutral language resource" because it is the fallback resource file even in localization scenarios.

Note: As in web forms and win forms, each culture has its own resource file, with the culture suffixed to the filename (AppResources.en-US.resx). We will discuss more on localization scenarios in another post.

Below is the code to dynamically bind your resource to XAML page element's properties.
"{Binding Path=LocalizedResources.ApplicationHeader, Source={StaticResource LocalizedStrings}}"
For example if we want to bind a string resource to the Text property of TextBlock Control:

<TextBlock Text="{Binding Path=LocalizedResources.ApplicationHeader, Source={StaticResource LocalizedStrings}}" />

Monday 4 November 2013

C# Remove Invalid filename characters from string

Ever wanted to remove invalid filename characters from a string while dealing with file related code?
Here is a pretty easy solution using C# Regex class.
The funda is to find any invalid character/characters from the string and remove it.
Here is the method which does the trick.
private static string GetValidFileName(string fileName)
{
// remove any invalid character from the filename.
return Regex.Replace(fileName.Trim(), "[^A-Za-z0-9_. ]+", "");
}
The code even preserves white spaces and removes only invalid special characters. The Regex patter can also be replaced by "[^a-zA-Z 0-9'.@]" A better solution which I prefer is using LINQ:
private static string GetValidFileName(string fileName)
{
return Path.GetInvalidFileNameChars().Aggregate(fileName, (current, c) => current.Replace(c.ToString(), string.Empty));
}
There is a solution mentioned in MSDN which personally I do not find very appealing.
static string CleanInput(string strIn)
{
 // Replace invalid characters with empty strings. 
 try {
    return Regex.Replace(strIn, @"[^\w\.@-]", "", 
       RegexOptions.None, TimeSpan.FromSeconds(1.5)); 
 }
 // If we timeout when replacing invalid characters,  
 // we should return Empty. 
 catch (RegexMatchTimeoutException) {
    return String.Empty;   
 }
}