jQuery and ASP.NET

July 31, 2010

List all Files in .NET 4.0 Based on the Creation Date

0 comments


I had recently posted on 7 New methods to Enumerate Directory and Files in .NET 4.0

A user commented asking if it was possible to returns a list of files from a directory for a given date range (i.e. start date - end date). Here’s how to do so:

C#

using System;
using System.Linq;
using System.IO;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
DirectoryInfo DirInfo = new DirectoryInfo(@"D:\Articles\Pics\jQuery");

DateTime dt1 = new DateTime(2009, 07, 15);
DateTime dt2 = new DateTime(2010, 04, 15);

// LINQ query for files between 15-July 2009 and 15-April 2010.
var files = from file in DirInfo.EnumerateFiles()
where file.CreationTimeUtc > dt1 &
file.CreationTimeUtc < dt2                       
select file;

// Show results.
foreach (var file in files)
{
Console.WriteLine("{0} created on {1}", file.Name, file.CreationTimeUtc);
}
Console.ReadLine();
}
}
}


VB.NET 10.0 (converted)

Namespace ConsoleApplication1
Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim DirInfo As New DirectoryInfo("D:\Articles\Pics\jQuery")

Dim dt1 As New Date(2009, 07, 15)
Dim dt2 As New Date(2010, 04, 15)

' LINQ query for files between 15-July 2009 and 15-April 2010.
Dim files = From file In DirInfo.EnumerateFiles()
Where file.CreationTimeUtc > dt1 And file.CreationTimeUtc < dt2
Select file

' Show results.
For Each file In files
Console.WriteLine("{0} created on {1}", file.Name, file.CreationTimeUtc)
Next file
Console.ReadLine()
End Sub
End Class
End Namespace


OUTPUT

image

July 30, 2010

Filter data in a WPF ListBox

2 comments


In this post, I will demonstrate how to filter data from the list box in WPF. To do this, I am using LINQ to Collections.

Assuming you have a WPF project, add a class file ‘Employee’

class Employee
{
  public int EmpNo { get; set; }
  public string EmpName { get; set; }
}

In the MainWindow.Xaml, add the following code:

<Grid>
<ListBox Height="298" HorizontalAlignment="Left" Margin="80,55,0,0"
Name="lstEmpData" VerticalAlignment="Top" Width="252">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding EmpName}"></TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<TextBlock Height="23" HorizontalAlignment="Left" Margin="60,18,0,0"
Name="textBlock1" Text="Search Name"
VerticalAlignment="Top" Width="134" />
<TextBox Height="27" HorizontalAlignment="Left" Margin="208,13,0,0"
Name="txtNameToSearch" TextChanged="txtNameToSearch_TextChanged"
VerticalAlignment="Top" Width="202" />
</Grid>


The xaml code shown above defines a ListBox which has ItemTemplate set to TextBlock. This TextBlock is bound with EmpName. The TextBox(txtNameToSearch) is used to define filter values.

In the Window_Loaded event, add the following code

ObservableCollection<Employee> lstEmployee =
new ObservableCollection<Employee>();

private void Window_Loaded(object sender, RoutedEventArgs e)
{
lstEmployee.Add(new Employee() { EmpNo = 1001, EmpName = "Mahesh" });
lstEmployee.Add(new Employee() { EmpNo = 1002, EmpName = "Amit" });
lstEmployee.Add(new Employee() { EmpNo = 1003, EmpName = "Vaibhav" });
lstEmployee.Add(new Employee() { EmpNo = 1004, EmpName = "Ashwin" });
lstEmployee.Add(new Employee() { EmpNo = 1005, EmpName = "Prashant" });
lstEmployee.Add(new Employee() { EmpNo = 1006, EmpName = "Vinit" });
lstEmployee.Add(new Employee() { EmpNo = 1007, EmpName = "Abhijit" });
lstEmployee.Add(new Employee() { EmpNo = 1008, EmpName = "Pankaj" });
lstEmployee.Add(new Employee() { EmpNo = 1009, EmpName = "Kaustubh" });
lstEmployee.Add(new Employee() { EmpNo = 1010, EmpName = "Mohan" });

lstEmpData.ItemsSource = lstEmployee;
}

The code shown above defines an Employee collection bound to the ListBox.

Now in the TextChanged event of the TextBox, add the following LINQ code which filters data from the collection and binds the result to the Listbox:

private void txtNameToSearch_TextChanged(object sender,
TextChangedEventArgs e)
{
  string txtOrig = txtNameToSearch.Text;
  string upper = txtOrig.ToUpper();
  string lower = txtOrig.ToLower();

  var empFiltered = from Emp in lstEmployee
  let ename = Emp.EmpName
  where
   ename.StartsWith(lower)
   || ename.StartsWith(upper)
   || ename.Contains(txtOrig)
   select Emp;

  lstEmpData.ItemsSource = empFiltered;
}
 
OUTPUT
image

July 29, 2010

Calculate the Size of a Folder/Directory using .NET 4.0

3 comments


.NET 4.0 introduces 7 New methods to Enumerate Directory and Files in .NET 4.0. All these methods return Enumerable Collections (IEnumerable<T>), which perform better than arrays. We will be using the DirectoryInfo.EnumerateDirectories and DirectoryInfo.EnumerateFiles in this sample which returns an enumerable collection of Directory and File information respectively.

