Task.WaitAll freezes UI with Control.Invoke() method.

Parallel tasks are important to complete the independent operation simultaneously. It makes us completely very heavy and time taking processes in less time when these operations run in multi-core environment but we have to follow the rules to make this multi-tasking to work.

Today I experienced such a case where my written code put me in a condition of “Dead Lock”. It is a situation more than one task that want to acquire the same resource and one is already holding this resource but another also wants to access it. If no task able to complete its operation then it creates a deadlock situation.

When we creating application, in some cases it may be possible to update the UI in various threads. E.g. Progress reporting. I found a case that let our application put into a situation which freezes the application. Let there was few tasks that are independent of each other but we need to merge the result all of these tasks with some required condition.

List<Task> tasks = new List<Task>();
//Create and start independent tasks
tasks.Add(Task.Factory.StartNew<List<string>>(() => CreateInitialData()));
tasks.Add(Task.Factory.StartNew<List<string>>(() => CreateValidationData()));
tasks.Add(Task.Factory.StartNew<List<string>>(() => CreateGUILookup()));

Now we need to complete these tasks to get the results so that we can merge it. To do this, the Task Parallel Library has Task.WaitAll method which takes array of task as a parameter. It waits until all the operations do not complete. In other words, it hold the UI and waits to complete all the tasks.

Task.WaitAll(tasks.ToArray());
//Merge result of all task on completion

In one of the thread, some subtask is done which make a call to the UI. It was working fine for a while until I made some changes. I was trying to get one property of the progress bar and it was accessed in an asynchronous way using the “BeginInvoke” method. It was a bug in the application which does not return the correct results so I replace it with the “Invoke” method.

“Control.Invoke()” method waits and returns the results immediately while BeginInvoke method is an asynchronous approach. It leaves control from the current statement without returning the values and we are not able to get returned results until we call AsynResult.EndInvoke().

//At some instance code by mistake try to access 
// the properties of the any control and made dead lock
// 
int progress = (int)this.Invoke((Func<int>)delegate 
{ return progressBar1.Value; });
System.Diagnostics.Debug.Write(progress);

Now what WaitAll does, it blocks until all tasks have finished. The tasks can't finish because Invoke will run its action on the UI thread, which is already blocked by WaitAll. It is creating deadlock because Invoke waits for the UI thread to unblock.

Complete example:

namespace ParallelWaitDeadLock
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            List<Task> tasks = new List<Task>();
            //Create and start indepenet tasks
            tasks.Add(Task.Factory.StartNew<List<string>>(() => CreateInitialData()));
            tasks.Add(Task.Factory.StartNew<List<string>>(() => CreateValidationData()));
            tasks.Add(Task.Factory.StartNew<List<string>>(() => CreateGUILookup()));
 
            Task.WaitAll(tasks.ToArray());
            //Merge result of all task on completion
       
        }
 
        private List<string> CreateInitialData()
        {
            //
            Task.Delay(1000);
            return new List<string>();
        }
 
        private List<string> CreateGUILookup()
        {
            //
            Task.Delay(1000);
            //At some instance code by mistake try to access 
            // the properties of the any control and made dead lock
            // 
            int progress = (int)this.Invoke((Func<int>)delegate 
            { return progressBar1.Value; });
            System.Diagnostics.Debug.Write(progress);
            return new List<string>();
        }
 
        private List<string> CreateValidationData()
        {
            //
            Task.Delay(1000);
            return new List<string>();
        }
    }
}

We need to take care to avoid such a situation when subtask tries to do UI relation operations even the parent task holds the UI and waits to complete the task.

It is causing a deadlock. The UI thread is waiting for the all tasks to be completed. UI resources are already locked by the Task.WaitAll and then we are trying to invoke code on the UI thread which is causing "Deadlock".

Task.WhenAll() method will return a new task that will be marked as completed when all tasks have completed. If we await this task, UI thread will be freed, and so the routine will be able to invoke code on the UI thread, avoiding a deadlock.

We should use Task.WhenAll() instead.  

await Task.WhenAll(tasks.ToArray());

How to create Node.js development environment in Visual Studio?

