Wednesday, 28 September 2011

Performance Dashboard Reports in SSMS SQL Server 2008 R2 to find the Bottlenecks

SqlServer developers, DBAs or if you are just normal developer who often uses the SSMS if you are assigned to optimize the database performance and you’re not much familiar or don’t' want to play around with DMVs and DMFs then Performance Dashboard Reports are for you.

Go and download the performance dashboard reports from here. and add it as a custom report to Management Studio (SSMS). It is a free download! Read on below to find out how to install it and use it on your SQL Server. I have also included custom modified files as attachment in end of the post that allow you to use this for a SQL Server 2008 instance. This is provided “as is” with no guarantees.

What will you get by these reports?

Well, These reports are created covering the performance aspects for SQL Server instance. The reports are mainly intended to quickly identify performance problems and help resolve them. These reports use the DMV’s that came out with SQL 2005, so they are very fast & reliable information when troubleshooting a performance problem. Some of the common problems that can be detected using the Dashboard Reports are:

1) CPU bottlenecks (which queries are consuming the most CPU and Plan for this query)

2) IO bottlenecks (which queries are performing the most IO and Plan for this query).

3) Index recommendations generated by the query optimizer (missing index recommendations pulled from sys.dm_db_missing_index_details and sys.dm_db_missing_index_group_stats)

4) Blocking

5) Latch contention and other Wait Types

Pre-Requisites

1. You need to have Management Studio installed on the machine where you intend to use the Performance Dashboard Reports (could be either client or server machine).

2. If you are still using SQL Server 2005 the it needs to have at a minimum SP2 applied (build 9.0.3042 or greater)

Steps to Install:

For SQLServer 2005

1. Run the setup exe downloaded from HERE.

2. Once you install the above, go to %\Program Files\Microsoft SQL Server\90\Tools\PerformanceDashboard and run the setup.sql script against the SQL instance that you want to monitor the performance for.

For SQLServer 2008 R2

1. Run the setup exe downloaded from HERE.

2. Once you install the above. Download the attachment from the link at end of this post and extract the files. You’ll find two files there copy them and paste them to %\Program Files\Microsoft SQL Server\90\Tools\PerformanceDashboard. Overwrite the old files and run the setup.sql script against the SQL instance that you want to monitor the performance for.

Start using the performance reports

Note: The script will create some Stored Procedures, table-valued & scalar functions in the MSDB database. All the SP’s created by Dashboard with have the schema MS_PerfDashboard.

If you want more information on the newly created objects, use the query below
If you want more information on the newly created objects, use the query below
select * from sys.objects where schema_id = SCHEMA_ID('MS_PerfDashboard')

Now, Open a new management studio window, right-click on instance name -> Reports -> Custom Reports.

image

Browse to the location %\Program Files\Microsoft SQL Server\90\Tools\PerformanceDashboard and choose the performance_dashboard_main.rdl and click OK. This will add the performance dashboard to SSMS.

Next time when you right-click on the instance and go to Reports, you should see the entry performance_dashboard_main. Clicking on this will launch the Main Dashboard page.

Below is the screenshot of what the performance report will look like:

image

Few basic fixes you can do quickly:

Missing Indexes -

In the Miscellaneous Information it’ll show you the Missing Indexes link. Click it will open the other reports that will not only show you the Missing index information but also the queries to created them.

Expensive Queries -

If you have queries running on your server instance as job or frequently and consuming lots of resources you’ll find these reports very useful.

image

Report for queries taking higher CPU time will be show by the graph you can click on the bar and find the query details like execution plan, time etc.

Export your reports – Reports should have Export function so it is there. Just right click on any report and select Excel or PDF.

image

Sound interesting.. umm then go ahead and explore more Nerd smile.

You can find some more interesting material of using Performance dashboard reports

1. PPT on Performance Dashboard Reports by Amit Banarjee

2. Perfromance Dashboard “troubleshooting problems” Video by Harish Chawla 

I hope you will enjoy this small but great Dashboard to tune your SqlServers.

download the upadted setup.sql for SqlServer 2008