Here’s how to calculate the size of a folder or directory using .NET 4.0 and LINQ. The code also calculates the size of all sub-directories.

C#

using System;
using System.Linq;
using System.IO;

namespace ConsoleApplication3
{
  class Program
  {
    static void Main(string[] args)
    {
      DirectoryInfo dInfo = new DirectoryInfo(@"C:/Articles");
      // set bool parameter to false if you
      // do not want to include subdirectories.
      long sizeOfDir = DirectorySize(dInfo, true);

      Console.WriteLine("Directory size in Bytes : " +
      "{0:N0} Bytes", sizeOfDir);
      Console.WriteLine("Directory size in KB : " +
      "{0:N2} KB", ((double)sizeOfDir) / 1024);
      Console.WriteLine("Directory size in MB : " + 
      "{0:N2} MB", ((double)sizeOfDir) / (1024 * 1024));

      Console.ReadLine();
    }

    static long DirectorySize(DirectoryInfo dInfo, bool includeSubDir)
    {
       // Enumerate all the files
       long totalSize = dInfo.EnumerateFiles()
                    .Sum(file => file.Length);

       // If Subdirectories are to be included
       if (includeSubDir)
       {
          // Enumerate all sub-directories
          totalSize += dInfo.EnumerateDirectories()
                   .Sum(dir => DirectorySize(dir, true));
       }
       return totalSize;
    }
  }
}

VB.NET 10.0 (converted using online tool)

Imports System
Imports System.Linq
Imports System.IO

Module Module1

Sub Main()
   Dim dInfo As New DirectoryInfo("C:/Articles")
   ' set bool parameter to false if you
   ' do not want to include subdirectories.
   Dim sizeOfDir As Long = DirectorySize(dInfo, True)

   Console.WriteLine("Directory size in Bytes : " & _
    "{0:N0} Bytes", sizeOfDir)
   Console.WriteLine("Directory size in KB : " & _
    "{0:N2} KB", (CDbl(sizeOfDir)) / 1024)
   Console.WriteLine("Directory size in MB : " & _
    "{0:N2} MB", (CDbl(sizeOfDir)) / (1024 * 1024))

   Console.ReadLine()
End Sub

Private Function DirectorySize(ByVal dInfo As DirectoryInfo, _
   ByVal includeSubDir As Boolean) As Long
   ' Enumerate all the files
   Dim totalSize As Long = dInfo.EnumerateFiles() _
     .Sum(Function(file) file.Length)

   ' If Subdirectories are to be included
   If includeSubDir Then
     ' Enumerate all sub-directories
     totalSize += dInfo.EnumerateDirectories() _
      .Sum(Function(dir) DirectorySize(dir, True))
   End If
   Return totalSize
End Function

End Module


OUTPUT

I got the following output after running this code.

image

To confirm that the code worked as expected, I opened Windows Explorer > C Drive > Right clicked the folder > Properties. Here is the screenshot that matches the output we got from our code

image

July 28, 2010

Compare two List<string> using LINQ

0 comments


In this post, we will see how to compare two List<string> and list the elements found in one List<string> but not in the other. We will be using the Enumerable.Except method

C#

static void Main(string[] args)
{
List<string> lstOne =
new List<string>() { "Jim", "Jack", "Kate", "Nope" };

List<string> lstTwo =
new List<string>() { "Jack", "Nope", "Jim" };

IEnumerable<string> lstNew = null;

// Compare two List<string> and display items of lstOne not in lstTwo
lstNew = lstOne.Except(lstTwo, StringComparer.OrdinalIgnoreCase);

PrintList(lstNew);
Console.ReadLine();
}

static void PrintList(IEnumerable<string> str)
{
foreach (var s in str)

Console.WriteLine(s);
Console.WriteLine("-------------");
}

OUTPUT

image

Read some more tips in my article over here Some Common Operations using List<string>

July 27, 2010

Bind Enum to a WPF ListBox using ObjectDataProvider

0 comments


In programming languages, Enumeration has a specific role for storing values. The Enum.GetValues() method retrieves an array of the values of the constants in an Enum. Let us see how to use this method and bind an Enumeration to a WPF ListBox using the ObjectDataProvider.

Create a WPF project with the name of WPF_EnumBinding. In the WPF Project, open the MainPage.Xaml.cs and write an enumeration as shown below:

public enum Department
{
IT,
System,
HRD,
Accts,
Transport
}

Since ‘Enum’ is defined in mscorlib assembly, it is referred in the Xaml code shown below. The ObjectDataProvider is used to bind the Enumeration with the Xaml. The namespace under which enumeration i.e. WPF_EnumBinding is declared, is also referred in the Xaml. The Xaml code is as below:

<Window x:Class="WPF_EnumBinding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:System;assembly=mscorlib"
xmlns:data="clr-namespace:WPF_EnumBinding"
Title="MainWindow" Height="350" Width="525">
<
Window.Resources>
<
ObjectDataProvider MethodName="GetValues"
ObjectType="{x:Type src:Enum}" x:Key="dname">
<
ObjectDataProvider.MethodParameters>
<
x:Type TypeName="data:Department"></x:Type>
</
ObjectDataProvider.MethodParameters>
</
ObjectDataProvider>
</
Window.Resources>
<
Grid>
<
ListBox Height="294" HorizontalAlignment="Left"
Margin="32,17,0,0" Name="lstEnum" VerticalAlignment="Top"
Width="222" DataContext="{Binding Source={StaticResource dname}}"
ItemsSource="{Binding}">
</
ListBox>
</
Grid>
</
Window>