Now Visual studio is enriched with the tools that turn Visual Studio into a powerful Node.js development environment. Node.js Tools for Visual Studio is free and open source plug-in built on top of Visual Studio 2012, 2013, or 2015. This tool has enable following feature for Node.js development:

  • Intelligent code completion
  • Advanced debugging and profiling
  • Integration with other Visual Studio features and 3rd party tools
  • Node.js, io.js, JavaScript, Typescript, HTML, CSS, and JSON support

Installation:
To create Node.js development environment in Visual Studio follow the below steps:

  1. Install Visual Studio
    Node.js Tools for Visual Studio supports Visual Studio 2012 Update 4, Visual Studio 2013 Update 4 and higher. It also support community version of Visual Studio. Visual Studio Community is a free, fully featured, and extensible IDE for individual developers, open source projects, academic research, education, and small professional teams. Create applications for Windows, Android, and iOS as well as web applications and cloud services. Build apps for any platform. Use designers, editors, debuggers, and profilers in a single tool. Access thousands of extensions and more. Go to Visual Studio download page and download which flavor of Visual Studio application you want to use.
  2. Install Node.js Tools for Visual Studio
    Node.js Tools for Visual Studio installs via msi installer and takes few minutes. Just download the appropriate version of the tools according to the Visual studio that you have installed. The latest release of tools is Node.js Tools 1.1.1 and if you have installed Visual Studio 2012 or 2013 then download tools that relevant to your Visual Studio installation.
    clip_image002_thumb[2]
    After downloading the tools follow the installation wizard to complete the installation. Currently I am using Visual Studio 2013 so I am using tools compatible with Visual Studio 2013.

    clip_image003_thumb[1]
    Click next and then accept License agreement to complete the installation.
  3. Install Node.js and Get Started with Node Tools for VS
    in last step, we need to install Node.js interpreter and Azure tools (for deployment). Actually Node.js Tools for Visual Studio requires a Node.js interpreter to be installed to work with Node.js. Node.js is built for 32-bit and 64-bit architectures.
    Node.js (x86): https://nodejs.org/dist/v0.12.7/node-v0.12.7-x86.msi
    Node.js (x64): https://nodejs.org/dist/v0.12.7/x64/node-v0.12.7-x64.msi
    Azure Tools:
    Azure Tools for VS 2015: http://go.microsoft.com/fwlink/?LinkId=534216
    Azure Tools for VS 2013: http://go.microsoft.com/fwlink/p/?linkid=323510
    Azure Tools for VS 2012: http://go.microsoft.com/fwlink/p/?linkid=323511

Now we are ready to start working with Node.js in Visual Studio and going to see the installed temples for the Node.js projects.
To create a project, Select New Project from File menu. You will find Node.js templates in Installed Templates under JavaScript section. Click on Node.js and you will find several template to create Node.js projects.

clip_image005_thumb[2]

Select “Blank Node.js Web Application”. Enter a project name “NodejsWebAppTest” and location and click OK.

Once Visual Studio completes the process to create the project then it opens “server.js” file in the editor. It is just like a program which prints “Hello world” on the console.

var http = require('http');
var port = process.env.port || 1337;
http.createServer(function (req, res) {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello World\n');
}).listen(port);

Now press F5 to run the application in browser. In my case what happened, I missed the step 3 – Installing Node.js. Due to this reason an Information dialog appear on my screen telling that you have not installed Node.js.
clip_image006_thumb[1]

Then I have to download Node.js and install it before running this application again. Here are the steps to install Node.js:

  1. Run the downloaded application and it will popup below welcome screen. Click Next.
    clip_image007_thumb[1]
  2. Accept License agreement to complete this step and then click Next.
    clip_image009_thumb[1]
  3. After this step it will ask you to specify the destination folder where it should be installed.
    clip_image011_thumb[1]
    This is global installation of Node.js which is referenced in the projects. We can specify the path to a local interpreter in each of your Node.js projects.
  4. After that click next and at last step, click install to start installation process.
    clip_image013_thumb[1]

When this process complete then again try to run the application. Just press F5 and you will see the results in the browser.

clip_image015_thumb[1]