Tuesday, 27 September 2011

How to Fix Selenium popup alerts problem in Web Automation Testing

Selenium is popular framework that is being used with automation testing of webpages. But there is a problem that is being faced by the testing teams is it doesn’t support the handling of Popup or alert() boxes being called on onload() or onbeforeunload() event of browser. There’s workarounds exists like AutoIT etc. Special case seen for this is when we have Confirmation applied before navigating away from a page and selenium would fail to handle this and Automation will fail. One of my colleague was facing the same problem and he don’t want to use AutoIT. So I came with my own solution that can be used as fix and work well in handling the popups/alerts.

Environment: NUnit, Selenium, C#

The best way to deal with such alert box or popup is to use vbscript. It can identify the running window instance by its title and will send the “Enter” key to send ok.

The complete code for vbs will be:


Set oShell = CreateObject("WScript.Shell")
Set
args = WScript.Arguments
arg1 = args.Item(0)

If oShell.AppActivate(arg1) Then
Wscript.Sleep 500
oShell.SendKeys
"{ENTER}"
End
If

Create a new vbs file copy & paste the above code save it.

Next step is to call the vbs file when you webpage is showing the alert/popup with ok/cancel (whatever) buttons. To call the vbs you need to change your methods calls in NUnit.

So create a function that can call the vbs as separate process asynchronously to open and wait for a while to open the page and alert box to appear. Copy and paste the below method code. The function will take title of the window as argument and call the vbs file. I’ve named the vbs file to auto.vbs here.

public Thread SimulateClickForConfirmation(string title)
{

//Simulate autoclick on IE windows
Thread th = new Thread(new ThreadStart
(() => {
Thread
.Sleep(1000);
Process script = new Process
();
script.StartInfo.FileName =
Environment.CurrentDirectory + "\\auto.vbs"
;
script.StartInfo.Arguments = title;
script.Start();
script.WaitForExit();
script.Close();
}));

th.Start();

return th;
}

Now you’ll call this function when you want to simulate the click for the alert or confirmation popup.

for e.g:

Thread th = pObj.SimulateClickForConfirmation(currentPage.Title);

//navigating away from the current page by clicking through selenium
selenium.Click(Someotherpage);

//abort the thread if previous statement gets executed
th.Abort();

This will activate the browser window and click on the alerts or confirmation box’s default button. I hope this would help our testing team facing such problems.

So Don’t stop testing.. Smile.

Monday, 26 September 2011

RadDock vs WebParts comparison list

To compare RadDock and Webparts, I did some research and I found few points that
can help you taking decision which control to use either RadDoc or WebParts. Both provides you user personalization experience. Below are my listings:

Features of Webparts and RadDock

WebParts provide the following features out of the box:

  • Adding new WebParts to the page

  • Editing the content of a WebPart

  • Binding WebParts

These features are not built-in within the RadDock control but can be easily implemented.

RadDock provides:

  • [Live] resize functionality

  • Rich client-side API

  • Animations

  • Smooth drag and drop

  • Cross-browser compatibility

  • 13 built-in Skins

Ease of development

RadDock allows developers to create dynamic pages, the content of which can be personalized
by end users, and then the changes are saved and later restored to the last state.
Inbuilt features are available to support the rapid development and can be customized
as per the requirements. Built-in skin and CSS support.

Save state in cookies for statically created RadDocks.
Dynamically add or delete RadDocks via Ajax and save their state in the session

Microsoft WebParts allow developers to easily create a portal, i.e. they represent
the parts for creating and personalizing page layouts, contributing content, uploading
documents, etc. - things related to portals. Webparts has to be designed from scratch
but can be built in separate DLL and installed in the GAC to reuse across applications.
Creation of webpart and Adding skin/css requires work from scratch and provide high
level of customization.

Personalization

Available Features:
Asp.net Webparts allows the personalization with two types of control:

Shared control: - An authorized user can personalize both Shared and User scoped
properties on the control for all users. In the case of a dynamic control (a control
that is added to the page programmatically, or from a catalog of controls), an authorized
user can permanently delete it for all users. In the case of a static control (a
control that is declared in the markup of an .aspx page), it cannot be deleted,
although an authorized user can close the control for all users.