OUTPUT

image

July 26, 2010

List Common Elements between two List<string>

0 comments


Here’s a simple post that shows how to list common elements between two List<Strings>. Use the Enumerable.Intersect method

C#

class Program
{
static void Main(string[] args)
{
List<string> lstOne =
new List<string>() { "Jim", "Jack", "Kate", "Nope" };
List<string> lstTwo =
new List<string>() { "Jack", "Nope", "Jim" };
IEnumerable<string> lstNew = null;

// Compare two List<string> and display common elements
lstNew = lstOne.Intersect(lstTwo, StringComparer.OrdinalIgnoreCase);
PrintList(lstNew);

Console.ReadLine();
}

static void PrintList(IEnumerable<string> str)
{
foreach (var s in str)
Console.WriteLine(s);
Console.WriteLine("-------------");
}
}

VB.NET


    Sub Main()
Dim lstOne As New List(Of String)() _
From {"Jim", "Jack", "Kate", "Nope"}
Dim lstTwo As New List(Of String)() _
From {"Jack", "Nope", "Jim"}
Dim lstNew As IEnumerable(Of String) = Nothing

' Compare two List<string> and display common elements
lstNew = lstOne.Intersect(lstTwo, StringComparer.OrdinalIgnoreCase)
PrintList(lstNew)

Console.ReadLine()
End Sub

Private Sub
PrintList(ByVal str As IEnumerable(Of String))
For Each s In str
Console.WriteLine(s)
Next s
Console.WriteLine("-------------")
End Sub

OUTPUT


image


Read some more tips in my article over here Some Common Operations using List<string>

July 25, 2010

Web Camp Training Kit - Recent Microsoft Web Camps Presentations, Demos and Labs

0 comments


Microsoft recently released the July 2010 release of the Web Camps Training Kit.

The Web Camp Training kit includes all the content presented around the world at the recent Web Camps events; presentations, demos, labs and more. Inside the new kit you’ll find content that covers the following technologies:

  • ASP.NET MVC 2
  • ASP.NET 4 Web Forms
  • jQuery
  • Entity Framework
  • Visual Studio 2010

Download the Web Camp Training Kit

July 24, 2010

Understanding YSlow – A Firebug Extension to Analyze and Improve Webpage Performance

3 comments


Yahoo’s YSlow is a ‘must have’ Firefox add-on and is an extension (for performance) to the Firebug tool. YSlow analyzes web pages and suggests ways to improve the performance of web pages based on a set of rules for high performance web pages laid out by Yahoo. There are 34 rules laid out by Yahoo and YSlow is capable of testing 22 of them.

The 22 rules testable by YSlow and as listed in the YSlow user guide, are:

  1. Minimize HTTP Requests
  2. Use a Content Delivery Network
  3. Add an Expires or a Cache-Control Header
  4. Gzip Components
  5. Put StyleSheets at the Top
  6. Put Scripts at the Bottom
  7. Avoid CSS Expressions
  8. Make JavaScript and CSS External
  9. Reduce DNS Lookups
  10. Minify JavaScript and CSS
  11. Avoid Redirects
  12. Remove Duplicate Scripts
  13. Configure ETags
  14. Make AJAX Cacheable
  15. Use GET for AJAX Requests
  16. Reduce the Number of DOM Elements
  17. No 404s
  18. Reduce Cookie Size
  19. Use Cookie-Free Domains for Components
  20. Avoid Filters
  21. Do Not Scale Images in HTML
  22. Make favicon.ico Small and Cacheable

Assuming you have downloaded YSlow and installed it in Firefox, let us quickly run the YSlow tool on a website and then dissect the results to understand the tool better. Once installed, the YSlow tool can be invoked from Firefox. Just open your web page in Firefox and click the YSlow tool (lower right corner of the Firefox status bar). Here are the results of running YSlow on a sample webpage from my site.

image

As you can observe, the results consists of 4 Tabs – Grade, Components, Statistics and Tools. The screenshot also shows the rulesets applied as well as the the Grade received by the website. Let us understand these terms one by one.

Rulesets

Let us first understand the rulesets that YSlow uses to grade pages (we will understand grading shortly). There are 3 predefined rulesets that you can choose to apply on a webpage:

YSlow(V2) - This ruleset contains the 22 rules listed in the beginning of this article.

Classic (V1) - This ruleset contains rules from 1 to 13.

Small Site or Blog - This ruleset contains 14 rules that are applicable to
small websites or blogs. These are Rule 1, 4, 5, 6, 7, 9, 10, 11, 12, 16, 17, 20, 21 and 22.

In addition to these rulesets, you can also create your own set of rules. For more information on creating custom set of rules, read Customizing Rulesets.

Grade

‘Grade’ is one of the four tabs as shown below and depicts a report card on our page’s performance.

image

YSlow examines all the components of a webpage and then grades the web page based on one of three predefined ruleset or even a custom-defined ruleset, we discussed about in the Rulesets section. How the grading works, is when YSlow analyzes a webpage, it deducts points for every breach of a rule and then applies a grade to each rule. Here’s a sample screenshot of the grades received by the webpage for each rule and the suggestion for improvement, shown on the right.

