jQuery and ASP.NET

September 30, 2010

Monitor Website Uptime using Free Services

12 comments


A webmasters biggest nightmare is receiving mails from visitors informing that the website is down. A website can be down for many reasons including hardware failure, software issues, security reasons or a power outage.

Most Webhosting companies (even those who claim 99.99% uptime) do not notify you about an unscheduled downtime and if you happen to inform them about the website going down every now and then, here’s a standard answer - ‘It seems there are some routers across the world having an issue and we cannot help as this is third party’. Moreover they fail to acknowledge the mails from your visitors as they are not ‘real-proofs’

So in this scenario, how do you monitor your site’s uptime and get notified, when there’s an issue? Here are 5 Free tools that I suggest to monitor your website uptime for Free. Feel free to use the comments section and suggest any other services that you have used to monitor the uptime of for your websites:


Uptime Robot

image

This is one of my favorite uptime monitoring services! It checks your website headers and monitors status codes for errors or timeouts. While most uptime monitoring tools monitor your website after a one hour interval, Uptime Robot monitors your websites every 5 minutes, for FREE.

  • Monitors 50 websites
  • 5 minutes monitoring frequency
  • Alerts via Email, SMS, RSS and Twitter
  • Supports websites with SSL certificates as well as self-signed certificates

.mon.itor.us

image

Once you get started, .mon.itor.us monitors your websites, network devices and more and reports your site outage and response time. The Free Service:

  • Monitors unlimited sites
  • Checks from USA and Europe
  • 30 minutes monitoring frequency
  • Alerts via SMS, E-mail, RSS and Instant Messenger

Montastic

image