Per-User control: - The control cannot be personalized with the page in Shared scope,
because the control does not even appear on the page. The control only appears when
the page is in User scope.

RadDock controls are always in shared mode and allow all users to interact. But
you can customize them to persist/Not-persist the changes in layout state as per
the user.

Ease of Customization:

For custom personalization you need to create a custom provider class in Asp.net
WebParts. WebPartPersonalization class Implements the logic necessary to carry out
personalization actions.

Customization of the RadDock would be much easier as more focus would be on logic
rather than the look n feel. RadDock allow saving/loading of layout so no need to
create custom provider.

Pros and Cons
  • The biggest drawback of webparts is that it does not open the properties section
    inside the webpart. Instead, it opens in a zone on the main screen.

  • An even bigger drawback of WebParts is that you can't edit the properties while
    in catalog view. To switch between the two, you need to do a postback.

  • For RADDOCK there’s no need to implement any provider. Instead it requires customizing
    the scope and persistence of user’s layout.

  • WebParts work only when in admin mode.

  • Webparts are using the table layout which itself seems problematic in some cases.

References:

http://demos.telerik.com/aspnet-ajax/dock/examples/myportal/defaultcs.aspx

http://msdn.microsoft.com/en-us/library/z36h8be9.aspx">
http://www.telerik.com/community/forums/aspnet-ajax/docking/comparison-with-the-asp-net-web-part-framework.aspx

http://www.telerik.com/community/forums/aspnet-ajax/docking/comparison-with-the-asp-net-web-part-framework.aspx

Wednesday, 21 September 2011

Improve your productivity with New PowerCommands Tool on VisualStudio 2010

If you gone through the last post about Productivity Power Tool and found it useful then here' I’m again with a new HotShot stuff that will increase your productivity +1 level up. Are you ready to take a tour on this? yes.. you are thats why you are developers guys. So lets get started. So our next Tool for Visual Studio 2010 is PowerCommands Tool.

Go and download the PowerCommands for Visual Studio 2010 here.

SNAGHTML18848871 Download PowerCommands for Visual Studio 2010 Extension

[ I somehow manage to create this image to looks relevant Hot smile]

This is hottest in the market I’m telling you When I saw the download and rating, it made me post about it. imageSee the figures when I was writing this post. And these figures it earned in very short time.

 

Install it simple steps as any other addin for VS2010. Now restart visual studio and lets see what you can do with it:

1. New Context menu commands for files, projects and solution

Right click on any file in the Project and see new options

image

i) Yes Open Containing Folder is previously was only for Project and Solution files but now each file can be directly be navigated in the containing folder.

ii) Open the CommandPrompt in the Containing folder. You may ask how often will I use it.. But I can tell you few instance svcutil, wsdl, snkey etc. for these utilities you need command prompt. Now this sounds cool isn’t it.

2. Copy Reference

Now its more cool then ever and easy with time saving on adding reference. If you have one reference in one project in your solution and want to add the same in other project then Right Click the reference and Copy Reference. Go and Paste it in other project.

image

2. Copy As Project Reference
This command copies a project as a project reference to the clipboard. It can be executed from a project node. Quick way to adding the project as reference.

3. Commands for solution file

Right on the solution file will show you few new commands added.

image

=> Copy Path
This command copies the full path of the currently selected item to the clipboard. It can be executed by right-clicking one of these nodes in the Solution Explorer:
The solution node; A project node; Any project item node; Any folder.

=> Format document on save / Remove and Sort Usings on save
The Format document on save option formats the tabs, spaces, and so on of the document being saved. It is equivalent to pointing to the Edit menu, clicking Advanced, and then clicking Format Document. The Remove and sort usings option removes unused using statements and sorts the remaining using statements in the document being saved.
Note: The Remove and sort usings option is only available for C#  documents.
Note: Format document on save and Remove and sort usings both are initially defaulted OFF.