image

Then a final grade is computed (in our case ‘B’) by summing up the values of the points gained for each rule, weighted by the rule's importance.

Components

Components is the second of the four tabs as shown below:

image

The Component tab shows the various components on the page (javascript, css etc) and information related to each component (click the ‘+’ icon or ‘Expand All’ link). This will give you an idea which component takes more time to load and you can consider to gzip it and improve performance.

Statistics

Statistics is the third tab and provides a graphical representation of the number of HTTP requests made to the server and the total weight of the page in kilobytes for both Empty Cache and Primed Cache scenarios.

image

The Empty Cache scenario is when the browser makes the first request to the page and the Primed Cache scenario is when the browser has a cached version of the page. In a Primed Cache scenario, the components are already in the cache, so this will reduce the number of HTTP requests and thereby the weight of the page.

Tools

Tools is the last tab and contains a list of various tools that YSlow suggests to run on the webpage resources (images, JavaScript, CSS) to improve the performance of the page.

image

With this, I hope this quick guide explained what YSlow is all about and how you can use it to analyze and improve the performance of your web pages. I am going to apply this tool on my web pages and follow the recommendations made by this tool to improve performance. I hope you do the same for your web pages too! You can read more about YSlow in the YSlow User Guide.

Link to Download YSlow

July 23, 2010

Expand a TextBox on Focus using jQuery

0 comments


Here’s how to animate and expand the height and width of a TextBox when it receives focus. After a delay, the TextBox returns to its normal size

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Expand a TextBox on Focus in jQuery</title>
<
style type="text/css">
.txt
{
width:100px;
height:15px;
}
</style>
<
script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js">
</
script>

<
script type="text/javascript">
$(function () {
$(".txt").focus(function () {
$(this).animate({
width: '200px',
height: '40px'
},
"slow"
)
.delay(2000)
.animate({
width: '100px',
height: '15px'
},
"slow"
);
});
});
</script>
</
head>
<
body>
<
div>
<
input class="txt" type="text"
value="Some Text Some Text Some Text" /><br />
</
div>
</
body>
</
html>

The code is self explanatory. We first animate the height and width of the TextBox and increase its size. We then set a delay() and then animate the height and width back to what it was earlier.

See a Live Demo

July 22, 2010

Free Antivirus Software for your Windows OS

0 comments


I am a Windows power user and have the habit of regularly backing up my data, use a firewall, understand the pitfalls of bad internet behavior, regularly keep my OS updated with patches and do a lot of other stuff that other power users do to keep the system safe. However in addition to all of these points, I also use an Antivirus for my machine, just to add an extra layer of security.

Here is a short review and list of FREE Antivirus Programs if you are running Windows OS. Please note that this list is not comprehensive and contains only the Antivirus programs that I have used and tested on my machine.


Microsoft Security Essentials

IMHO, Microsoft Security Essentials is one of the best Antivirus solutions (in the freebee category) to guard your PC against viruses, spyware, and other malicious software. The automatic upgrades are smooth, the software is lightweight, runs quietly without constant interruptions and is very easy to use. You should have genuine Windows to install Microsoft Security Essentials. There’s also a new Beta for Next Version of Microsoft Security Essentials Now Available

Terms of Use: As mentioned in the Eula, “You may install and use any number of copies of the software on your devices in your household for use by people who reside there or for use in your home-based small business

OS Supported: Windows XP (Service Pack 2 or Service Pack 3)/Windows Vista (Gold, Service Pack 1, or Service Pack 2)/ Windows 7 (32/64 bit)


avast!

avast! provides good protection against viruses, spyware and other forms of malicious software. One of the features that I specifically liked was that avast runs in Safe Mode too, has a Boot time scanner, is easy to use and does not take a lot of my system resources. It’s free edition does not contain a spam filter nor does it provide any technical support, which I feel is a serious limitation.

Terms of Use: avast! Free Antivirus is free only for personal and non-commercial use

Features: http://www.avast.com/free-antivirus-download#tab2

OS Supported: Microsoft Windows 2000, Microsoft Windows XP/Vista/7 (32/64 bit)


Avira AntiVir

Avira AntiVir Personal is a free antivirus solution against malicious programs such as viruses, Trojans, backdoor programs, hoaxes, worms, dialers etc. It’s free edition supports Netbook with low resolution, comes with a Generic Repair option for your PC and also includes customer support. Although I haven’t personally used their support, friends have given me a feedback that their support is very prompt. I found that at times it gives out false alerts ‘too frequently’ but that can be controlled by

Terms of Use: Free of charge virus protection to home-users, for personal use only, and is not for business or commercial use.

OS Supported: Unix/ Windows 2000, SP4 and update rollup 1, Windows XP, SP2/ Vista (SP 1 recommended)/ Windows 7 (32/64 Bit)


Other Free Antivirus Softwares

Apart from the ones listed above, a quick search reveals some free antivirus solutions like AVG, ClamWin, Comodo etc. There is also a good thread on superuser.com that discusses free antivirus solutions.

If you are looking out for a paid Antivirus solutions then I strongly recommend to try ESET NOD32 Antivirus 4

July 21, 2010

Improve Laptop Battery Performance in Windows 7

0 comments