Conclusion:
Now we have a Node.js development environment up and running in Visual Studio. There are lots features included in the IDE for development of Node.js as we are debugging a C# code. E.g. Debugging, IntelliSense, Profiling and Interactive windows also.

How disable path editing in BreadCrumbEdit control?

Recently I have implemented DevExpress BreadCrumbEdit control in my application and in the implementation I need to disable editing of the path in the control. In technical words, I need BreadCrumbEdit control in only Select mode rather the Edit Mode. Initially it can be set using the BreadCrumbEdit’s BreadCrumbMode property to “Select”.
I found one solution that it is impossible to prevent switching to the Edit mode. The easiest way DevExpress guys suggest that handle the BreadCrumbEdit's PropertiesChanged event and reset it back to “Select” if it try to go in the “Edit” mode. So I did it in the following manner:

C#

private void breadCrumbEdit1_PropertiesChanged(object sender, EventArgs e)
{
    if (breadCrumbEdit1.Properties.BreadCrumbMode == BreadCrumbMode.Edit)
    {
        breadCrumbEdit1.Properties.BreadCrumbMode = BreadCrumbMode.Select;
    }
}

VB

Private Sub breadCrumbEdit1_PropertiesChanged(sender As Object, e As EventArgs)
    If breadCrumbEdit1.Properties.BreadCrumbMode = BreadCrumbMode.Edit Then
        breadCrumbEdit1.Properties.BreadCrumbMode = BreadCrumbMode.Select
    End If
End Sub

DevExpress - Response.Redirect cannot be called in a Page callback

Scenario:

DevExpress Web controls generates callback to refresh the controls and pass data between events. When we using some Callback panel or ASPxGridView callbacks event methods then we cannot call Respose.Redirect method to navigate between pages. If we use these methods then it will raise exception.

Solution:

To avoid these exception use the ASPxWebControl.RedirectOnCallback method to rather than pages.Response.Redirect() because it does not work in a callback. Let you have created a callback with “MYCallback_Callback” event handler method then at the callback method you should use below ASPxWebControl.RedirectOnCallback method to redirect on another page.

DevExpress.Web.ASPxClasses.ASPxWebControl.RedirectOnCallback("~/MyPage.aspx?id="+ e.Parameter);

You will not be able to use Response.Redirect () or Server.Transfer () in a callback to check if the control has a client event can be used instead, if this event can use window.location.replace("MyPage.aspx"), using JavaScript on the client to move to another page.

DevExpress v15.2 Released – What’s is new this version?

 

I have attended DevExpress Webinars consecutively in last few days and there was lots of features they included in the newer version v15.1. All the technology persons Mehul, Don, Julian and Bukcnall described all these features with much clearly and I found that they are much valuable to increase the productivity of the developers. Here are list of webinars related to DevExpress v15.2 build:

Mehul Harry
Don Wibier

v15.2: What's New for DevExtreme & HTML5

03-Dec-2015

Julian M Bucknall
Paul Usher

v15.2: What's New for Reporting and Dashboards

02-Dec-2015

Julian M Bucknall
Paul Usher

v15.2: What's New for Windows Developers

01-Dec-2015

Mehul Harry
Don Wibier

v15.2: What's New for ASP.NET Developers

30-Nov-2015

The amazing thing that I liked most is “Grid-Based Report Generation”. This release ships with a new WinForms Grid-based report generation option. With only a few lines of code, you can invoke the DevExpress WinForms Report Designer from the Grid Control and create reports based on its data.

clip_image002 

Currently I am working with WinForms controls so I found few new control in the WinForms control suite:

  • Diagram Control
  • Date Editor & Calendar Control
  • Excel Data Source
  • Ring/Line Animations
  • Tabbed Form
  • Tabbed Pane Control
  • Toolbox Control
  • Clipboard Management

    the amazing thing they have included is Clipboard management. It was the desired functionality for us because every time we need to write custom code to implement this functionality. Before that it was not easy to copy the Grid Control content to another program including the formatting rules e.g. cell colors. Check this out.
    clip_image003

More interesting controls also included in the ASP.NET WebForms suite also:

Card View Control:

 It is packed with new features like Batch Editing, Conditional Formatting, Export to PDF, XLS, XLSX and RTF Formats, Selected Records Export, Conditional Formatting Export, Header Panel, Total Summary, Endless Paging, Date Range Header Filter, Ellipsis with tooltips in cell texts, Design-Time Card Layout Editor allows you to build a Microsoft Outlook inspired Contacts View with integrated data shaping and editing capabilities.

clip_image005

ASP.NET QueryBuilder Control

Right now this control is available in CTP, but this DevExpress ASP.NET Query Builder allows you to visually construct SQL queries and return a string containing a SELECT statement. It is enriched with cool features.

clip_image007

This control can automatically obtain and display database schema within the QueryBuilder's UI. It has ability to visually edit 'WHERE', 'ORDER BY' and 'GROUP BY' query clauses. Relationship management is required feature for a query builder and they have availed and relationships between tables are automatically resolved based on foreign keys in the control. Along this we can see the Query results preview also.

There are many more features included in ASPxGridView – Responsive Layout, Adaptive layout, export with Format Conditions, Scheduler Control and others. XAF, DevExtreme & HTML5, Reporting, WPF, CodeRush.

The main improvement what DevExpress bring to the Developer community is that they have improved the performance of the control on each platform. Performance is main concern while using the third party controls and within this release they have focused on it also.

Enjoy new Office 2016 style themes also. Smile

The complete features details are available about the DevExpress v15.2 here. Hope this will help you explorer amazing fast DevExpress controls.

How to use ValueConverter (Decimal Converter) during data binding with control?

Scenario:

While using DevExpress WPF control, sometimes it requires to convert the binding value according to the control’s property. In that case we need use the Value Converters in this case.
Let we require to bind the SpinEdit WPF control edit value property with some object property which require to be converted to decimal value. To do that we need to follow below steps:

  1. Create a custom converter class which implements IValueConverter to convert the value to the decimal.
    namespace DevExWpfApp
    {
        public class DecimalConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                return System.Convert.ToDecimal(value);
            }
    
            public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                throw new NotImplementedException();
            }
        }
    }
    
  2. Now use it in the XAML by declare it as resources and then call it as below:
    <UserControl.Resources>
    <local:DecimalConverter x:Key="DecimalConverter"/>
    </UserControl.Resources>
    
       <dxe:SpinEdit EditValue="{Binding Entity.MaxValue, Converter={StaticResource DecimalConverter}" />

Install .NET Framework 3.5 in Windows 8 and 10

Windows 8 and 10 comes with .NET framework 4 or higher pre-installed, but there are lots of applications require the .NET framework v3.5 installed to install on these newer version of operating systems. These applications will not run unless you will install the required version of .NET framework. When you try to run any such sort of applications then Windows 8 and 10 will prompt you to download and install .NET framework 3.5 from the Internet. However, this will take a lot of time.

Source: MSDN article.
Below are the steps to enable .NET framework 3.5:

  1. Go to Settings. Choose Control Panel then choose Programs.

    clip_image002
  2. Click Turn Windows features on or off, and the user will see window as image below.

    clip_image004

    clip_image006

    You can enable this feature by click on .NET Framework 3.5 (include .NET 2.0 and 3.0) select it and click OK. After this step, it will download the entire package from internet and install the .NET Framework 3.5 feature.

You can save your time and install .NET Framework 3.5 from the Windows 8 and 10 installation media respectively. This method is much faster and does not even require an Internet connection.
Follow below steps to install .NET Framework 3.5 in Windows 8 and 10 using DISM:

  1. Bring your installation media to prepare installation either it is DVD or ISO image. If you are using ISO image then mount it using software e.g. Power ISO, DAEMON Tools so then you will be able to access the files for the installation.
    Packages are located in the drive letter: \sources\sxs directory.
  2. Open CMD.EXE with Administrative Privileges. Right click on the start button (or press “Win + X”) to popup the system menu. There you will find a menu item titled “Command Prompt (Admin)”. Click on this to launch the command prompt in admin mode.
    image
  3. Run the following command and hit Enter.
    Dism.exe /online /enable-feature /featurename:NetFX3 /All /Source:E:\sources\sxs /LimitAccess

    clip_image009
    Please make sure to change the source path:
    e.g.
    If you have Windows setup at “D:” drive, replace “E:” with “d:”
    If you have Windows setup at “F:\Win10Setup” folder path, replace “x:” with “f:\Win10Setup”
    When run from the command prompt, it will start installing the .NET framework. It will take a while to complete the whole process. Once done, restart your system for the changes to take effect.