=> Collapse Projects
Super cool for you if you have large number of projects in your solutions. This command collapses a project or projects in the Solution Explorer starting from the root selected node. Collapsing a project can increase the readability of the solution. This command can be executed from three different places: solution, solution folders and project nodes respectively.

=> Remove and Sort Usings (Batch command to all files/Projects)
This command removes and sort using statements for all classes given a project. It is useful, for example, in removing or organizing the using statements generated by a wizard. This command can be executed from a solution node or a single project node.

=> Show All Files (Batch command to all files/Projects)
This command shows the hidden files in all projects displayed in the Solution Explorer when the solution node is selected. It enhances the Show All Files button, which normally shows only the hidden files in the selected project node.

image

Copy & Paste Class
Just like references This command copies a selected class entire content to the clipboard, renaming the class. This command is normally followed by a Paste Class command, which renames the class to avoid a compilation error. It can be executed from a single project item or a project item with dependent sub items. Paste command pastes a class entire content from the clipboard, renaming the class to avoid a compilation error. This command is normally preceded by a Copy Class command. It can be executed from a project or folder node.

Edit Project File
This command opens the MSBuild project file for a selected project inside Visual Studio. It combines the existing Unload Project and Edit Project commands.

Tab commands

=> Undo Close
This command reopens a closed document , returning the cursor to its last position. To reopen the most recently closed document, point to the Edit menu, then click Undo Close. Alternately, you can use the Ctrl + Shift + Z shortcut.
To reopen any other recently closed document, point to the View menu, click Other Windows, and then click Undo Close Window. The Undo Close window appears, typically next to the Output window. Double-click any document in the list to reopen it.

=> Close All
This command closes all documents. It can be executed from a document tab.

File Menu

=> Clear Recent File List
This command clears the Visual Studio recent file list. The Clear Recent File List command brings up a Clear File dialog which allows any or all recent files to be selected.

=> Clear Recent Project List
This command clears the Visual Studio recent project list. The Clear Recent Project List command brings up a Clear File dialog which allows any or all recent projects to be selected.

Code Perspective

=> Email CodeSnippet
To email the lines of text you select in the code editor, right-click anywhere in the editor and then click Email CodeSnippet. Easy peasy to send the peace of code which needs to be sent and discussed and subject line is seems to be meaning full! Winking smile

image


=> Insert Guid Attribute
This command adds a Guid attribute to a selected class. From the code editor, right-click anywhere within the class definition, then click Insert Guid Attribute.

=> Refactor any hardcoded value to constants

Just select the value and right click on it | Refactor | ExtractConstant. See screenshot below

image

I hope you have enjoyed the show. You must be feeling something like:

 

 image

 

 

Dear Readers!!! I always try to come with best of my finding for you so keep an eye on www.cshandler.com

Improve your productivity with VisualStudio 2010– Productivity Power Tools

Are you a smart visual studio 2010 developer? If you want to be then this post is for you. This post is for Visual Studio 2010 users to get productive while working. Whatever you missed to have in your VS release, is here. While writing the code your another task is to manage the things around and this tool will help you providing everything on the table. Best features ever seen with good UI and at very small cost of performance overhead if you have minimal requirement of hardware configuration for VS2010.

Very first Go and Download the VS2010 Productivity Power Tool from here.

image Download ProPowerTools

Installation is as smooth as like another plugin. After Installing you may want to visit features that I liked most. There’s lots of things you would see are available as options to quick clicks. but below are mine favorites and I use them massively.

1. Improved Add reference prompt box with search

This is one of the feature I’ve ever waited cause manually going through and finding the references of assembly..ohh that sucks!! But now you can just type in search box and everything that matches get filtered and you can select it plus box will be there you can add more if you want and then just close the box when you’re done. and its loading fast.

image

2. Quick Access
Quick Access is a new tool window that allows users to search for and execute common tasks within the Visual Studio IDE. Not sure where a particular menu command is located? Want a quick way to create a new Silverlight project? By using Quick Access, you can efficiently find and execute common VS operations without taking your hands off the keyboard. Quick Access allows users to:

  • Execute Main Menu and Context Menu commands
  • Open the New Project Dialog with a specific Project Template selected
  • Show a tool window
  • Jump to a Visual Studio Options page
  • Navigate to an open document in your Tab Well
  • Create and execute a series of actions (task)