I use Windows 7 on an ASUS Netbook that runs on a battery for 6-9 hours. One thing that always comes to my mind is why does my battery life fluctuate +-3 hours and how can I improve my netbook’s battery life and performance.

Well Windows 7 has just the right utility to provide that information. It’s called PowerCfg. Here’s how to use this utility.

Go to Start > All Programs > Accessories > Command Prompt. Right click > Run as administrator.

image

Type the following command powercfg –energy on the command prompt and hit enter. You will get a screen similar to the following screenshot:

Tip: It’s best to run this command when your system is in an idle state.

image

After 60 seconds, Windows creates an HTML file called ‘energy-report.html’ in C:\windows\system32. This report gives you an overview of your system’s energy efficiency over a 60 second period. Here are some screenshots of the report when I ran it on my netbook.

image

The report also give warnings of processes with significant processor utilization.

image

Read more about this utility in this whitepaper Using PowerCfg to Evaluate System Energy Efficiency

July 20, 2010

Create a List<string> from a Delimited string

0 comments


Here’s how to create a List<string> from a Delimited string using the Enumerable.ToList method

C#

static void Main(string[] args)
{
IEnumerable<string> lstNew = null;
string s = "jQuery MooTools Prototype";
char separator = ' ';
lstNew = s.Split(separator).ToList();
PrintList(lstNew);
Console.ReadLine();
}

static void PrintList(IEnumerable<string> str)
{
foreach (var s in str)
Console.WriteLine(s);
Console.WriteLine("-------------");
}

VB.NET

Sub Main()
Dim lstNew As IEnumerable(Of String) = Nothing
Dim
s As String = "jQuery MooTools Prototype"
Dim separator As Char = " "c
lstNew = s.Split(separator).ToList()
PrintList(lstNew)
Console.ReadLine()
End Sub

Shared Sub
PrintList(ByVal str As IEnumerable(Of String))
For Each s In str
Console.WriteLine(s)
Next s
Console.WriteLine("-------------")
End Sub

image

Read more tips in my article over here Some Common Operations using List<string>

July 19, 2010

Test Regular Expressions in Your Browser

1 comments


After you have created a regular expression, you usually write a script or use a tool to test if the Regex works as expected. Alternatively, if you are using Firefox or Google Chrome, then here are some plug-ins that make it very simple to test regular expression directly from your browser. I had recently written a post on Validate US Zip Code using JavaScript where I had used the Regex ^[0-9]{5}(?:-[0-9]{4})?$ We will use the same regex for this post and test it using the add-ons for Firefox and Chrome.

Regular Expressions Tester 3.0

This is a Firefox add-on for regular expressions with color highlighting (including submatches) and helpers for creating expressions. Observe in the screenshot shown below how the color changes to yellow as soon as the Regex matches a valid US zip code.

image

Regular Expression Checker

This is a simple add-on for Google Chrome and is inspired by Regular Expressions Tester 3.0. You can save a regular expression and the tool also shows the number of matches, sub patterns etc. The only thing that I was not comfortable with was that this tool wanted access to my browser history to work properly. Now I am not sure why was that required. Nevertheless, here’s a screenshot of the results after testing my Regex.

image

I could not find any add-ons for Internet Explorer that can test Regular Expressions. If you know of any such add-on, let me know and I will add it to this list.

July 18, 2010

Validate US Zip Code using JavaScript

2 comments


Here’s how to validate US Zip code using JavaScript. We will be using a Regular Expression to do so.

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Validate US Zip Code in JavaScript</title>
<
script type="text/javascript">
function
IsValidZipCode(zip) {
var isValid = /^[0-9]{5}(?:-[0-9]{4})?$/.test(zip);
if (isValid)
alert('Valid ZipCode');
else {
alert('Invalid ZipCode');
}
}
</script>
</
head>

<
body>
<
form>
<
input id="txtZip" name="zip" type="text" /><br />
<
input id="Button1" type="submit" value="Validate"
onclick="IsValidZipCode(this.form.zip.value)" />
</form>
</
body>
</
html>

The code above validates a US zip code based on both the five digit (12345) as well as nine-digit (12345-1234 ) schemes.

See a Live Demo

July 17, 2010

Display Date in MM/DD/YYYY format using JavaScript

2 comments


To display a date in mm/dd/yyyy format in JavaScript, use this script

<script type="text/javascript">
var
currentDt = new Date();
var mm = currentDt.getMonth() + 1;
var dd = currentDt.getDate();
var yyyy = currentDt.getFullYear();
var date = mm + '/' + dd + '/' + yyyy;
alert(date);
</script>

OUTPUT

image

Similarly if you want to always represent the month as double digits, just add a ‘0’ as shown below:

var mm = currentDt.getMonth() + 1;
mm = (mm < 10) ? '0' + mm : mm;

The output now is:

image

If you know of a better way without using any JavaScript frameworks, I would love to hear it! Use the comments section.

July 16, 2010

Office 2010 Getting Started and User Resources Guides

0 comments


If you are excited about the recent Office 2010 release and are keen to learn the new features, then here’s some free learning material for you!

Microsoft recently published PDF’s of ‘Getting Started Guides’ and documents related to Office 2010, including an overview, product guide, getting started, and new features.

image

Download Office 2010 User Resources

July 15, 2010

‘Copy To Clipboard’ functionality for your Website

0 comments