Monstastic, as they put it, is the free website monitoring service that doesn't suck! The Free Service:

  • Monitors 3 websites
  • Checks from multiple locations in USA
  • Support for http, https and port numbers
  • 30 minutes – 1 day (selectable) monitoring frequency
  • Alerts via E-mail, RSS and PC & Mac widgets

    100Pulse

    image

    100pulse website monitoring checks on your site regularly and monitor websites for downtime and response time. The free uptime monitoring service monitors http services. The Free Service:

    • Monitors two sites
    • 15 minute – 3 hours (selectable) monitoring frequency
    • Alerts via E-mail, RSS, Twitter
    • Weekly, Month Periodic Reports

    InternetSeer

    InternetSeer is probably the world's largest website monitoring service. Their monitoring systems remotely check your website from several geographic monitoring stations at selected intervals. If the monitoring system is unable to reach the site, an email, cell phone or pager alert is sent to notify you of the problem. The Free Service:

    • Monitors one site
    • 60 minute monitoring frequency
    • Confirm all alert errors prior to notifying you
    • Alerts via E-mail, phone email or pager email
    • Weekly Performance Report

    September 29, 2010

    ASP.NET Security Update - Important

    0 comments


    I had recently blogged about ASP.NET Security Vulnerability. There was an announcement by Scott Guthrie about a security update released by Microsoft to fix the ASP.NET Security Vulnerability

    Download the Update here and install it on your servers.

    Here’s a summary of the security bulletin - ”This security update resolves a publicly disclosed vulnerability in ASP.NET. The vulnerability could allow information disclosure. An attacker who successfully exploited this vulnerability could read data, such as the view state, which was encrypted by the server. This vulnerability can also be used for data tampering, which, if successfully exploited, could be used to decrypt and tamper with the data encrypted by the server. Microsoft .NET Framework versions prior to Microsoft .NET Framework 3.5 Service Pack 1 are not affected by the file content disclosure portion of this vulnerability. The security update addresses the vulnerability by additionally signing all data that is encrypted by ASP.NET

    September 28, 2010

    Fully Qualified Path in .NET

    1 comments


    I was writing a program where I had to resolve its fully qualified path using Environment Variables. Here’s how it is done using the ‘PATH’ Environment variable

    static void Main(string[] args)
    {
    // List Environment Variables
    foreach (DictionaryEntry de in Environment.GetEnvironmentVariables())
    Console.WriteLine("{0}={1}", de.Key, de.Value);

    Console.WriteLine("--------------");
    Console.WriteLine("Fully Qualified Path");
    string ext = "notepad.exe";
    string fullPath = Environment.GetEnvironmentVariable("PATH")
    .Split(';')
    .FirstOrDefault(p => File.Exists(Path.Combine(p, ext)));
    Console.WriteLine(fullPath);
    Console.ReadLine();
    }

    OUTPUT (partial)

    image

    September 27, 2010

    Detect Mobile Device using ASP.NET

    5 comments


    Not many developer are aware that there is a property available in .NET called the HttpCapabilitiesBase.IsMobileDevice that lets you detect Mobile Device Browsers. Just use the following code:

    C#

    using System;
    using System.Web;
    using System.Web.Configuration;

    public partial class _Default : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {
    HttpBrowserCapabilities hbc = Request.Browser;
    if (((HttpCapabilitiesBase)hbc).IsMobileDevice)
    {
    Response.Write("You are browsing from a mobile device");
    }
    else
    {
    Response.Write("No mobile device");
    }
    }
    }




    VB.NET


    Imports System
    Imports System.Web
    Imports System.Web.Configuration

    Partial Public Class _Default
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    Dim hbc As HttpBrowserCapabilities = Request.Browser
    If (CType(hbc, HttpCapabilitiesBase)).IsMobileDevice Then
    Response.Write("You are browsing from a mobile device")
    Else
    Response.Write("No mobile device")
    End If
    End Sub
    End Class


    September 26, 2010

    A potentially dangerous Request.Form value was detected from the client – ASP.NET 4.0

    0 comments


    If you happen to upgrade your .NET Framework to use the .NET 4.0 CLR's version of ASP.NET, then it helps keeping the ASP.NET 4.0 breaking changes document handy.

    After the upgrade, most of the users using the Rich-text editors or textboxes to submit HTML data, encounter the following error “Exception type: System.Web.HttpRequestValidationException Exception message: A potentially dangerous Request.Form value was detected from the client

    Now we know about the request validation feature in ASP.NET that shields cross-site scripting (XSS) attacks to a certain level. However this level of security changes in ASP.NET 4.0 making it stricter in terms of request validation.

    As given in the documentation “In ASP.NET 4, by default, request validation is enabled for all requests, because it is enabled before theBeginRequest phase of an HTTP request. As a result, request validation applies to requests for all ASP.NET resources, not just .aspx page requests. This includes requests such as Web service calls and custom HTTP handlers. Request validation is also active when custom HTTP modules are reading the contents of an HTTP request

    To fix this error, open your web.config and add the following setting inside <system.web> as shown here

    <system.web>
    <httpRuntime requestValidationMode="2.0" />
    ... rest of your attributes come here

    The <httpRuntime requestValidationMode="2.0" /> disables validation for request data. Although this isn’t particularly a very good fix as it compromises security, I believe it’s the only quick hack available unless you want to float your own custom request validator.

    September 25, 2010

    Convert String to Dictionary using LINQ

    1 comments


    We were working on a requirement where we had a string containing key-value pairs as shown below:

    string htmlStr = "[Emp=1][Dept=2][Age=35][Sex=M]";

    We had to convert this string to a Dictionary in the simplest possible way. Here’s how it can be done using Enumerable.ToDictionary()

    C#


    public static void Main()
    {
    string htmlStr = "[Emp=1][Dept=2][Age=35][Sex=M]";
    string[] arr = htmlStr.Split(new[] { '[', ']' },
    StringSplitOptions.RemoveEmptyEntries);
    // convert to a Dictionary
    var dict = arr
    .Select(x => x.Split('='))
    .ToDictionary(i => i[0], i => i[1]);
    }

    VB.NET (Converted Code)


    Public Shared Sub Main()
    Dim htmlStr As String = "[Emp=1][Dept=2][Age=35][Sex=M]"
    Dim arr() As String = htmlStr.Split( { "["c, "]"c }, StringSplitOptions.RemoveEmptyEntries)
    ' convert to a Dictionary
    Dim dict = arr.Select(Function(x) x.Split("="c)).ToDictionary(Function(i) i(0), Function(i) i(1))
    End Sub

    As you can see, we first split the string and then use the ToDictionary method to convert the split string into a Dictionary object

    OUTPUT

    image

    September 24, 2010

    Silverlight 4 Color Palette

    0 comments


    In this post, we will see how to read all the colors from ‘System.Windows.Media.Colors’ class and create a color palette in Silverlight. This class contains every color as a property of the structure ‘System.Windows.Media.Color’ type. With the help of reflection, the ‘Colors’ class can be loaded.

    Step 1: Create a SL application, name it as ‘SILV4_ColorPlate’. Write the following XAML code in MainPage.Xaml

    <Grid x:Name="LayoutRoot" Background="White" Height="598" Width="605">
    <ListBox Height="447" HorizontalAlignment="Left" Margin="22,13,0,0"
    Name="lstColor" VerticalAlignment="Top" Width="436"
    SelectionChanged="lstColor_SelectionChanged"/>
    <Button Content="Button" Height="41" HorizontalAlignment="Left"
    Margin="487,84,0,0" Name="btnColor" VerticalAlignment="Top"
    Width="93" />
    </Grid>

    Step 2: Open MainPage.Xaml.cs and in the loaded event write the following code. Add a reference to System.Reflection:


    private void UserControl_Loaded(object sender, RoutedEventArgs e)
    {
    Type t = typeof(System.Windows.Media.Colors);

    PropertyInfo[] sysColors = t.GetProperties();

    foreach (var color in sysColors)
    {
    //Read the Structure here
    Color c = (Color)color.GetValue(null, null);

    StackPanel stkPnl = new StackPanel();
    stkPnl.Width = lstColor.Width;
    stkPnl.Orientation = Orientation.Horizontal;

    TextBlock txtColName = new TextBlock();
    txtColName.Text = color.Name;
    txtColName.Width = 70;
    txtColName.Height = 20;
    Rectangle rectColor = new Rectangle();

    rectColor.StrokeThickness = 6;
    rectColor.Fill = new SolidColorBrush(c);
    rectColor.Width = 60;

    TextBlock txt = new TextBlock();
    txt.Width = 20;

    stkPnl.Children.Add(txtColName);
    stkPnl.Children.Add(txt);
    stkPnl.Children.Add(rectColor);

    ListBoxItem item = new ListBoxItem();
    item.Content = stkPnl;

    lstColor.Items.Add(item);
    }
    }

    The above code makes use of reflection to load all the colors from the Colors class. Every property is read and its name is displayed using the ‘TextBlock’. This property is type-casted to the ‘Color’ structure. The ‘SolidColorBrush’ object is created using the Color structure and the Fill property of the rectangle is set using this Color object.

    Step 3: Write the following code in the ‘SelectionChanged’ event of the ListBox ‘lstColor’ as shown below:


    private void lstColor_SelectionChanged(object sender,
    SelectionChangedEventArgs e)
    {
    ListBoxItem item = lstColor.SelectedItem as ListBoxItem;

    StackPanel pnl = item.Content as StackPanel;

    foreach (UIElement ele in pnl.Children)
    {
    if (ele.GetType() == typeof(Rectangle))
    {
    btnColor.Background = ((Rectangle)ele).Fill;
    }
    }
    }

    The code shown above reads the selected ListBoxItem. Since this selection returns an object of ‘StackPanel’, every child element is read from the UIElementCollection of the StackPanel. If the element is of the type ‘Rectangle’, its ‘Fill’ property is assigned to the ‘Background’ property of the ‘Button’.

    That’s it. Run the application and the following result will be displayed:

    image

    September 23, 2010

    Programmatically add Content to the Popup control in Silverlight

    0 comments


    Adding a Popup to a Silverlight application is as easy as dragging and dropping a Popup control from the ToolBox

    <Popup x:Name="popup" />

    However if you want to programmatically add content to the Popup control, here’s how to do so:

    private void Button_Click(object sender, RoutedEventArgs e)
    {
    //Create Popup content with a border, background color
    // and a child element Button
    popup.Child = new Border()
    {
    Height= 150,
    Width=150,
    Background = new SolidColorBrush(Colors.LightGray),
    Child = new Button() { Content = "OK", Height=50, Width=50 }
    };

    // Show/hide Popup
    popup.IsOpen = !popup.IsOpen;
    }
    }

    As you can see, we are programmatically adding a Border element, specifying attributes of the Popup like Height, Width, Background Color and also adding a Button inside the popup, with attributes of its own. It’s common for developers to use the Popup type to create Cascading Menus programmatically!

    September 22, 2010

    Learn JavaScript, straight from the Gurus - Free JavaScript Video Lectures

    5 comments


    I consider myself lucky to ‘know’ and have ‘access’ to these brilliant and free JavaScript videos and lectures, delivered by the best in the industry.

    In this post, I will share links of some very useful JavaScript videos and lectures delivered by JavaScript Gurus, full of information, fun watching and absolutely Free! Although the internet is full of free videos, I have chosen only a couple of them, which I found the most useful. Get ready to take notes as you learn..

    Crockford’s video lectures on JavaScript – Douglas Crockford is a JavaScript architect and plays an important role in designing new features of the language. His videos are a ‘must-have’ for any JavaScript developer.

    YUI Theater - Provides access to free programming talks by gurus on JavaScript and web development.

    Channel 9 JavaScript videosTalk shows and videos about JavaScript. Also contains videos of using JavaScript with Microsoft technologies.

    David J Malan Dynamic Website Lectures - Professor David J. Malan discusses the use of JavaScript in building dynamic websites - Lecture 8 and Lecture 9

    Google: HTML, CSS, and Javascript from the Ground UpBasic understanding of how UI’s are created using HTML, CSS and JavaScript.

    Here are some additional videos I found interesting, in no particular order

    The Past, Present and Future of JavaScript

    Crockford – Javascript: The Good Parts (Excellent talk)

    Nicholas Zakas: "Maintainable JavaScript"

    John Resig: "Advancing JavaScript with Libraries" - 1 of 2

    John Resig: "Advancing JavaScript with Libraries" - 2 of 2

    Best Practices in Java script Library Design

    High-performance JavaScript: Why Everything You’ve Been Taught Is Wrong

    If you know of any other JavaScript videos/lectures that are available freely, please share them with the viewers in the comments section

    September 21, 2010

    Detect if a String contains Special Characters

    0 comments


    There are many ways to detect if a String contains Special Characters. In this code snippet, I will show a quick way to detect special characters using Regex.

    C#

    static void Main(string[] args)
    {
    string str = "Th!s $tri^g c@n$ist $pecial ch@rs";
    Match match = Regex.Match(str, "[^a-z0-9]",
    RegexOptions.IgnoreCase);
    while (match.Success)
    {
    string key = match.Value;
    Console.Write(key);
    match = match.NextMatch();
    }
    Console.ReadLine();
    }

    VB. NET

    Shared Sub Main(ByVal args() As String)
    Dim str As String = "Th!s $tri^g c@n$ist $pecial ch@rs"
    Dim match As Match = Regex.Match(str, "[^a-z0-9]", _
    RegexOptions.IgnoreCase)
    Do While match.Success
    Dim key As String = match.Value
    Console.Write(key)
    match = match.NextMatch()
    Loop
    Console.ReadLine()
    End Sub

    Regex.Match searches the input string for the first occurrence of the regular expression specified. The Success property of the Match object tells us whether the regular expression pattern has been found in the input string. If yes, then print the first match and retrieve subsequent matches by repeatedly calling the Match.NextMatch method.

    OUTPUT

    image

    September 20, 2010

    Filter a Type in .NET inside the For-Each Loop

    0 comments


    Here’s a nice way to filter an ArrayList right inside the For-Each Loop. We have to filter and print only ‘integers’ greater than 10.

    static void Main(string[] args)
    {
    ArrayList arr = new ArrayList();
    arr.Add(15);
    arr.Add(25.35);
    arr.Add(10);
    arr.Add(20);
    arr.Add(25);
    arr.Add(20.2);

    foreach (var num in arr.OfType<int>().Where(x => x > 10))
    {
    Console.WriteLine(num);
    }

    Console.ReadLine();
    }

    As you can observe, we are using the Enumerable.OfType<TResult> inside the foreach loop to filter only those elements of the ArrayList which are integers and greater than 10. This code will only work in .NET 3.5 and above.

    OUTPUT

    image

    September 19, 2010

    ASP.NET Security Vulnerability found - take steps NOW to secure your web.config

    0 comments


    Quoted from the Microsoft Security Advisory “Microsoft is investigating a new public report of a vulnerability in ASP.NET. An attacker who exploited this vulnerability could view data, such as the View State, which was encrypted by the target server, or read data from files on the target server, such as web.config. This would allow the attacker to tamper with the contents of the data. By sending back the altered contents to an affected server, the attacker could observe the error codes returned by the server. We are not aware of attacks that try to use the reported vulnerabilities or of customer impact at this time.”

    [Updated] - Update on Security Vulnerability

    Additional Info and Workaround

    Important: ASP.NET Security Vulnerability

    Understanding the ASP.NET Vulnerability

    ASP.NET POET Vulnerability - What Else Can I Do?

    Oracle Padding Vulnerability in ASP.NET

    Where can I ask Questions?

    Post questions here

    September 18, 2010

    jQuery UI 1.8.5 Released to Microsoft CDN – Example with Live Demo

    1 comments


    The jQuery UI team released jQuery UI 1.8.5 yesterday which contains some bug fixes in the jQuery UI Core, Utiities, Widgets and Effects. You can see the release note here.

    Along with this release, what particularly got me excited was that now we have a choice of CDN’s for the jQuery UI library. Along with the Google CDN, the jQuery UI is also available on Microsoft CDN. Here’s the link to jQuery UI on Microsoft CDN. This links includes the Libraries, Theme CSS and Internationalization/Localization files. Way cool!

    Here’s an example of using jQuery UI Library and Themes from Microsoft CDN (adapted from one of my jQuery how-to-do’s) to prevent users from selecting weekends while using the jQuery UI DatePicker

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <
    head>
    <
    title>Prevent users from selecting weekends in jQuery UI
    DatePicker(from DevCurry.com)</title>
    <
    link type="text/css" rel="Stylesheet"
    href="http://ajax.microsoft.com/ajax/jquery.ui/1.8.5/themes/
    smoothness/jquery-ui.css" />
    <
    script type="text/javascript" src="
    http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
    </
    script>
    <
    script type="text/javascript" src="
    http://ajax.microsoft.com/ajax/jquery.ui/1.8.5/jquery-ui.min.js">
    </
    script>

    <
    script type="text/javascript">
    $(function () {
    $("#datepic").datepicker({
    beforeShowDay: $.datepicker.noWeekends
    });
    });
    </script>
    </
    head>
    <
    body>
    <
    input id="datepic"/>
    </
    body>
    </
    html>
    image 

    See a Live Demo

    I have also updated my link List Latest jQuery and jQuery UI Theme links on Google CDN

    September 17, 2010

    Silverlight Toolkit for Windows Phone 7 RTW Released

    0 comments


    This looks like a week of major releases! With the release of IE 9 Beta still fresh, Microsoft recently released the Windows Phone Developer Tools RTW. The WP7 Developer Tools allow you create .NET applications for the Windows Phone 7 platform using the Silverlight. I am really excited since these Tools hit the RTM.

    This release contains the following:

    • Visual Studio 2010 Express for Windows Phone
    • Windows Phone Emulator Resources
    • Silverlight 4 Tools For Visual Studio
    • XNA Game Studio 4.0
    • Microsoft Expression Blend for Windows Phone

    Here are some important links:

    Download Windows Phone Developer Tools RTW

    Windows Phone Developer Tools Release Notes

    Windows Phone 7 Training Kit for Developers - RTM Refresh

    Silverlight Toolkit for Windows Phone 7 – Quick Preview

    September 16, 2010

    Internet Explorer 9 Beta Released – Is the Web Blushing?

    0 comments


    Competition brings out the best!

    The internet currently is being stormed with the news of IE 9 Beta release. Well there’s a reason for it, as although developers and users got a glimpse of IE9 features through the platform previews and the test drives, the user interface has been released for the first time for the public to view.

    Through the IE 9 platform previews, it was evident to an IE user/developer that this is the best effort the IE team has made so far and it did pay off. This new version of IE and it’s interface, is absolutely amazing!! Here are some key features that I would like to point at:

    • cleaner, streamlined interface, with focus on content.
    • faster browser, fast enough to compete and surpass competitor browsers in some areas
    • more secure
    • GPU-powered, hardware acceleration
    • improved JavaScript Engine
    • better support for HTML5, CSS3 embracing modern web
    • Seamless integration with Windows 7
    • and much more…

    Watch a video of IE 9 below (video opens in a new browser)

    image

    If you are new to IE 9 and have never seen/heard about it before, see all the demos of the test drive. Since this is a beta product, there are going to be some crashes (I encountered one). Nevertheless, once you start using it, you keep saying to yourself ‘Man, this is a great product’. Here’s an excellent and a detailed review by Ed Bott Internet Explorer 9 beta review: Microsoft reinvents the browser

    I am gearing up to put aside the sluggish experience I had with the previous version of IE (IE 8) and now look forward to the IE 9 release and I must admit, I am already enjoying this beautiful online experience. Kudos IE Team!

    Download IE 9 Beta over here

    September 15, 2010

    Print Special Characters like the Copyright Symbol using JavaScript

    1 comments


    To print special characters like the Copyright symbol © or a Trademark ™ using JavaScript, use escape sequences.

    For example, to print the Copyright symbol ©, use this code:

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <
    head>
    <
    title>Print Special Characters using JavaScript</title>
    </
    head>
    <
    body>
    <
    div id="divOne" />
    <
    script type="text/javascript">
    var
    str = "Copyright \u00A9 DevCurry.com";
    document.getElementById('divOne').innerHTML = str;
    </script>
    </
    body>
    </
    html>

    Check some more Character Entity References over here. Note that escape sequences in JavaScript begins with a backslash character (\) like \u00A9 and so on.

    OUTPUT

    image

    September 14, 2010

    Populate a DropDownList with a Sequence of Numbers using LINQ

    1 comments


    Let us assume you want to populate a DropDownList with ‘Years’ data ranging from 1990 to 2010. The LINQ Range Operator is extremely useful in such situations to quickly generate a sequence of numbers. Here’s how to populate an ASP.NET DropDownList with a Sequence of Numbers using a single line of LINQ code.

    C#

    protected void Page_Load(object sender, EventArgs e)
    {
    DropDownList1.DataSource = Enumerable.Range(1990, 21).ToList();
    DropDownList1.DataBind();
    }

    VB.NET

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    DropDownList1.DataSource = Enumerable.Range(1990, 21).ToList()
    DropDownList1.DataBind()
    End Sub

    As you can see, we use the Enumberable.Range method to generate a sequence of integers within a range and then bind the DropDownList to the list of integers.

    OUTPUT

    image

    September 13, 2010

    Creating a Google Chrome Extension is as Easy as 1-2-3

    16 comments


    Chrome Extension allows 3rd-party developers to add new functionality to the Google Chrome browser. Did you know, all that it takes to develop a Google Chrome Extension is HTML, CSS, JavaScript and an icon. Sounds doable right? Let’s see how easy it is to create a ‘World Clock/Time’ Chrome Extension.

    Step 1: Create a folder on your computer and call it JSClock. Create a manifest file (text file) inside the folder and call it manifest.json. Add the following contents to the file

    {
    "name": "World Clock",
    "version": "1.0",
    "description": "World Clock showing Time of 12 countries",
    "browser_action": {
    "default_icon": "clock.ico",
    "popup": "clock.html"
    }
    }

    Note: If you are using any information from an external website, such as Google or Flickr, you also need to provide permission to the environments in which you’ll work. That’s done by adding the permission info to the manifest as follows:

    "permissions": ["http://*.google.com/", "http://api.flickr.com/"]

    Anyways for this example, we do not need to add the permission info. So leave the manifest as it is. As you will observe, the manifest file provides browser actions (for UI) to load a HTML page and an icon. So let’s create them.

    Step 2: Add an icon to the folder. I downloaded a clock icon file from here and rename it as clock.ico

    Step 3: Now create a clock.html page and add your JavaScript, CSS and HTML tags in it. I downloaded a free World Clock script over here and added it to clock.html.

    Your extension is ready. I told you it’s easy! You can download the entire folder here (uncompress it before using).

    Installing the Extension

    Step 4: All you have to do now is load the extension in Chrome. Open Chrome, click on the Tools icon (image )in the top-right corner of your browser > Select Tools > Extensions. Click the + Developer Mode to expand it if it is not already expanded.

    image

    Click on ‘Load unpacked extension..’ button and browse to the JSClock folder and click ok. If everything is in place, you will be able to view information about the extension in the extensions page as shown below:

    image

    Your extension has been installed! To view it, check the World Clock icon next to the address bar in the Chrome toolbar.

    image

    Clicking the dropdown brings up the rest of the countries.


    image

    If you plan to distribute your extension, the contents of the folder are packaged into a special ZIP file that has a .crx suffix. Read more on Hosting an extension

    IMHO, Developing an extension for Google Chrome is the simplest of all the browsers! Note that I have tested this extension only on Windows, although it should also work on a Mac.

    September 12, 2010

    jQuery DatePicker – Select a Date Programmatically

    3 comments


    I have seen users asking how to programmatically select a date using jQuery UI DatePicker control.

    The DatePicker beforeShowDay event is ideal for this type of a requirement. As described in the documentation “The function takes a date as a parameter and must return an array with [0] equal to true/false indicating whether or not this date is selectable, [1] equal to a CSS class name(s) or '' for the default presentation, and [2] an optional popup tooltip for this date. It is called for each day in the DatePicker before it is displayed.”

    Here’s an example. Assume you want to select a date “9-22-2010”

    <html xmlns="http://www.w3.org/1999/xhtml">
    <
    head>
    <
    title>Select a Date in jQuery 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.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
    </
    script>
    <
    script type="text/javascript"
    src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.4/jquery-ui.min.js">
    </
    script>

    <
    script type="text/javascript">
    $(function () {
    $("#devcurry-datepic").datepicker({
    beforeShowDay: function (date) {
    var selDate = "9-22-2010";
    // month are 0 based, so +1.
    var mm = date.getMonth() + 1, dd = date.getDate(),
    yy = date.getFullYear();
    // format date
    var dt = mm + "-" + dd + "-" + yy;
    if (dt == selDate) {
    return [true, "ui-state-hover"];
    }
    return [true, ""];
    }
    });
    });
    </script>
    </
    head>
    <
    body>
    <
    input id="devcurry-datepic"/>
    </
    body>
    </
    html>

    In the code shown above, we format the date and compare it with the date that has to be selected. If it matches, apply a css style ‘ui-state-hover’ to give it a selected feel. You can use any other class you want. The result is shown below with 22nd September selected.


    image

    Has anyone been able to use the setDate function in this scenario. It seems this function worked only in the previous versions of jQuery UI. Let me know if it has worked for you!

    September 11, 2010

    Windows Server AppFabric Architecture Guide for enterprise-scale load requirements

    0 comments


    Microsoft recently released the Windows Server AppFabric Architecture Guide.

    The focus of this document is to provide specific recommendations on how to properly design an AppFabric deployment for enterprise-scale load requirements. The document discusses the following:

    • high-level understanding of the primary components of AppFabric.
    • specific issues that influence your AppFabric architecture that include concepts surrounding configuration of the hosting environment, the AppFabric Windows services, and deployment of .NET Framework WCF and WF services to an AppFabric web farm
    • understand how to conceptually scale out an AppFabric installation at the service and database tiers. The configuration of the persistence and monitoring data plays an important role in ensuring that your architecture is able to scale correctly over time.
    • look at optimizations and different server and cluster configurations at the data-tier level.

    You may also want to also look at the Windows Server AppFabric Web Farm Guide which contains related deployment and configuration information.

    What is App Fabric?

    As given in the document - AppFabric extends Windows Server to provide enhanced hosting, management, and caching capabilities for web applications and middle-tier services. The AppFabric hosting features add service management extensions to Internet Information Services (IIS), Windows Process Activation service (WAS), and the .NET Framework version 4. These features include Hosting Services and Hosting Administration tools that make it easier to deploy, configure, and manage Windows Communication Foundation (WCF) and Windows Workflow Foundation (WF)-based services.

    September 10, 2010

    jQuery UI DatePicker Date Range

    3 comments


    In this post, I will show you how to specify Date Range for the jQuery UI DatePicker control, using the maxDate and minDate options.

    The Current Date for these examples is assumed to be 10th September, 2010.

    Specify Date Range in Months - You can specify selectable months in the DatePicker as shown below:

    <script type="text/javascript">
    $(function () {
    $("#datepic").datepicker({ minDate: 0, maxDate: '+1M' });
    });
    </script>

    The above code makes only the current date and one month, starting from the current date, selectable. Rest all the dates are disabled as shown below.

    image


    Specify DateRange in Weeks - You can specify selectable weeks in the DatePicker as shown below:

    <script type="text/javascript">
    $(function () {
    $("#datepic").datepicker({ minDate: '-1w', maxDate: '+2w' });
    });
    </script>

    The above code sets the selectable range to 2 weeks from the current day and 1 week prior to the Current Day. Rest all the dates are not selectable.

    image


    Specify Date Range in Days – You can specify selectable days in the DatePicker as shown below:

    <script type="text/javascript">
    $(function () {
    $("#datepic").datepicker({ minDate: '-6d', maxDate: '+6d' });
    });
    </script>

    The above code restricts the user to select dates only within the range of 6 days before and 6 days after, the current day.

    image


    Note: The different periods that can be used in the DatePicker are as follows - 'y' for years, 'm' for months, 'w' for weeks and 'd' for days. You can also specify a combination of periods like '+1y +3m +2w +6d' which is equal to 1 Year, 3 Months, 2 Weeks and 6 days.

    Note: The user can directly type in the textbox and override the restrictions you have set on the datepicker. It is advised to always use server-side validation in addition to client-side validation.

    September 9, 2010

    Silverlight PivotViewer

    0 comments


    If you have not yet checked out the Silverlight PivotViewer control, then I suggest you do so. Similar to the Pivot WPF application, the PivotViewer control enables amazing data visualization experiences on massive amounts of data. With a combination of DeepZoom, animation and transitions, you can represent collections in a powerful and interactive manner.

    Watch a Silverlight PivotViewer introduction video below to see the rich powerful user experiences you can create using this control

    image

    To develop applications with the PivotViewer, you would require Visual Studio 2010, Silverlight 4 Tools for Visual Studio 2010, and Silverlight 4 Toolkit.

    Get the PivotViewer Control and its Technical Documentation

    September 8, 2010

    Deserialize JSON string and bind to ASP.NET DropDownList

    7 comments


    This post is written by guest blogger Aamir Hasan

    This article demonstrates how to Deserialize JSON string and bind to an ASP.NET DropDownList control.

    Open Visual Studio 2010 and create a new ASP.NET Web Application. Right click the project > Add New Item > Class. Name the class ListItems.cs and click Ok. Visual Studio will pop a message to save the class in the App_Code folder. Click Ok.

    Open the ListItems Class and add the following code to hold the name and values from the JSON string:

    public class ListItems
    {
    public string[] Names { set; get; }
    public string[] Values { set; get; }
    }

    Now drag and drop a DropDownList control from the ToolBox to your Default.aspx page as shown below:

    <asp:DropDownList ID="DropDownList1" runat="server">
    </
    asp:DropDownList>

    Open your Default.aspx.cs page and in the Page load, add the following code:

    protected void Page_Load(object sender, EventArgs e)
    {
    if (!IsPostBack) { // thanks to azmsharp for the correction
    string JSONString = "{\"Names\":[\"Aamir\",\"Hasan\",\"Awais\"," +
    "\"Ahmed\",\"Saba\",\"Sobia\"],"
    + "\"Values\":[\"0x1\",\"0x2\",\"0x3\",\"0x4\",\"0x5\",\"0x6\"]}";
    JavaScriptSerializer _convert = new JavaScriptSerializer();
    ListItems _Items = _convert.Deserialize<ListItems>(JSONString);

    for (int i = 0; i < _Items.Names.Length; i++)
    {
    this.DropDownList1.Items.Add(new ListItem(_Items.Names[i]));
    }
    }
    }

    Make sure that you add a reference to the System.Web.Script.Serialization namespace. In the code shown above, we have created a sample JSON string and then deserialized and cast it to ListItems class. In the last step, we loop through the items and then bind it to the DropDropList control.

    Note: We have used the JavaScriptSerializer class to do the deserialization. You can also use a third party library like JSON.NET or the DataContractJsonSerializer class.

    Run the web application and you can see that your DropDownList is populated with JSON string items.

    image

    Aamir Hasan, is a Sr. Software Engineer and Technical Lead in a US based firm, having five years of experiences working on Microsoft products. He is capable of coordinating off-shore high level web development projects.

    September 7, 2010

    Highest Value in each Group using LINQ

    1 comments


    In this post, I will show you how to fetch the maximum value in each Group using LINQ

    Let us consider you have the following class called Employees

    C#

    class Employees
    {
    public int EmpId { get; set; }
    public int DeptId { get; set; }
    public int Salary { get; set; }
    }

    You want to find out the highest salary of an Employee in each Department. Here’s the LINQ query:

    C#

    List<Employees> emp = new List<Employees>();
    // populate emp – demo by devcurry
    // emp.Add(new Employees() { EmpId = 1, DeptId = 1, Salary = 20000 });

    var highest = from e in emp
    group e by e.DeptId into dptgrp
    let topsal = dptgrp.Max(x => x.salary)
    select new
    {
    Dept = dptgrp.Key,
    TopSal = dptgrp.First(y => y.Salary == topsal).EmpId,
    MaximumSalary = topsal
    };

    Here's a quick description. We first get the maximum salary in a department using

    let topsal = dptgrp.Max(x => x.salary)

    we then use the ‘topsal’ variable to compare it against the salary of an Employee in that department and then select the Empid

    TopSal = dptgrp.First(y => y.Salary == topsal).EmpId

    That's it and you will get the Employee with the highest salary in each department. To print the results, just use a loop and print the values - foreach(var a in highest){ }.

    September 6, 2010

    Auto Submit a Form using jQuery on DropDown List Item Change

    1 comments


    In this short example, let us quickly see how to submit a form automatically, when the user selects a new item from the HTML Select/DropDown List

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <
    head>
    <
    title>Submit Form w/jQuery-DevCurry.com</title>
    <
    script type="text/javascript"
    src="http://code.jquery.com/jquery-latest.js" >
    </
    script>
    <
    script type="text/javascript">
    $(function () {
    $("#sel").live("change keyup", function () {
    $("#form1").submit();
    });
    });
    </script>
    </
    head>
    <
    body>
    <
    form id="form1" action="somepage.php" method="get">
    <
    select id="sel">
    <
    option value="0">Choose a Value</option>
    <
    option value="1">HTML 5</option>
    <
    option value="2">jQuery 4</option>
    <
    option value="3">Ruby 3</option>
    </
    select>
    </
    form>
    </
    body>
    </
    html>

    In this example, both the change and keyup event of the DropDownList is captured using live(). According to the W3C specifications, the change event occurs when a control loses the input focus and its value has been modified since gaining focus. However IE triggers the ‘change’ event as soon as the option is selected, whereas Mozilla, Chrome and Safari do not. This behavior of triggering the change event by IE on keyboard scrolling is not according to the W3C specs. This is the reason that we use both the change and keyup event to capture selection, when the user uses the keyboard to scroll through the dropdownlist items.

    See a Live Demo

    September 5, 2010

    Windows Azure Software Development Kit (September Refresh)

    1 comments


    Microsoft recently released a September Refresh of the Windows Azure Software Development Kit. The SDK still remains the same as the one released in June/July, but with a few bug fixes and some additions, including the following:

    • Support for .Net 4 based services
    • Support for IntelliTrace to debug Windows Azure services
    • [Microsoft.WindowsAzure.StorageClient.dll] Application crashes with unhandled NullReferenceException that is raised on a callback thread.
    • [Microsoft.WindowsAzure.StorageClient.dll] MD5 Header is not passed to the Azure Blob Service in block blob uploads

    Download the September Refresh of the Windows Azure SDK.

    The Windows Azure SDK provides developers with the APIs, tools, documentation, and samples needed to develop Internet-scale applications that run on Windows Azure.

    September 4, 2010

    var vs dynamic keyword in C# 4.0

    11 comments


    To put it as simple as possible, there is a simple difference between the C# ‘var’ and ‘dynamic’ keyword. When using the ‘var’ keyword, the type is decided by the compiler at compile time, whereas when using the ‘dynamic’ keyword, the type is decided by the runtime.

    If you have been doing C# programming lately, you are already aware of the ‘var’ keyword, a strongly implicitly typed local variable for which the compiler is able to determine the type from the initialization expression - very useful when doing LINQ programming.

    The ‘dynamic’ keyword was introduced in .NET 4.0 framework which also introduced the Dynamic Language Runtime (DLR) to accommodate dynamic languages like IronRuby and IronPython [are they dead?]. C# 4.0 provides access to this DLR using the new ‘dynamic’ keyword. C# is a statically typed language and the ‘dynamic' type automatically tells the compiler that it is a dynamic invocation, so ignore the compile time checking for this type. This also means that any invalid operations will only be detected at runtime.

    Let’s see an example. Consider this piece of code:

    var emp = new Employee();
    emp.TakeBreak();


    dynamic emp = new Employee();
    emp.TakeBreak();

    In the first case, i.e. when you are using the ‘var’ keyword, the type is statically inferred. So the line of code evaluates as

    Employee emp = new Employee()


    The compiler will check to see if a TakeBreak() method exists, if not, fail the compilation.

    However that’s not the case when using the ‘dynamic’ type. Using the ‘dynamic’ type does not make it type-safe, hence the compiler is bypassed and the compiler does not check if the TakeBreak() method exists.

    No type-safety? Why the hell do I need the ‘dynamic’ keyword for?

    Well you need it because it is very useful in certain areas like interoperability. To start with an obvious one, it is very useful in dynamic languages that require runtime binding. Also, if you have an object declared as dynamic, then it’s no more your concern to handle how this object obtains it’s value. It’s value can be taken from a DOM object, or from a dynamic language like IronRuby, Reflection, Service or a COM API etc. The runtime takes care of the operations on this object.

    The ‘dynamic’ type is also extremely useful when you are interoperating with Office Automation API’s. This saves you from casting everything from the object.

    If you are interested, I will write a couple of more articles on the new ‘dynamic’ type and how you can use it to interoperate with the new Office Automation API’s. Let me know via the comments section if you care to see an example!

    September 3, 2010

    MultiDimensional Array in JavaScript

    2 comments


    Although JavaScript does not provide inbuilt support for MultiDimensional Arrays, however you can create a multidimensional array by creating a new array as an element of an existing array. In this example, we will see how to create a 3x3 matrix in JavaScript

    <script type="text/javascript">

    // declare array of multi dimensions
    var arrOfArr = new Array(3);
    // or declare as [[],[],[]] as suggested by Elijah

    // allocate storage
    for (var x = 0; x < arrOfArr.length; x++) {
    arrOfArr[x] = new Array(3);
    }

    // Populate the array
    // first array
    arrOfArr[0][0] = "00";
    arrOfArr[0][1] = "01";
    arrOfArr[0][2] = "02";

    // second array
    arrOfArr[1][0] = "10";
    arrOfArr[1][1] = "11";
    arrOfArr[1][2] = "12";

    // third array
    arrOfArr[2][0] = "20";
    arrOfArr[2][1] = "21";
    arrOfArr[2][2] = "22";

    alert(arrOfArr);
    </script>



    Although here arrOfArr seems to be a one-dimensional array, each elements of the array is initialized with another 1-D array, thus making it an array of array i.e. 2-D array.

    Similarly for a three-dimensional array, you would declare the array using

    arrOfArr[x][y] = new Array();

    and then use it using the following code:

    arrOfArr[0][0][3] = "some value";

    and so on.

    September 2, 2010

    Windows Phone 7 RTM

    1 comments


    Yesterday, September 1, Microsoft announced the Release to manufacturing (RTM) of Windows Phone 7! To hardware manufacturers and other service partners, this means they can start finalizing the drivers and other services oriented towards Windows Phone 7.

    For mobile enthusiasts like me, there is no official hardware release date yet, but rumors are it could be somewhere in October. For Windows Phone 7 Developers, check out the Windows Phone 7 resources for developers.

    Terry Myerson, Microsoft's corporate vice president of Windows Phone Engineering in his blog quoted:

    Windows Phone 7 is the most thoroughly tested mobile platform Microsoft has ever released. We had nearly ten thousand devices running automated tests daily, over a half million hours of active self-hosting use, over three and a half million hours of stress test passes, and eight and a half million hours of fully automated test passes. We’ve had thousands of independent software vendors and early adopters testing our software and giving us great feedback. We are ready.

    After the recent debacle of the short-lived Kin cell phone, Windows Phone 7 is Microsoft’s answer to its competitors on the mobile space and I hope Microsoft can provide a great mobile OS to users!

     

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