To use, press Ctrl+3 to launch Quick Access, type in your search term (e.g., “debug”), and press Enter on the desired result. If your search term returns too many results, continue pressing Ctrl+3 to cycle through each category of results.

3. Auto Brace Completion
Automatic Brace Completion improves the productivity of writing code by automatically inserting the closing code construct when the opening construct is typed for VB & C#. More specifically, this extension:

  • Supports the following constructs: (), {}, [], <>, “”, and ‘’.
  • Allows you to press <TAB> to navigate past the next enclosing brace
  • Allows you to automatically complete a statement in C# by inserting the closing semi-colon and moving you to the next line with SHIFT + ENTER

The extensions from the previous Productivity Power Tools have been included and improved.

4. HTML Copy

If you are a blogger then you’ll love it cause you may want to copy the code as HTML when you add it to your post. I’m telling you it’s a worth utility. you’ll no longer have to go fix up the formatting of your code when you paste it into a TFS bug form or any other HTML based control. It is possible to modify the html format which gets copied to the clipboard and with the release you now have the ability to customize that to suite your needs. You can go to Tools | Options | Productivity Power Tools | HTML Copy or Simply just press CTRL + 3 and type “HTML COPY” Winking smile

5. Triple Click
It’s never been easier to select a line of code from the mouse by simple triple-clicking anywhere on the line.

6. Move Line Up/Down Commands
This is pretty cool..! This extension maps the Alt+Up Arrow & Alt+Down Arrow keys such that they will move the current line of code or the selected lines up and down through the editor.

7. Enhanced Tool Tip

Navigate directly to the Definitions and see just by expanding the nodes what’s inside.

image

8. Turn Off the Feature you don’t like or want to use

Ahh.. and atlast there is lots of extensions in there, few must be helpful for you but not all so whatever feature you feels annoying you just go to Tools | Options | Productivity Power Tools and find the extension on the right (remember to scroll!). It requires a restart of Visual Studio to change effect.

SNAGHTML182b1830

The above list is something I liked most out of this Productivity Power Tools. I hope you will find more useful ways to utilize them all.

I hope you like this post. Also have a look at another post on New productive Tool from Visual Studio Toolbox The PowerCommands Tool.

Monday, 19 September 2011

How to create your own custom code snippets in Visual Studio

If you are a developer and do lots of programming then Most of the time code lines get repeated. So you have to write them again and again or if you do copy paste then every time you have to change the name and ID’s or whatever is to be changed for readability. Visual Studio facilitates you to create you own custom code snippets for such situations. There are already such snippets comes and get installed with visual studio.

image Snippet Symbol that appears in Intellisense window.

for e.g. in C# we have snippet like below:

ctor – for default class constructor

for – for default for loop snippet

svm – for main function

prop – to create property

etc. So what you do is just type these words and double tap on TAB key and code get generated there just like that. This is one of feature that I love in our VisualStudio.

I suggest you a must have tool that you want to use and surely will love it. The Snippet Designer for VisualStudio. you can also write your own code snippet.

Download the addin from here:

Snippet designer for Visual Studio 2010/2008

Install the plugin Restart your VisualStudio. Now follow below steps:

Go to Menu File-> New –> File.. option

image

you’ll see a new template installed there for Snippet Designer

image

Select the CodeSnippet file template and click ok.

Now mention the name of SnippetName [it’ll appear as the tooltip when you use this snippet in your code] and select you language for which you want to create the snippet.

image

Now start typing you code or just copy paste it from you source. Now its time to choose the Literals you may want to change by your own at the time use. Wrap the string with $ It’ll automatically replace all the occurrences of that string in your snippet. See the snapshot below:

image

Now you are almost done here. Now Go to properties window and mention a shortcut that’ll let this snippet appear

image

Now save the file by pressing Ctrl + S and select a location to save this snippet file.

image