‘Copy Text To Clipboard’ is a frequently requested feature. Different browsers have different security implications when it comes to manipulating the clipboard. For example Firefox by default, does not allow you to store data in the clipboard, although you can override this setting.

Users have used JavaScript and Flash as a workaround. Until Flash 9, you could set data on the system clipboard at any time. However with the changes in Flash 10, you can manipulate the clipboard only through ActionScript that originates from user interaction, i.e. an explicit mouse click or through the keyboard.

I recently came across a free and open source library that is fully compatible with Flash Player 10 and provides an easy way to copy text to the clipboard using an ‘invisible’ Adobe Flash movie and a JavaScript interface. The library is called ‘zeroclipboard’. How this library works is that it overlays a Flash object over a button or any other DOM element that initiates the copy. So when the user clicks the element, the Flash object registers an explicit action and copies text into the clipboard, which sounds perfectly ‘legal’ as I may say so.

This library requires that the browser has JavaScript enabled and FlashPlayer installed. You can learn how to use the library through the Instructions Wiki. Also see a working Demo.

As always, I would love to hear some alternate solutions. Feel free to drop in your comments!

July 14, 2010

Windows Phone 7 Developer Tools Beta and Training Kit

0 comments


If you are a Windows Phone 7 Developer, then here’s an update. Microsoft just released the Windows Phone 7 Developer Tools Beta

Check the Release notes for the Beta. As quoted in Scott Gu’s post and the Official blog post, here are some major changes:

  • Microsoft Expression Blend for Windows Phone – Blend is now integrated completely into the Windows Phone Developer Tools Beta.
  • Developer Registration Utility – Now you can unlock you Windows Phone 7 device for development purposes.
  • XAP Deployment Tool – if you want to deploy XAP files directly to an unlocked device, now you can.
  • The Windows Phone 7 API – we’re getting close to completion. Many namespaces that were previously distributed over several different DLLs have now been consolidated into one. In addition, there have been realignments and changes in several other namespaces as well. Push Notifications, Accelerometer and App Bar APIs have all been updated.
  • Additional Controls – There are some additional controls coming in the next few weeks (i.e. Panorama and Pivot) which didn’t make the beta release. They are coming soon.
  • Control Templates – Silverlight for Windows Phone control templates have been updated to match evolutions in the overall OS.

You can also download the Windows Phone 7 Training Kit for Developers - Beta Refresh. This Training Kit will give you a jumpstart into the new Windows Phone world by providing you with a step-by-step explanation of the tools to use and some key concepts for programming Windows Phones

July 13, 2010

Online Tools to Test Mobile Readiness of Your WebSites

1 comments


There is a surge of mobile phones in the market and users nowadays spend a good amount of their time browsing the Internet on their handsets. In order to target this user base and give them a good ux on their mobile sets, you should consider designing your websites for mobile users too and test it for mobile readiness. This way you can find and fix issues early on during the design and take steps to correct them.

Here are some online tools to test mobile readiness for your websites.

mobiReady

mobiReady evaluates mobile readiness for your websites by doing an in-depth analysis of your pages to determine how well your site performs on a mobile device. I did an analysis of www.FaceBook.com and here are the results:

image

image


dotMobi

The dotMobi mobile phone emulator emulates a real mobile phone Web browser. You need to specify a website (in our case Facebook.com) and hit the Submit button to see how your site looks to a mobile phone user.

image

Note: You must have JAVA enabled on your browser to utilize the .mobi mobile emulator.

As of this writing, there are two skins available for Nokia N70 and Sony K750. Here’s how Facebook looks on a Sony K750 phone.

image


iPhoneTester

iPhoneTester is an online iPhone simulator to test iPhone specific websites. I tested the Facebook iPhone specific site called iphone.facebook.com to check if the website fits correctly on the iPhone's limited screen space. Here is how the site looks on a landscape view!

image

As an alternative to iPhoneTester, you can also use TestiPhone which allows you to pass the simulator request parameters to change the way it behaves.

I hope you liked these tools. If you know of any other online tool to test mobile readiness, please share them with the viewers in the comments section.

July 12, 2010

How to Disable JavaScript on browsers running IE6 or Lesser

0 comments


Web Developers often face requirements to detect the browser type and version and execute some script based on that. If you are not using any JavaScript framework, then here’s how to execute a script only if the Internet Explorer version is greater than 6 (IE6)

Just add this piece of code in between the ‘head’ tags

<head>
<
title>Execute script only if > IE 6</title>

<!--[if gte IE 7]>
<SCRIPT LANGUAGE="Javascript">
alert("You are running Internet Explorer 7 or greater");
</SCRIPT>
<![endif]-->

</head>

This is how Microsoft officially recommends you to detect the browser type and version. As stated in the documentation,

“The downlevel-hidden conditional comment contains hyphens ("--") in the opening and closing tag, similar to the basic HTML Comment. The content is placed inside the comment tags. Because the first four characters and the last three characters of the comment are identical to a basic HTML Comment element, downlevel browsers ignore the HTML content inside the comment block”

July 11, 2010

Convert a List<int> to List<string>

0 comments


Here’s how to convert a List<int> to List<string>. Use the List(T).ConvertAll method

C#

// Convert a List<int> to List<string>
List<int> lstNum = new List<int>(new int[] { 3, 6, 7, 9 });
lstNew = lstNum.ConvertAll<string>(delegate(int i)
{
return i.ToString();
});
PrintList(lstNew);