Details on command line parameters of DISM:

  • /Online targets the operating system you're running (instead of an offline Windows image).
  • /Enable-Feature /FeatureName:NetFx3 specifies that you want to enable the .NET Framework 3.5.
  • /All enables all parent features of the .NET Framework 3.5.
  • /LimitAccess prevents DISM from contacting Windows Update.
  • /Source specifies the location of the files needed to restore the feature (in this example, the x:\sources\sxs directory).

After completion of this process .NET Framework 3.5 feature enabled. Restart and then you good to go for the installation of your application.

How to enable required field validator in a particular row of GridView?

Scenario:
In some cases editing is enabled on the selected row when you doing batch editing in ASP.NET GridView or DevExpress Grid Control. During edit operation we need to validate only these selected rows editor controls so that it will not block or validated another rows. It require to enable only associated cell validators in the editing rows.

Solution:

Let we have a checkbox in each row to select the editing row to enable the validator controls. Then we have to follow below steps:

First you need to add server event on Check Box control of Change event fire.

<asp:CheckBox ID="chkbox" runat="server" OnCheckedChanged="chkbox_CheckedChanged"    AutoPostBack="true"/>

Then fire of checked event of Checkbox you need to enable/disable RequiredFieldValidator server control.

protected void chkbox_CheckedChanged(object sender, EventArgs e)
{
   CheckBox chkbox= sender as CheckBox;
   GridViewRow currentRow = chkbox.NamingContainer as GridViewRow;
   RequiredFieldValidator rfv = grdCustomer.Rows[currentRow.RowIndex]
                                      .FindControl("ValReqED") as RequiredFieldValidator;
   if (chkCustomer.Checked)
   {
      rfv .Enabled = true;
   }
}

ASPX:

<asp:GridView ID="grdView" AutoGenerateColumns="false" BorderWidth="0" OnRowCommand="grdView_RowCommand" runat="server" CssClass="table">
    <Columns>
        <asp:TemplateField HeaderText="Save It">
            <ItemTemplate>
                <asp:CheckBox ID="chkbox" runat="server" AutoPostBack="true" OnCheckedChanged="chkbox_CheckedChanged"/>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Expiration Date">
            <ItemTemplate>
                <asp:TextBox ID="txtExpirationDate" style="padding:12px 5px;" placeholder="(mm/dd/yyyy)" CssClass="datepiker" runat="server"></asp:TextBox>
                <asp:RequiredFieldValidator ID="ValReqExpD" Enabled="false" Display="Dynamic" runat="server" ErrorMessage="Expiry Date cannot be Blank." ControlToValidate="txtExpirationDate"></asp:RequiredFieldValidator>
                <asp:RegularExpressionValidator Display="Dynamic" ID="ValRegExpD" runat="server" ControlToValidate="txtExpirationDate" ErrorMessage="Enter a valid Expiry Date ." ValidationExpression="([1-9]|0[1-9]|1[012])([-/.])([1-9]|0[1-9]|[12][0-9]|3[01])([-/.])(19[5-9][0-9]|20[0-4][0-9])">
                    <b>Enter a valid Renewal Date</b>
                </asp:RegularExpressionValidator><br />
                <asp:CompareValidator ID="ValCmpSD" Display="Dynamic" runat="server" ControlToCompare="txtEffectiveDate" ControlToValidate="txtExpirationDate" ErrorMessage="Expiry Date should be greater than Effective date" Operator="GreaterThan" Type="Date"></asp:CompareValidator>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Healthy eye tips for IT professionals to keep their vision correct

Looking at current trend of advancements in technology, spending long hours in front of television, computers & mobile screens is becoming part of life style today. But in IT industry, we have to spend most part of our day in front of the computer screen to do our work. In all of this daily routine we forget about one of the most important parts of our body, the eyes. The ones that itch from sheer exhaustion and burn tirelessly after the end of a really long day. This can lead to eyes and vision related problems in future.

We might not feel the need to exercise your eyes because well, there aren't any immediate symptoms or signs of weak or tired eyes but if we want to guard our self from hazy spots and blurry vision in the future, then we suggest you exercise them as often as possible. And the eye workout is that you can do it at any given time of the day and all we need are a few minutes to avoid future problem with that part which required to do job for the living.
Here are the few EYE related tips

Ø After every 20 to 30 minutes of work, look at a distant object and blink several times. This will help in better focusing and relaxation of eye muscles

Ø Blink frequently. People tend to reduce blink rate while working on computer. This can lead to dry eyes. Avoid staring at screens & objects for long.

Ø Exercise your eyes at frequent intervals. Eye exercise is simple. All you need to do is blink several times, then close your eyes and roll them in clockwise and anti-clockwise direction. While doing this, breathe deeply but slowly and open your eyes slowly after doing this.

Ø Rub your palms against each other till they become warm. Cover your eyes with your warm palms for a minute. You will experience soothing effect in your eyes.

Ø Splashing water on your face during breaks can keep you refreshed. This also helps in cleaning and cooling your eyes.

Ø A few minutes of walk during breaks will refresh your body and mind. It is also good for your eyes as walking increases blood supply to your eyes.

Ø Position the monitor and lights in such a manner that glare from the screen is minimum. 

Few tips are simple Yoga that help to avoid eye problems. We've put together few simple yoga exercises that that will help ease out overused muscles, reduce tension in the face and eyes and help your eyes focus.

Source - Yoga for eyes
here are few yoga exercises that that will help ease out overused muscles, reduce tension in the face and eyes and help your eyes focus.

  • Blink - Open your eyes wide and then quickly blink about 10 times. Now, close your eyes for about 20 seconds and repeat this exercise four more times. The human eye should blink about 25 times in one minute. However, many of us don't, especially when we're focusing on something on our computer or smartphone. This exercise helps your eye nourish itself, relaxes the eye muscles and prevent dry eyes.
  • Palming - If you've gone for yoga classes at any point in time you'll be familiar with this one. Rub your palms together till they feel warm. Then place them on your eyes and hold the position till your palm feels warm. Concentrate on something and relax. This exercise is another form of relaxation which is something your eyes could use, especially after a long day at work.
  • Sideways & Rotation - So now you want to stretch your eye muscles. Move your eyes slowly from side to side and then all the way around in a circle. If you find that difficult, then use your finger and move it in a circle, and let your eyes follow. Make sure your neck doesn't move and repeat both those exercises about 20 times.
  • Sarvangna Asanaor the shoulder stand - This exercise doesn't just help your eyes but your brain as well. Lie down on a mat and using your arms, life your body waist downwards in the air so that your legs are straight and toes point outwards. This pose stimulates blood circulation in brain and optic nerve. You can also lay on your back and life your legs upward, as high as you can go. This exercise increases blood circulation to the eyes, brain, ears and nose, thereby improving their functioning. This pose also helps you detoxify and maximize the performance of all the other organs.

          clip_image001

  • Bhramari Pranayama - Also known as the humble bee breath, this exercise is really calming and can drown down the unnecessary noise in your head, making you feel relaxed with just a few breaths. Sit on the floor cross-legged or however you feel comfortable. Now place your fingers over your eyes horizontally. Exhale and when you inhale make a bee like buzzing sound. Make sure you apply very little pressure on the eyeball and keep your lips sealed.

Some more helpful exercises: Yoga for Eyes: Improve Eyesight Naturally

Free Programming Books

There was thread on Stackoverflow which contribute the list of free programming books. The Original Source for these free books as below:
 List of freely available programming books
Further I found a nice maintained list on GitHub – Free programming books and subset of the list is here:

Parallel Programming
Partial Evaluation
Professional Development
Programming Paradigms
Regular Expressions
Reverse Engineering
Security
Software Architecture
Standards
Theoretical Computer Science
Web Performance