Now Open a new project and start typing the shortcut key you mentioned.

image

You custom code snippet will appear now double Tap the TAB key

image

Now change the values of the literal you have want to as per your choice.

and you are done Smile . I hope next time you go for some demo or something you might want to create some Snippets like this so that you don’t have to type your code again and again and by just pressing few keys and your code will appear just like that. Impress your audience or your colleagues.

Be a Smart Programmer.

Async CTP and Roslyn The Future of CSharp and VB.NET

In this talk, Technical Fellow Anders Hejlsberg will share project plans for the future directions of C# and Visual Basic, including a discussion of what trends are influencing and shaping the direction of programming languages. Anders will talk about asynchronous programming and Windows 8 programming, coming in the next version of Visual Studio. He will also discuss the long-lead project "Roslyn", including object models for code generation, analysis, and refactoring, and upcoming support for scripting and interactive use of C# and Visual Basic.



Download the video from original source here.

Wednesday, 14 September 2011

JustDecompile by Telerik for IL and conversion of CSharp code to VB.Net

In daily practices when we need to see the IL code from our assemblies we do prefer to use ILDASM.exe to see the IL. Going forward Telerik guys have done such a nice work and made a easy and handy tool to see your IL Code and Even you can convert your code from C# to VB.net and vice versa. This is the most cool feature I like in it. Now I can create my Demos in C# as well as in VB.Net altogether. :)

You can download the Telerik’s JustDecompile from HERE.

image

Its free and available as Beta release. So go ahead download and start using it. You can request to telerik guys to add if something is missing or found any bug or some new features in the next coming builds.

Now how to see the IL code:

After Installation launch the JustDecompile tool and go to Open

image

Now select your DLL you want to watch the IL for It’ll get loaded into the Assembly list browser on the left side:


image

Now select the node and you’ll see the code on the lefthand side pane. In the Top Menu ribbon you’ll find a Dropdown. you can make your choice what you wanted to see you code in

  • IL
  • C#
  • VB.NET

image

I chose this tool just to see the IL code but it gave me more than that-

image What more It provide is, you can find the usage by FindUsage utility, Search is there to analyze a large assembly. And since the name is as DecCompiler it can decompile the assembly and will generate the Project too for you. by Click on the “CreateProject” It’ll generate the project for you for the selected Tree node.

Convert your code from C# to VB.Net and Vice versa

1. Launch the tool, open the Assembly and select the appropriate node that’ll show your code. Now select the option from Dropdown in the Menu ribbon and see the magic.

image

You can also opt for the Version of the framework too. and Silverlight framework is also supported.

image

This small utility impressed me and I came to write this post. I hope you liked it.

Tuesday, 13 September 2011

Watch the keynote from the Build developer conference Windows 8

Watch the keynote from the Build developer conference




For more info visit Windows Dev Center
http://msdn.microsoft.com/en-us/windows/home

To Download the Developer Preview tools Download.

Thursday, 8 September 2011

C# keywords rarely known but frequently asked in Interview Questions