VB.NET

' Convert a List<int> to List<string>
Dim lstNum As New List(Of Integer)(New Integer() { 3, 6, 7, 9 })
lstNew = lstNum.ConvertAll(Of String)(Function(i As Integer) i.ToString())
PrintList(lstNew)

OUTPUT

image

Read more tips over here Some Common Operations using List<string>

July 10, 2010

10 Free Tools to Load/Stress Test Your Web Applications

8 comments


Wikipedia defines Load and Stress Testing as “Load testing is the process of putting demand on a system or device and measuring its response. Stress testing refers to tests that determine the robustness of software by testing beyond the limits of normal operation”.

Due to budget constraints, my clients usually ask for some free tools to load/stress test their application, before going live. Here are some free tools to Load/Stress Test web applications. Please note that this is just a listing and is in ‘no particular order’.

The Grinder - The Grinder is a load testing framework that makes it easy to run a distributed test using many load injector machines. Test scripts are written in Jython, and HTTP scripts can be recorded easily from a browser session.

Pylot - Pylot is a free open source tool for testing performance and scalability of web services. It runs HTTP load tests, which are useful for capacity planning, benchmarking, analysis, and system tuning.

Web Capacity Analysis Tool (WCAT) - Web Capacity Analysis Tool (WCAT) is a lightweight HTTP load generation tool primarily designed to measure the performance of a web server within a controlled environment. WCAT can simulate thousands of concurrent users making requests to a single web site or multiple web sites. The WCAT engine uses a simple script to define the set of HTTP requests to be played back to the web server. Extensibility is provided through plug-in DLLs and a standard, simple API.

fwptt - fwptt it's a Web application tester program for load testing web applications. It can record normal and ajax requests. I tested it on asp.net applications, but it should work with jsp, php or other.

JCrawler - JCrawler is an open-source (under the CPL) Stress-Testing Tool for web-applications. It comes with the crawling/exploratory feature. You can give JCrawler a set of starting URLs and it will begin crawling from that point onwards, going through any URLs it can find on its way and generating load on the web application

Apache JMeter – JMeter is open source software, a 100% pure Java desktop application designed to load test functional behavior and measure performance. It was originally designed for testing Web Applications but has since expanded to other test functions.

Siege - Siege is an http load testing and benchmarking utility. It was designed to let web developers measure their code under duress, to see how it will stand up to load on the internet. Siege supports basic authentication, cookies, HTTP and HTTPS protocols. It lets its user hit a web server with a configurable number of simulated web browsers.

http_load - http_load runs multiple http fetches in parallel, to test the throughput of a web server. However unlike most such test clients, it runs in a single process, so it doesn't bog down the client machine. It can be configured to do https fetches as well

Web Polygraph - Web Polygraph is a freely available performance testing tool for caching proxies, origin server accelerators, L4/7 switches, content filters, and other Web intermediaries

OpenSTA - OpenSTA is a distributed software testing architecture designed around CORBA. The current toolset has the capability of performing scripted HTTP and HTTPS heavy load tests with performance measurements from Win32 platforms. However, the architectural design means it could be capable of much more.

I hope you liked this list.

July 9, 2010

Disable Certain Days In a Week using jQuery UI DatePicker

2 comments


A couple of days ago, I had posted on Prevent Users from Selecting Weekends using jQuery UI DatePicker

Dominic mailed asking if it was possible to do this without using the built-in function 'noWeekends'. He wanted to disable Tuesdays and Fridays of every week in the DatePicker. Here’s how to achieve the same:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Disable Certains Days in a Week using jQuery UI DatePicker</title>
<
link rel="Stylesheet" type="text/css" href="http://ajax.googleapis.com/
ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" />
<
script type="text/javascript" src="http://ajax.microsoft.com/ajax/
jquery/jquery-1.4.2.min.js"></script>
<
script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/
jqueryui/1.8.2/jquery-ui.min.js"></script>


<
script type="text/javascript">
$(function() {
$("#datepic").datepicker(
{ beforeShowDay: function(day) {
var day = day.getDay();
if (day == 2 || day == 5) {
return [false, "somecssclass"]
} else {
return [true, "someothercssclass"]
}
}
});
});
</script>
</
head>
<
body>
<
input id="datepic"/>
</
body>
</
html>

OUTPUT

image

See a Live Demo

July 8, 2010

Top 10 Questions Related to Data Answered by Microsoft

0 comments


My colleague and Microsoft MVP Anoop shared an interesting tweet yesterday about the Top 10 Questions Related to Data Answered by Microsoft

The questions answered are the following:

  1. So what happened to “Oslo”?
  2. Why did you rename ADO.NET Data Services to WCF Data Services?
  3. Where does Microsoft stand on LINQ to SQL?
  4. What's happening to the "M" language? How do “M” and the Entity Data Model relate to each other? Which do I choose?
  5. When does a developer use “M” vs. T-SQL? Should I use “M” rather than T-SQL to define the shape of my data?
  6. What's New in ADO.NET Entity Framework 4 and WCF Data Services 4?
  7. What is "Quadrant" and what does it do for me?
  8. When will the SQL Server Modeling CTP ship?
  9. How does the SQL Server Modeling CTP relate to .NET?
  10. What is the Open Data Protocol (OData)?

Check out the answers here.

July 7, 2010

