Monday, December 30, 2013

FIX: JQuery date format validation for non US dates in Chrome

Include following script in your javascript file and reference it in your page(s) to get rid of the most common error of JQuery date format validation in Chrome which doesn't allow non US dates.

    $(document).ready(function () {
jQuery.validator.methods["date"] = function (value, element) { return true; }


Wednesday, August 7, 2013

My Bookmarks - Part I: CSS

Following are references to some of the sites/ posts which I came across while developing websites.

**Credit to the respective post/ blog owners **

Cross-Browser CSS Gradient
This concise CSS class can make your DIV or any other HTML control appearing with gradient background without really needing any image.

background: #999; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#cccccc', endColorstr='#000000'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#ccc), to(#000)); /* for webkit browsers */
background: -moz-linear-gradient(top,  #ccc,  #000); /* for firefox 3.6+ */
Complete reference to post:
A cool website to get color code to use them while setting gradients:

Wednesday, July 31, 2013

Replacement of InnerText property, while updating display text of elements such as (span, etc) in HTML.

This article aims to provide a javascript function to update display text of controls such as (SPAN, etc) in HTML using javascript. 

Generally, we tend to update innerText  property of such elements in this scenario, but when it works perfectly as expected in IE and Chrome, it fails in Firefox. Because,it's not supported.

Instead, include below javascript function in your JS library, and call it. This is more elegant and cross-browser solution of this problem.

function setTextContent(element, text) {
    while (element.firstChild!==null)
        element.removeChild(element.firstChild); // remove all existing content

Sample call:

setTextContent($('span.displayText), result);

Friday, July 5, 2013

When should we not use MVC bundling?

As we all know MVC bundling and minification is a very powerful feature, but recently I faced a strange problem in one of the project as detailed below.

I was using Trent Richardson's Timepicker control to avail time picker functionality in my MVC 4 application. I had relevant JQuery file bundled using MVC bundling feature. I found this working quite well in development environment (Visual Studio 2012).
But when I deployed the website on IIS, I started facing a strange issue, and there was a javascript error "function expected" in that particular bundle. I could see the bundle got loaded because developer tool was showing javascript code when that bundle was selected in "scripts" tab.

Finally, when I referenced the JQuery file directly instead of bundle, it started working fine on IIS. Though the problem got solved, I was than now curious to know what was wrong with that particular file if bundled, and if MVC bundling was actually an issue, then why it was working well in development environment, but not in IIS?

Posting this on various forums gave me following two detailed answers which helped me in identifying in which situations we should avoid using bundling -

Answer 1

Minification is a complex process by making scripts/styles smaller using techniques such variable name shortening, white space elimination, comments removal, etc... It uses ASP.NET Web Optimization that depends on WebGrease for minification. Of course, there can have issues but I personnaly never noticed that.
Here are some situations, where you should not use bundling
  • There is only one file in your bundle. Why bundling ?
  • You are using only famous frameworks such as JQuery or jQuery UI. Do not redistribute scripts that are already served by someone else. Google/Microsoft/Amazon/... already provide CDN for the most popular, open-source JavaScript libraries.
    <script src="//"></script>
  • Your bundle takes only a few Bytes. Web performance Optimization suggests to limit the number of web requests. Everything has a cost. Not very optimal, but sometimes it's better to put inline scripts in your page.
  • In some architectures. Bundles requests contains a unique identifier used for caching. If any file in the bundle changes, the ASP.NET optimization framework will generate a new token, guaranteeing that browser requests for the bundle will get the latest bundle. When working with some architectures, JS updates can be frequent and will invalidate all your bundles.
  • On Dev Environment. It's is really really painful to debug a bundle.
Answer 2

What bundling suppose to do is to put together the script/stylesheet files in a single bundle into a single request and send it to the client so that the browser has to make less calls to get those required script files. In a development environment, when you do debugging in visual studio. It doesn't do the above process unless you specify it to do so. But in a production environment, when the debug is set to false in the web.config file. it will start to do the above process. There can be some other reasons as well. such as the script might have two versions. one for debugging and one for production. I came across such a situation with knockout. in my development environment I had referenced the debug version of the script. But when I put it into the production environment, everything came to a hault. There was a release version for the 
knockout script file and I had to reference that to make everything work again
Hope this will help you

Fetch maximum of an integer/ numeric/ decimal field of your table using Entity Framework

Whenever there is a need to fetch the maximum of integer/ numeric/ decimal field, you can execute following simple statement to get the same, if your project is using Entity Framework.

Following example is for finding maximum value in an Integer field. Similarly, you can use it for decimal/ double/ etc fields.

Also, consider "int?" (nullable) in below statement, because if there is no record in the particular table, then the below statement will return null. If you use "int" instead of "int?", then it will throw an exception if the table has no record.

int? intIdt = db.Users.Max(u => (int?)u.UserId);

Thursday, June 27, 2013

Linq to Entities (or Entity Framework) - Find index of row matching condition in entity set (DbSet/ ObjectSet)

This article aims to explain how to find the index of a row matching a particular condition in DbSet/ ObjectSet using Linq to Entities.

While working with Entity Framework (at least till Entity Framework 5), and Linq-to-entities, I realized it doesn't have support to find index of row within the DbSet for obvious reasons. And so I thought to write a method manually. There are many approaches for the same, and different developers might have implemented different approaches. I found the one I implemented below as more performance optimized.

Say, for example, you have an entity set "Cities". There exists, thousands of rows in this table. You need to sort the cities by their name, and want to find index of a particular city within that ordered collection.

One instance of such need is to have paging implemented in your site, and you want your user to jump to the page containing record of a particular city by keeping paging intact.

The approach is to - First check if that particular city exists in the "Cities" collection or not.
If it exists, call the below FindIndex method:

Also, take a note of loopCapacity variable in below code. In below example, it means, the final "for loop" to find and calculate the index will be started only after a bunch of 100 records are found. Here, these 100 records contain that particular record (i.e. city) which we are looking for.  

public int FindIndex(String CityName)
            int index = 0;
            int totalRecords = db.Cities.Count();
            int halfCount = Convert.ToInt32(Math.Ceiling(Convert.ToDecimal(totalRecords / 2))) + 1;
            int loopCapacity = 100;
            int recordsToSkip = 0;
            if (totalRecords > 0)
                bool nextIteration = true;
                while (nextIteration)
                    for (int counter = 0; counter < 2; counter++)
                        recordsToSkip = recordsToSkip + (counter * halfCount);
                        if (db.Cities.OrderBy(c => c.CityName).Skip(recordsToSkip).Take(halfCount).Where(c => c.CityName == CityName).Count() > 0)
                            if (halfCount > loopCapacity)
                                totalRecords = totalRecords - (halfCount * 1);
                                halfCount = Convert.ToInt32(Math.Ceiling(Convert.ToDecimal(totalRecords / 2))) + 1;
                                nextIteration = true;
                                foreach (Cities city in db.Cities.OrderBy(c => c.CityName).Skip(recordsToSkip).Take(halfCount))
                                    if (city.CityName == CityName)
                                        index = index + 1;
                                        index = recordsToSkip + index;
                                        index = index + 1;
                                nextIteration = false;
                            nextIteration = true;
            return index;

Hope this helps!

Do let me know if anything is unclear, or if you need explanation for any part of code


Tuesday, June 25, 2013

C# - Generate random number

Sometimes we need to generate a random number in our application for various purpose (such as, to use it as a part of unique key, etc).

There is a quick way in C#, that can generate a random number. Here, you can also specify the range within which the random number should be generated.

int generatedRandomNumber = new Random(System.DateTime.Now.Millisecond).Next(int.MinValue, int.MaxValue);

This will generate a random number within the range of -2147483648 and 2,147,483,647. But you can narrow down your range to only positive values or some explicit range by changing the parameters in Next function above.

Hope it does help!

Javascript: Function to check if the string is numeric (i.e. valid number)

Following is the javascript function which accurately validates if the supplied string a valid number or not.

function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);

Trim, Ltrim, Rtrim, FullTrim - trimming string functions in Javascript

JQuery 1.9+ have inbuilt functions for string trimming, but they aren't supported in many browsers, such as, IE 8, IE 9, etc., and so I refrain myself from using those function, and hence there is a need to have our custom function to perform this job!

Following are javascript functions for trimming strings: 

function StringTrim(inputText){return inputText.replace(/^\s+|\s+$/g, '');};

function StringLtrim(inputText){return inputText.replace(/^\s+/,'');};

function StringRtrim(inputText){return inputText.replace(/\s+$/,'');};

function StringFulltrim(inputText){return inputText.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');};

Add them in javascript library of your application, and you can use them to trim strings in various ways, such as, left trim, right trim, trim, and full trim.

Hope this helps!

Thursday, May 30, 2013

SQL Query to return a table containing all dates falling within a date range along with their week day names

Following is the T-SQL code to return all dates falling within a given date range. This uses CTE for populating all dates, and store them in a temporary table.

DECLARE @StartDate datetime
DECLARE @EndDate datetime
SET @StartDate = '01-Apr-2013'
SET @EndDate = '30-Apr-2013'

;WITH DatesList
SELECT @StartDate [fldDate]
SELECT fldDate + 1 FROM DatesList WHERE fldDate < @EndDate

SELECT fldDate, DATENAME(dw, fldDate) as fldDayFullName INTO #DatesList FROM DatesList option (maxrecursion 0)

SELECT * FROM #DatesList

Friday, May 10, 2013

How to convert an array of one type to another type in using Linq in .NET

Following is the sample code that converts a string array into GUID array with faster performance:

String strGUIDs[];
//Consider the above array is containing all GUIDs in string format.
Guid[] guids = Array.ConvertAll(strGUIDs, x => Guid.Parse(x));

You can convert an array from one type to another using the above approach.

Thursday, April 25, 2013

Vertical Scrollbar in JQuery AutoComplete UI

In most cases, we need to display a vertical scrollbar in JQuery AutoComplete UI.
JQuery and UI libraries come along with their own styling and theming, and it has its own CSS "jquery-ui-n.n.nn.css".
And we certainly need to play with the styles inside that in order to change any behaviour or styling of same.
Instead of doing any changes inside JQuery libraries, add following styling attributes in your page/ css file, and you will find vertical scrollbar.
/* setting up height for autocomplete UI */
.ui-autocomplete {
    max-height: 150px;
    overflow-y: auto;
    /* prevent horizontal scrollbar */
    overflow-x: hidden;
    /* add padding to account for vertical scrollbar */
    padding-left: 5px;
    padding-right: 5px;
/* IE 6 doesn't support max-height
 * we use height instead, but this forces the menu to always be this tall
* html .ui-autocomplete {
    height: 150px;

Remember, changing JQuery libraries are never a good idea, because you will also need to take care of the same each time when you upgrade your libraries:

Monday, April 8, 2013

FIX: "The Page Cannot be found" on Classic ASP + IIS 6

In order to successfully deploy your Classic ASP site in IIS 6, you manually need to enable ASP engine for IIS. Otherwise, it will keep giving you error - "The page cannot be found".

Follow the steps as per below:

1) Open IIS Manager.

2) Click "Web Service Extensions" in root on left-hand side  3) See "Active Server Pages", by default it is set to "Prohibited"4) Right-click and change it to "Allow" and then your ASP site will start working fine.