There are few words that we rarely use in day to day C# practices[I’m focusing readers who are beginners]. But I’ve seen them in either online exams or other IT quiz shows So I came to write something about those untouched keywords. Below is the list of these keywords

  • Implicit
  • Explicit
  • Volatile
  • Checked
  • Unchecked
  • Const vs ReadOnly [The most frequently asked Interview question for C# programmer]

Lets get to know about them which one is used where and when:

Implicit

The implicit keyword is used to declare an implicit user-defined type conversion operator. Implicit conversion operators can be called implicitly, without being specified by explicit casts in the source code. It eliminates unnecessary casts, implicit conversions can improve source code readability.

The below example you can see we’ve a CustomType that takes Integer value as its initializing value and after defining the Implicit operator It becomes directly castable to int.

image


However, because implicit conversions can occur without the programmer's specifying them, care must be taken to prevent unpleasant surprises. In general, implicit conversion operators should never throw exceptions and never lose information so that they can be used safely without the programmer's awareness.

Explicit

As I mentioned sometimes implicit conversion can surprise you as it can go unnoticed. So in case you want to enforce an casting to be explicit then Explicit keyword is there. Again The explicit keyword is used to declare an explicit user-defined type conversion operator.

class MyType
    {
        public static explicit operator MyType(int i)
        {
            // code to convert from int to MyType
        }
    }

Unlike the Implicit it enforces the explicit cast to mention when a type is declared with conversion operator.

image

Volatile:

Volatile is kept under the category of Modifiers. The volatile keyword indicates that a field can be modified in the program by something such as the operating system, the hardware, or a concurrently executing thread.

Syntax:

public volatile int i;

Behavior: The system always reads the current value of a volatile object at the point it is requested, even if the previous instruction asked for a value from the same object. Also, the value of the object is written immediately on assignment. And due to such behavior  volatile modifier is usually used for a field that is accessed by multiple threads without using the lock statement to serialize access. Using the volatile modifier ensures that one thread retrieves the most up-to-date value written by another thread.

The type of a field marked as volatile is restricted to the following types:

  • Any reference type.
  • Any pointer type (in an unsafe context).
  • The types sbyte, byte, short, ushort, int, uint, char, float, bool.
  • An enum type with an enum base type of byte, sbyte, short, ushort, int, or uint.

 

Checked and Unchecked:

Before we start I want to show you some code:

public static void Main() {     short x = 32767;   // Max short value     short y = 32767;     int z = 0;     //perform the sum and try cast it back to short before assigning     z = (short)(x + y);     Console.WriteLine("Checked output value is: {0}", z);     Console.Read(); }

Output:

image?????????????????????

Are you expecting this output in you application or Program. Better you throw an exception if you system is dealing with sensitive data. If you think so.. then use Checked.

Syntax:

checked(expression)

Now modify the above code like this:

try {     z = checked((short)(x + y)); } catch (System.OverflowException e) {     System.Console.WriteLine(e.ToString()); }

Now see the output:

image

Important Note: In a checked context, if an expression produces a value that is outside the range of the destination type, the result depends on whether the expression is constant or non-constant. Constant expressions cause compile time errors, while non-constant expressions are evaluated at run time and raise exceptions.

Similarly if you want to Skip such check always if your application or logic is flexible and ineffective by the resulting values then use unchecked.

Syntax:

unchecked (expression)

int z = unchecked((short)(x + y));

Output would be the same as we had without using checked.

image

if neither checked nor unchecked is used, a constant expression uses the default overflow checking at compile time, which is checked. Otherwise, if the expression is non-constant, the run-time overflow checking depends on other factors such as compiler options and environment configuration.

const vs readonly

So here we are at Interview Question. I’m sure these words are mostly used in code. So I’m not going show any demo for their use but to discuss some interesting answers that your interview would like Winking smile.

const value type

  • must be initialized
  • initialization must be at compile time

A constant member is defined at compile time and cannot be changed at runtime. Constants are declared as a field, using the const keyword and must be initialized as they are declared.

Constants must be a value type (sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool), an enumeration, a string literal, or a reference to null.

readonly value type

  • It can use default value, without initializing
  • initialization can be at run time

  • can be initialized either at the declaration or in a constructor

A read only member is like a constant in that it represents an unchanging value. The difference is that a readonly member can be initialized at runtime, in a constructor as well being able to be initialized as they are declared.

I hope this post provide some quick and useful information to those who are beginners in C#.

Wednesday, 7 September 2011

Synchronize UI when task is in progress or completed TPL .Net 4.0

Using TPL for parallel programming is now a cup of cake. It made life easier for those who are new to multithreaded programming. Bunch of code lines can be encapsulated as an individual task using Task class and you are flexible to run the task either in Sync or Async mode. In Sync mode the UI freeze for moment until the task gets completed since all other threads are blocked. So for a good user experience you don’t want to let your application screen freezes for moment so Async task is a good choice in such case.

This post is to show how to notify the UI when the Asycn task gets completed. Absolutely you will want to get notify when you Asycn task has completed its work/execution.

Task.ContinueWith() is the function that will execute the next task after completion of the invoking task.

Syntax:
.ContinueWith((result) =>
                {
                    //UI updation code to perform
                }, new CancellationTokenSource().Token, TaskContinuationOptions.None,
                //Right way to synchronize the UI with the completion of invoking task on ContinueWith
                TaskScheduler.FromCurrentSynchronizationContext());

Let take an example of simple windows forms application that can process images to generate the thumbnails:


First let design the UI like this:

image

[I’m still using WinForms just to save my time in creating demos Smile with tongue out.]

In the Form1.cs code behind file I’ve create a function ProcessFilesInParallel() that will get enabled when user select the ParalledMode checkbox from the UI. Rest MaintainQuality Checkbox is toggling in two functions and limit files dropdown can limit you file processing and will Cancel the processing immediately the limit reaches. I’m not going to explain the other functional code you can download the sample and do analyze the code here but we’ll focus on UI updation while task in progress and when the task gets complete.

The mail task to perform is to show the progress bar progressing and Show tittle analytical summary of the task when completed. Below is the complete code of PracessfilesInParallel() method:

private void ProcessFilesInParallel()
        {
            ParallelOptions parOpts = new ParallelOptions();
            parOpts.CancellationToken = cancelToken.Token;
            parOpts.MaxDegreeOfParallelism = Environment.ProcessorCount;

            string[] files = Directory.GetFiles(sourcePath, "*.jpg");
            long count = 0;
            totalfiles = files.Length;
            btnCancel.Visible = true;
            //--- Record the start time---
            DateTime startTime = DateTime.Now;

            try
            {
                Task t1 = Task.Factory.StartNew(() =>
                {
                    try
                    {
                        Parallel.ForEach(files, parOpts, currentFile =>
                        {
                            //Check if cancellation requested
                            if (cancelToken.Token.IsCancellationRequested)
                            {
                                cancelToken.Token.ThrowIfCancellationRequested();
                            }

                            string filename = Path.GetFileName(currentFile);
                           
                            //Threadsafe updation to shared counter
                            count = Interlocked.Increment(ref count);

                            if (islimited && fileLimit <= count)
                            {
                                cancelToken.Cancel();
                               // MessageBox.Show("Limit reached fileLimit = " + fileLimit + " Count=" + count);
                            }

                            if (isQuality)
                                GenerateThumbnail(filename);
                            else
                                GetThumb(filename);

                            //update the progress on UI
                            progressBar1.Invoke((Action)delegate { ReportProgress(count); });
                        });
                    }
                    catch (OperationCanceledException ex)
                    {
                        progressBar1.Invoke((Action)delegate { ReportProgress(0); });
                        MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }

                    //ContinueWith is used to sync the UI when task completed.
                }, cancelToken.Token).ContinueWith((result) =>
                {
                    //Note the time consumed here
                    TimeSpan elapsed = DateTime.Now.Subtract(startTime);
                    TimeElapsed = (int)elapsed.TotalSeconds + " s : " + elapsed.Milliseconds + " ms";

                    //finally update the UI with the summary result
                    lblResult.Invoke((Action)delegate { lblResult.Text = "File Processed: " + count + " out of " + fileLimit + " Time Elapsed: " + TimeElapsed; });
                },new CancellationTokenSource().Token, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
            }
            catch (AggregateException ae)
            {
                MessageBox.Show(ae.InnerException.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

As you can see I’ve used control.Invoke() method because if you don’t use it’ll throw error of cross thread operation is invalid or something like that. so you have invoke the object in the currently executing thread.

Other important is to use TaskSchecutler.FromCurrentSynchronizationContext() function as parameter as this is the best fit to use if you are going to update UI in the ContinueWith() task delegate.

image

So when you’ll run the code the output would be something like this:

image

The code to show progress is also written in the function ProcessinParallel() method:

//update the progress on UI
progressBar1.Invoke((Action)delegate { ReportProgress(count); });

Note - The sample attached have all the running code for you.

SNAGHTML192c8af4

I hope you enjoyed this post cause I enjoyed lot creating this demo. Smile

Download the complete sample source code in the article