5 JavaScript Books Worth Every Cent

11 comments


An investment in knowledge always pays the best interest – Benjamin Franklin

The dynamic web is full of interactive ‘ajaxified’ websites and JavaScript is one of the most important pillars that goes into the construction of these websites. With JavaScript frameworks like jQuery, Prototype, Scriptaculous etc. becoming popular, it has become all the more important to learn and master JavaScript, to be able to use these frameworks effectively and efficiently. To learn a programming language, the simplest way in my opinion is to purchase a good book, read it, and then put the learning into practice, a lot of practice!

Here are 5 JavaScript books I strongly recommend if you are looking out to start client-side development and master it. This collection also contains some upcoming books I plan to purchase. I have categorized these books for Beginners as well as Intermediate-Advanced developers.


JavaScript Books For Beginners



DOM Scripting: Web Design with JavaScript and the Document Object Model

image

This book is the Get-Start-Go guide for beginners with a good introduction to JavaScript and DOM concepts. Full of clearly explained practical examples (dynamic image gallery, slideshow animations, sample site) that you can use on your website, this book gets you up to speed with JavaScript and DOM in no time. I personally loved Jeremy’s tone of writing as well the presentation of concepts, that makes JavaScript look so easy. Although this book was published a couple of years ago, I strongly recommend this book as an excellent starting point for beginners. Jeremy has also authored Bulletproof Ajax that you may want to check out.


Object-Oriented JavaScript: Create scalable, reusable high-quality JavaScript applications and libraries

image

After you have read the DOM Scripting: Web Design with JavaScript and the Document Object Model book and have gained some level of experience with it, you should consider picking up this book. The first 4 chapters in this book are introductory chapters. The book starts getting exciting Chapter 5 onwards with examples on how to write object-oriented JavaScript. In my opinion, Chapter 8 - Coding and Design Patterns is the best chapter in this book.

As a side note, FireBug comes very handy while reading this book. The hands-on approach demonstrated in this book to write Object Oriented JavaScript code and the usage of patterns, is a reason why I strongly recommend this book.


JavaScript Books For Intermediate-Advanced Developers



JavaScript: The Good Parts

image

Douglas Crockford, as many of you already know, is a JavaScript champion and his advices on JavaScript is well known in the community, and when someone like him shares his knowledge through a book, you MUST buy it! This book is not for beginners, but for those who after a brush-up with the language and some hands-on experience, want to take their skills to the next level.

This book is to the point, well-written, sincere and does a great job of assessing the good and the bad of JavaScript. The parts where Crockford explains inheritance, invocation, scoping and closures are simply superb. If you are serious about learning JavaScript, you must have this book in your collection. Ever since I read his book, I changed the way I look at JavaScript!


JavaScript: The Definitive Guide: – 6th Edition

image

Although this book has not yet been released as of this writing, I have David Flanagan’s previous edition – JavaScript The Definitive Guide (5th Edition) with me. The 5th Edition was a very popular JavaScript book, gave a deep understanding of JavaScript and was amongst my favorites.

There’s no reason for me to believe that the new one will not be as useful as the 5th edition and this one’s definitely going into my collection. From the O’Reilly site: The sixth edition offers comprehensive coverage of ECMAScript 5 (the new language standard) and also the new APIs introduced in HTML5. The chapters on functions and classes have been completely rewritten and updated to match current best practices. A new chapter covers language extensions and subsets.


Secrets of the JavaScript Ninja

JavaScript Ninja

I am a big fan of the creator/lead developer of jQuery and a JavaScript expert, John Resig. I remember purchasing his book Pro JavaScript Techniques way back in 2007 and this is one of the best JavaScript books I have read.

I am excited about the soon-to-be-released In Secrets of the JavaScript Ninja book. In this book, John reveals the inside know-how of the elite JavaScript programmers. Written to be accessible to JavaScript developers with intermediate-level skills, this book gives you the knowledge you need to create a cross-browser JavaScript library from the ground up.


I hope you liked these JavaScript book recommendations. If you are serious about doing some solid client-side development, I would strongly recommend you to invest in these books!

July 6, 2010

Count Repeated Words in a List<String>

0 comments


Here’s how to count repeated words in a List<string>

C#

static void Main(string[] args)
{
List<string> strList = new List<string>()
{
"Jane", "Bandy", "Ram", "Jane", "Bandy", "Carol", "Bandy"
};

// Count Repeated Words
var q = strList.GroupBy(x => x)
.Select(g => new { Value = g.Key, Count = g.Count() })
.OrderByDescending(x => x.Count);

foreach (var x in q)
{
Console.WriteLine("Value: " + x.Value + " Count: " + x.Count);
}
}

VB.NET

Shared Sub Main(ByVal args() As String)
Dim strList As New List(Of String)() From {"Jane", "Bandy", "Ram", _
"Jane", "Bandy", "Carol", "Bandy"}

' Count Repeated Words
Dim q = strList.GroupBy(Function(x) x).Select(Function(g) New _
With {Key .Value = g.Key, Key .Count = g.Count()}) _
.OrderByDescending(Function(x) x.Count)

For Each x In q
Console.WriteLine("Value: " & x.Value & " Count: " & x.Count)
Next x
End Sub

OUTPUT

image

Read more tips over here Some Common Operations using List<string>

 

Copyright © 2009-2011 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions