Niranjan Kala's coding blog

on software development and productivity

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

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.


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;


<asp:GridView ID="grdView" AutoGenerateColumns="false" BorderWidth="0" OnRowCommand="grdView_RowCommand" runat="server" CssClass="table">
        <asp:TemplateField HeaderText="Save It">
                <asp:CheckBox ID="chkbox" runat="server" AutoPostBack="true" OnCheckedChanged="chkbox_CheckedChanged"/>
        <asp:TemplateField HeaderText="Expiration Date">
                <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>

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.


  • 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
Software Architecture
Theoretical Computer Science
Web Performance

Orchard CMS Learning stuff.

Recently I try to learn about the CMS which are developed in Microsoft technologies as there are lots of mature CMS available like joomla, Druple etc. These are based on the PHP and mostly hosted on apache(Linux based web server). Though I am working on .net stack so I decided to start with some open source CMS developed in technology and I decided to start learning with Orchard.

What is Orchard:
Orchard is a free, open source, community-focused Content Management System built on the ASP.NET MVC platform.

Orchard is built on a modern architecture that puts extensibility up-front, as its number one concern. All components in Orchard can be replaced or extended. Content is built from easily composable building blocks. Modules extend the system in a very decoupled fashion, where a commenting module for example can as easily apply to pages, blog posts, photos or products. A rich UI composition system completes the picture and ensures that you can get the exact presentation that you need for your content.

Here are few learning resources that I want to share with others also:

              How to resolve “The 'DesignerPackage' package did not load correctly” issue??

              It was the today morning I just start preparing to do my work and opened Visual Studio. Now what I found that there was lots popup showing the error for load fail of the designer packages respectively.

              The error  was “The 'DesignerPackage' package did not load correctly” and I did following trick to solve this issue in Visual studio 2013. If you are using older version then look for 11.0 or 10.0 folder for this “ComponentModelCache” directory.

              1. First open windows explorer and go to “C:\Users\<your users name>\AppData\Local\Microsoft\VisualStudio\12.0\ComponentModelCache”.

              2. Delete all the files located in this folder after closing the visual studio.

              After doing this start your visual studio and all errors went away.

              How to iterate through TileView items in XtraGrid?

              This is related to DevExpress question - How to loop through tiles in TileView, which help me to achieve the required functionality in the XtraGrid using the TileView. I require to implement the selection process for TileView similar to GridView in XtraGrid, but I require to iterate through all the TileView items. TileView actually use TileViewControl internally so it require to access under laying  tileview control items to access more information about the TileViewItems. See the below code snippet:

              private void HandleTileItemSelection(TileViewItem tileViewItem)
                  if ((ModifierKeys & Keys.Control) != Keys.Control)
                      Dictionary visibleTiles = ((tileView1.GetViewInfo() as ITileControl).ViewInfo as TileViewInfoCore).VisibleItems;
                      int alternateCheckedItemsCount = 0;
                      foreach (KeyValuePair item in visibleTiles)
                          if (item.Value != tileViewItem && item.Value.Checked)
                              item.Value.Checked = false;
                              tileView1.SetRowCellValue(item.Value.RowHandle, "CheckedStatus", false);

              RANDBETWEEN(m,n) in Sql Server?

              Today I have to find random number between two numbers lots of the time in the stored procedures So I tried to create a function which return random numbers between two boundary numbers m and n. I tried to look for the solution and got below logic to implement the function.

              Let m = 5 and n = 500 and method call would be RANDBETWEEN(5, 500). Then logic to find the random number would be as below:

              • Use RAND() (which returns a value between 0 and 1 (exclusive).
              • multiply by 298 (since you want a dynamic range of [300-3] = 297 + 1)
              • add 3 to Offset
              • and cast to INT?
              SELECT CAST(RAND() * 298 + 3 AS INT)
              A Stored Procedure can be written like this if it supposed to be reuse in code more often:
              @LowerBound int = 0 ,
              @UpperBound int = 1 , 
              @ret int OUT
                  SET NOCOUNT ON;
                  SELECT @ret = (CAST((RAND() * (@UpperBound - @LowerBound)) + @LowerBound AS INT));
              RETURN ;

              Call can be made like this:

              DECLARE @tmp INT;
              EXECUTE [dbo].[RANDBETWEEN] 0,10, @ret=@tmp OUT ;
              SELECT @tmp

              To create a function I found that I have to create a View that make random method call and then function will do remaining operation to get the random number.

              CREATE VIEW Get_RAND
              SELECT RAND() AS RANDNumber

              Then you can create a function like this (accessing the view with the SELECT RandomNumber... ) :
              CREATE FUNCTION RANDBETWEEN(@LowerBound INT, @UpperBound INT)
              RETURNS INT
                  DECLARE @TMP FLOAT;
                  SELECT @TMP = (SELECT RandomNumber FROM Get_RAND);
                  RETURN CAST(@TMP* (@UpperBound - @LowerBound) + @LowerBound AS INT);

              Then this function can be called as below:

              SELECT [dbo].[RANDBETWEEN](1,10)

              WCF or ASP.NET Web APIs for web services??

              This is a interesting question for everyone and especially for me too. Whenever I got chance to dig for these technologies to create service, I found myself little confuse that which one should I choose.

              It may be the “WCF vs ASP.NET Web API” contest for choosing in particular scenario and requirement of client. I got lots of reference and comparison related these two things which are discussed below:

              The ASP.NET Web API is a continuation of the previous WCF Web API project (Conceptual changes are described on Codeplex WCF documentation - How to Migrate from WCF Web API to ASP.NET Web API).

              Here is comparison from MSDN - WCF and ASP.NET Web API:

     Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the MVC.

              WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.

              In the scenarios listed below you should go for WCF:

              1. If you need to send data on protocols like TCP, MSMQ or MIME
              2. If the consuming client just knows how to consume SOAP messages

              We can expose REST endpoints on WCF services as well.

              WEB API is a framework for developing RESTful/HTTP services.

              There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.Although WCF provides some support for writing REST-style services, the support for REST in ASP.NET Web API is more complete and all future REST feature improvements will be made in ASP.NET Web API.

              Here are few nice articles and reference:
              WCF or ASP.NET Web APIs? My two cents on the subject
              Scott Hanselman’s - Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block

              What is the correct way to handle exceptions and UnobservedTaskException in the TPL?

              Information from: A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was

              If you create a Task, and you don't ever call task.Wait() or try to retrieve the result of a Task<T>, when the task is collected by the garbage collector, it will tear down your application during finalization. For details, see MSDN's page on Exception Handling in the TPL.

              The best option here is to "handle" the exception. This can be done via a continuation - you can attach a continuation to the task, and log/swallow/etc the exception that occurs. This provides a clean way to log task exceptions, and can be written as a simple extension method, ie:

              public static void LogExceptions(this Task task)
                  task.ContinueWith( t =>
                       var aggException = t.Exception.Flatten();
                       foreach(var exception in aggException.InnerExceptions)
              With the above, you can prevent any task from tearing down the app, and logging it, via:
              Task.Factory.StartNew( () => 
                     // Do your work...
              Alternatively, you can subscribe to the TaskScheduler.UnobservedTaskException and handle it there. 

              Continuation of the task could determine the status of the parent task whether it get faulted or completed to success. A continuation can find out if an exception was thrown by the antecedent Task by the antecedent task's exception property. The following code snippet will print the results of a NullReferenceException to the console.

              Task task1 = Task.Factory.StartNew (() => { throw null; });
              Task task2 = task1.ContinueWith (ant => Console.Write(ant.Exception());
              If task1 throws an exception and this exception is not captured/queried by the continuation then it is considered unhandled and the application get halted. With continuations it is enough to establish the result of the task via the Status property.
              asyncTask.ContinueWith(task =>
                  // Check task status.
                  switch (task.Status)
                      // Handle any exceptions to prevent UnobservedTaskException.             
                      case TaskStatus.RanToCompletion:
                          if (asyncTask.Result)
                              // Do stuff...
                      case TaskStatus.Faulted:
                          if (task.Exception != null)
                              mainForm.progressRightLabelText = task.Exception.InnerException.Message;
                              mainForm.progressRightLabelText = "Operation failed!";
              If you don't use continuations you either have to wait on the task in a try/catch block or query a task's Result in a try/catch block. See below code snippet:
              int x = 0;
              Task task = Task.Factory.StartNew (() => 7 / x);
                  // OR.
                  int result = task.Result;
              catch (AggregateException aggEx)

              How to close a MessageBox after several seconds?

              Related to: Close a MessageBox after several seconds.
              I need to create a message box or Popup which must be visible for specified time and close automatically after then.

              There is not inbuilt feature in .net framework to do this. You need to create your custom logic that message box close after a specific time. To do this create a custom message box class which have a timer which close the raised pop message when elapsed time equal to specified time to make it visible to the user.
              Here is the custom class:

              public class AutoClosingMessageBox {
                  System.Threading.Timer _timeoutTimer;
                  string _caption;
                  AutoClosingMessageBox(string text, string caption, int timeout) {
                      _caption = caption;
                      _timeoutTimer = new System.Threading.Timer(OnTimerElapsed,
                          null, timeout, System.Threading.Timeout.Infinite);
                      MessageBox.Show(text, caption);
                  public static void Show(string text, string caption, int timeout) {
                      new AutoClosingMessageBox(text, caption, timeout);
                  void OnTimerElapsed(object state) {
                      IntPtr mbWnd = FindWindow(null, _caption);
                      if(mbWnd != IntPtr.Zero)
                          SendMessage(mbWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
                  const int WM_CLOSE = 0x0010;
                  [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
                  static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
                  [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
                  static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);

              It can be called as below:

              AutoClosingMessageBox.Show("Text", "Caption", 1000);