Free .NET Profilers and Some Paid Ones Too

Profiling is an important part of your software development process and allows you to determine improvements in your applications. In simple words, it is tuning your application to increase its performance. Here are some free and paid .NET profilers to do the job for you

Free

EQATEC v3.0 – An easy to use code profiler to spot your app's slow code. Profiles only methods as of this writing. You can use it freely for non-commercial use. Check the pricing page for the free license

CLR Profiler for .NET Framework – Free memory allocation profiler which works for .NET 2.0 and 3.5 as well

slimTune - Free profiler and performance analysis/tuning tool for .NET based applications

Commercial

Visual Studio Team System Profiler – Ships with Visual Studio Team System (Developer and Suite) for finding performance issues in your native, managed or ASP.NET applications

ANTS Profiler v5.1 – Highly recommended profiler to identify performance bottlenecks and optimize performance

dotTrace 3.1 – Performance and memory profiler for .NET

MemProfiler 3.5 - powerful tool for finding memory leaks and optimizing the memory usage in programs written in C#, VB.NET or any other .NET Language

AQTime 6 - performance profiling and memory and resource debugging toolset for .NET applications

Backup Gadgets in Vista

There are some useful gadgets provided in the Windows Vista Sidebar gadgets. I find the Vista Notes Gadget useful to take down small notes. I recently had to move my data to a new machine and wanted to backup these gadgets. There are some tools that help you take a backup, however if you want to take a backup without using any tools, follow these steps:

1. Browse to C:\Users\<yourname>\AppData\Local\Microsoft\Windows Sidebar

2. You will find a file called Settings.ini. This file contains all the data and settings of your gadgets. Copy this file and save it in your backup drive.

3. In the new machine, replace the Settings.ini with the one you have in your backup drive

Voila!

Disable Right Click Easily using jQuery

I’ve seen allot of posts on forums on how to disable the right click event in JavaScript. Well the solution is pretty straight forward if you use jQuery! The trick is to bind to the contextmenu event. The code below is an example of how to do this.

<html xmlns="http://www.w3.org/1999/xhtml" >
<
head>
<
title>jQuery disable right click easily</title>
<
script language="javascript" type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</
script>
<
script type="text/javascript" language="javascript">
$(function() {
$(this).bind("contextmenu", function(e) {
e.preventDefault();
});
});
</script>
</
head>
<
body>
Sed lacus. Donec lectus. Nullam pretium nibh ut turpis.
Nam bibendum. In nulla tortor, elementum vel, tempor at,
varius non, purus. Mauris vitae nisl nec consectetuer.
Donec ipsum. Proin imperdiet est. Phasellus dapibus semper
urna. Pellentesque ornare, orci in consectetuer hendrerit,
urna elit eleifend nunc, ut consectetuer nisl felis ac diam.
Etiam non felis. Donec ut ante. In id eros.
</body>
</
html>



See a Live Demo

Website accessibility using NVDA

Website accessibility is a serious topic for all web developers these days, and if it isn’t, it should be. Making a website that is accessible is not that hard, but it does require you to think from a UI point of view instead of a pure coding thought process. One tool that is freely available for you to download is NonVisual Desktop Access (NVDA). The website describes it as this:

“Providing feedback via synthetic speech and Braille, it enables blind or vision impaired people to access computers running Windows for no more cost than a sighted person”

This tool can help you diagnose accessibility issues your website may have for blind or vision impaired users. It can help you diagnose input fields that can’t be read, missing alternate text for images and a bunch of other things. You can download this great piece of free software from here.

List the First Monday of every month using C# and VB.NET

Here’s some code for listing down the first Monday of every month in an year using C# and VB.NET. The Monday’s listed in this example are for the year 2010

C#

public static void Main(string[] args)
{
for (int mth = 1; mth <= 12; mth++)
{
DateTime dt = new DateTime(2010, mth, 1);
while (dt.DayOfWeek != DayOfWeek.Monday)
{
dt = dt.AddDays(1);
}
Console.WriteLine(dt.ToLongDateString());
}
Console.ReadLine();
}

VB.NET

Public Shared Sub Main(ByVal args() As String)
For mth As Integer = 1 To 12
Dim dt As New DateTime(2010, mth, 1)
Do While dt.DayOfWeek <> DayOfWeek.Monday
dt = dt.AddDays(1)
Loop
Console.WriteLine(dt.ToLongDateString())
Next mth
Console.ReadLine()
End Sub

OUTPUT

image

Multi-Column ComboBox in WPF

WPF XAML has huge capabilities for effective UX development. The following code shows how to display multi-column data values for ComboBox in WPF

C#

using System.Windows;
using System.Collections.ObjectModel;

namespace WPF_MultiColumnCombobox
{
/// <summary>
///
Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
ObservableCollection<Empl> _emp = new ObservableCollection<Empl>();

public Window1()
{
InitializeComponent();
}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
_emp.Add(new Empl() {EmpNo = 101, EmpName = "Mahesh", DeptName = "IT" });
_emp.Add(new Empl() {EmpNo = 102, EmpName = "Ajay", DeptName = "IT" });
_emp.Add(new Empl() {EmpNo = 103, EmpName = "Rahul", DeptName = "IT" });
_emp.Add(new Empl() {EmpNo = 104, EmpName = "Pradnya", DeptName = "HR" });
_emp.Add(new Empl() {EmpNo = 105,EmpName = "Abhijeet",DeptName = "ITSF" });
_emp.Add(new Empl() {EmpNo = 106, EmpName = "Keshav", DeptName = "MKTG" });
_emp.Add(new Empl() {EmpNo = 107,EmpName = "Prasanna",DeptName = "MKTG" });
_emp.Add(new Empl() {EmpNo = 108, EmpName = "Shailesh", DeptName = "BH" });
_emp.Add(new Empl() {EmpNo = 109,EmpName = "Sidhhart",DeptName = "ITSF" });
_emp.Add(new Empl() {EmpNo = 1010, EmpName = "Kaipl", DeptName = "AI" });

this.DataContext = _emp;

}
}

public class Empl
{
public int EmpNo { get; set; }
public string EmpName { get; set; }
public string DeptName { get; set; }
}
}

XAML Code

<Window x:Class="WPF_MultiColumnCombobox.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="560" Loaded="Window_Loaded" >
<
Window.Resources>
<
Style x:Key="txtStyle" TargetType="{x:Type TextBlock}">
<
Setter Property="TextAlignment" Value="Center"></Setter>
</
Style>

<
DataTemplate x:Key="EmpKey">
<
Grid Height="50" Width="160" ShowGridLines="True">
<
Grid.ColumnDefinitions>
<
ColumnDefinition Width="40"></ColumnDefinition>
<
ColumnDefinition Width="60"></ColumnDefinition>
<
ColumnDefinition Width="50"></ColumnDefinition>
</
Grid.ColumnDefinitions>

<
TextBlock Grid.Column="0" Text="{Binding EmpNo}"
Style="{StaticResource txtStyle}"></TextBlock>
<
TextBlock Grid.Column="1" Text="{Binding EmpName}"
Style="{StaticResource txtStyle}"></TextBlock>
<
TextBlock Grid.Column="2" Text="{Binding DeptName}"
Style="{StaticResource txtStyle}"></TextBlock>
</
Grid>
</
DataTemplate>

<
Style TargetType="{x:Type ComboBoxItem}">
<
Style.Triggers>
<
DataTrigger Binding="{Binding Path=DeptName}" Value="IT">
<
Setter Property="Background" Value="White"></Setter>
</
DataTrigger>
<
DataTrigger Binding="{Binding Path=DeptName}" Value="HR">
<
Setter Property="Background" Value="Blue"></Setter>
</
DataTrigger>
<
DataTrigger Binding="{Binding Path=DeptName}" Value="ITSF">
<
Setter Property="Background" Value="Gray"></Setter>
</
DataTrigger>
<
DataTrigger Binding="{Binding Path=DeptName}" Value="BH">
<
Setter Property="Background" Value="DarkGray"></Setter>
</
DataTrigger>
<
DataTrigger Binding="{Binding Path=DeptName}" Value="AI">
<
Setter Property="Background" Value="Blue"></Setter>
</
DataTrigger>
<
DataTrigger Binding="{Binding Path=DeptName}" Value="MKTG">
<
Setter Property="Background" Value="DarkBlue"></Setter>
</
DataTrigger>
</
Style.Triggers>
</
Style>
</
Window.Resources>

<
Grid>
<
ComboBox Height="38" Margin="0,27,0,0"
Name="comboBox1"
VerticalAlignment="Top" ItemsSource="{Binding}"
ItemTemplate="{StaticResource EmpKey}"
IsSynchronizedWithCurrentItem="True"
HorizontalAlignment="Left" Width="200">
</
ComboBox>
</
Grid>
</
Window>



The above .Xaml defines DataTemplate which represents the way data will be displayed. We also have the data styles defined based upon the values that will be displayed in the ComboBox. For eg: When the value of the DeptName is “HR”, the color of the row is Blue and so on.

Here’s the output:

image

Clicking on the ComboBox, you get an output similar to the following:

image

Call Custom functions on Tab KeyPress in TextBoxes using jQuery

I was recently asked how to cancel Tab Key on a TextBox and instead call a custom function using jQuery. Here’s the code for it:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Call Custom functions on Tab KeyPress in TextBoxes</title>
<
script src="http://code.jquery.com/jquery-latest.js"
type="text/javascript"></script>
<
script type="text/javascript">
$(function() {
$('input.tabcancel').bind('keydown', function(e) {
var keyCode = e.keyCode e.which;
if (keyCode == 9) {
e.preventDefault();
alertMe();
}
});
});

function alertMe() {
var $par = $("#para");
$par.html('perform some action here');
setTimeout(function() {
$par.empty();
}, 1000);

}
</script>
</
head>
<
body>
<
input type="text" class="tabcancel" /><br />
<
input type="text" class="tabcancel" /><br />
<
input type="text" /><br />
<
input type="text" class="tabcancel" /><br />
<
p id="para"/>
</
body>
</
html>



The code shown above handles the keydown event on all textboxes with the class ‘tabcancel’. The keyCode == 9 determines the tab key and we cancel the tab using e.preventDefault() and call a custom function alertMe(). The setTimeout() empties the contents of the para after 1 second.

See a Live Demo

IIS SEO Toolkit 1.0 Released

The IIS Team shipped the IIS Search Engine Optimization (SEO) Toolkit 1.0 Final last week. This free toolkit is an extension to IIS7 that helps Web developers, hosting providers, and server administrators by recommending how to make their site and the content more search engine-friendly. With SEO being one of the most sought after ingredient in any online web entity, this free tool comes as a great resource for your SEO activities.

Here are some important links:

Download Web Platform Installer or directly download the x86 / x64 versions

Quick walkthrough using the Quickstart Guide

Ask your questions using the IIS.NET SEO Toolkit Forum

Search Engine Optimization Toolkit Video and quick Overview

Tracking Microsoft Product Support LifeCycle

Microsoft has a huge range of products offerings and like any other product, these products too have a support lifecycle. I come across a lot of people who do not know where to look out for information related to the support lifecycle of a product. This information can be extremely useful while recommending products and their versions to clients.

Here are some links that will help you to look up the support lifecycle information for each product

Microsoft Support Lifecycle HomePage

Select a Product for Lifecycle Information

Support Lifecycle FAQs

Determine all Types that Implement an Interface

I recently saw an interesting discussion on a forum. The discussion was about finding all the types that implement a particular interface. Here’s a code that lists all the types implementing a particular interface:

C#

using System.Linq;
public static void Main(string[] args)
{
var t = typeof(IYourInterfaceName);
var assemblyTypes = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(typ => typ.GetTypes())
.Where(x => t.IsAssignableFrom(x));
foreach (var v in assemblyTypes)
{
Console.WriteLine(v.FullName);
}
Console.ReadLine();
}

VB.NET

Public Shared Sub Main(ByVal args() As String)
Dim t = GetType(IYourInterfaceName)
Dim assemblyTypes = AppDomain.CurrentDomain.GetAssemblies() _
.SelectMany(Function(typ) typ.GetTypes()) _
.Where(Function(x) t.IsAssignableFrom(x))
For Each v In assemblyTypes
Console.WriteLine(v.FullName)
Next v
Console.ReadLine()
End Sub

List all the TimeZones available on your machine using C# or VB.NET

To list the different TimeZones on your machine, use the TimeZoneInfo class. Here’s a sample:

C#

static class Program
{
public static void Main(string[] args)
{
var tzone = TimeZoneInfo.GetSystemTimeZones();

foreach (TimeZoneInfo tzi in tzone)
{
Console.WriteLine("{0}", tzi.DisplayName);
}
Console.ReadLine();
}

}

VB.NET

Class Program
Private Sub New()
End Sub
Public Shared Sub
Main(ByVal args() As String)
Dim tzone = TimeZoneInfo.GetSystemTimeZones()

For Each tzi As TimeZoneInfo In tzone
Console.WriteLine("{0}", tzi.DisplayName)
Next tzi
Console.ReadLine()
End Sub

End Class

OUTPUT

image

Silverlight 4 Beta Announced

Scott Guthrie just announced the release of Silverlight 4 Beta overnight at Microsoft Professional Developer Conference (PDC09)! What does this mean? It means if you’re working with Silverlight you have tones of new and cool features to create amazing applications. The beta release is a developer release, so there’s no end-user runtime is available for this release, nor is a go-live license for customers wishing to put their applications into production.

There are plenty of new controls and features added in this release. Here are some important ones that caught my attention:

· Printing API

· Right-click event handling

· Mouse wheel support

· Webcam and microphone access

· Rich TextArea Control (supports hyperlinks, images)

· COM interop

· Clipboard API

· Improved DataBinding

· CLR 4.0 Compatibility

· UDPListener and Multi-cast support

· Out Of Browser improvements

· Google Chrome browser support

· Managed Extensibility Framework (MEF)

· Local file access

This is only a small subset of the new features. For a comprehensive list of the new features, Tim Heuer has a great post Silverlight 4 Beta – A guide to the new features

Before getting started you must install the following software:

· Visual Studio 2010 Beta 2 or Visual Web Developer Express 2010 Beta 2

· Silverlight 4 Beta Tools for Visual Studio 2010

Test ‘standalone’ downloads (not needed if the tools above have been installed)

· Silverlight Runtime (Windows)

· Silverlight Runtime (Mac)

· Silverlight 4 SDK

Other tools that will enable you to create cool applications are:

· Expression Blend for .NET 4 Preview

· Silverlight Media Framework

· WCF RIA Services

Here are some Learning Resources

· What’s New in Silverlight 4?

· Microsoft Silverlight 4 Beta Offline Documentation (CHM)

· Microsoft Silverlight 4 Beta Online Documentation

· Getting Started with Silverlight 4

If you’ve read everything else and want a video on the new features, you can go here to check it out. Exciting times ahead!!

ASP.NET MVC 2 Beta Announced in PDC 09

The ASP.NET MVC team does know how to keep developers engaged! Yesterday in PDC 09, Bob announced ASP.NET MVC 2 Beta.

Some highlights of the new features in ASP.NET MVC 2 Beta as given on Phil Haack’s blog are:

  • RenderAction (and Action)
  • AsyncController
  • Expression Based Helpers (TextBoxFor, TextAreaFor, etc.)
  • Client Validation Improvements (validation summary)
  • Add Area Dialog
  • Empty Project Template
  • Here are some important links related to the release:

    Download ASP.NET MVC 2 Beta

    ASP.NET MVC 2 Beta Release Notes

    ASP.NET MVC 2 Beta Released

    When to use the jQuery live() and bind() methods

    I get asked occasionally when to use the bind() and live() jQuery event methods. bind() will bind a handler to one or more events for each matched element, at the time the call is made; whereas live() uses event delegation to bind a handler to an event for all current and ‘future’ matched elements. If you have controls that aren’t rendered dynamically, use bind(). If you have controls that are rendered dynamically, use live().

    Here are two examples.

    Bind

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <
    head>
    <
    title></title>
    <
    script language="javascript" type="text/javascript"
    src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
    </
    script>
    <
    script language="javascript" type="text/javascript">
    $(function() {
    $("input[type=button]").bind("click", function() {
    $(this).after("<br /><input type=\"button\" value=\"Child\" />");
    });
    });
    </script>
    </
    head>
    <
    body>
    <
    form>
    <
    input id="btnCreate" type="button" value="Create Children" />
    </
    form>
    </
    body>
    </
    html>

    In the code above, when the user clicks on btnCreate, a new <button> will be created beneath it. Clicking on any of the newly created buttons will not replicate the functionality. This is where you need to implement the live() method.

    Live

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <
    head>
    <
    title></title>
    <
    script language="javascript" type="text/javascript"
    src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
    </
    script>
    <
    script language="javascript" type="text/javascript">
    $(function() {
    $("input[type=button]").live("click", function() {
    $(this).after("<br /><input type=\"button\" value=\"Child\" />");
    });
    });
    </script>
    </
    head>
    <
    body>
    <
    form>
    <
    input id="btnCreate" type="button" value="Create Children" />
    </
    form>
    </
    body>
    </
    html>

    In the code above, the user can now click on any of the buttons, and a new button will be created beneath it. The only difference is I’m using the live() method.

    While choosing between bind() and live(), also note that we can bind only a single event in each call to the live() method whereas bind() can accept multiple events. Also blur, focus, mouseenter, mouseleave, change, submit are not supported with the live() method. Some more differences between live() and bind() have been listed over here

    Zip files and folders in .NET

    A lot of solutions exists that show how to zip files in .NET, for example some of them using SharpZipLib, GZipStream, Windows Shell API or the ZipLibrary class. However one lesser known solution which I have found to be very useful is the DotNetZip library

    As given on the site - “DotNetZip is an easy-to-use FREE class library and toolset for manipulating zip files or folders. Zip and Unzip is easy: with DotNetZip, .NET applications written in VB, C# - any .NET language - can easily create, read, extract, or update zip files. It works on Mono or MS .NET”

    You can download DotNetZip Library over here.

    Here’s a sample that shows how to use this library to zip all files in a folder

    C#

    using System;
    using Ionic.Zip;

    namespace ZipSample
    {
    class Program
    {
    static void Main(string[] args)
    {
    try
    {
    using (ZipFile zip = new ZipFile())
    {
    zip.AddDirectory(@"D:\Ajax");
    zip.Save(@"D:\Ajax\Ajax.zip");
    Console.WriteLine("Files zipped");
    }
    }
    catch (ZipException ex)
    {
    Console.WriteLine(ex.Message);
    }
    Console.ReadLine();
    }
    }
    }

    VB.NET

    Imports System
    Imports Ionic.Zip

    Namespace ZipSample
    Class Program
    Shared Sub Main(ByVal args() As String)
    Try
    Using
    zip As New ZipFile()
    zip.AddDirectory("D:\Ajax")
    zip.Save("D:\Ajax\Ajax.zip")
    Console.WriteLine("Files zipped")
    End Using
    Catch
    ex As ZipException
    Console.WriteLine(ex.Message)
    End Try
    Console.ReadLine()
    End Sub
    End Class
    End Namespace
    Depending on the size of the files in a folder, it may take some time for the zip operation to complete.

    Opening Multiple Browsers at Once

    Yesterday I had posted about Opening Multiple Files using a Batch File. A user mailed me asking if it was possible to open multiple browsers at once using the same technique. The answer is Yes and here’s how to do so:

    Open Notepad and copy and paste the following lines below:

    @echo off
    Start "IE" "C:\Program Files\Internet Explorer\iexplore.exe"
    Start “Firefox” "C:\Program Files\Mozilla Firefox\firefox.exe"
    Start "Chrome" "C:\Users\Suprotim\AppData\Local\Google\Chrome\Application\chrome.exe"
    Start "Safari" "C:\Program Files\Safari\safari.exe"

    Save the notepad file with the .bat extension. Now to open all these browsers at once, just execute the .bat file by double clicking it

    Note: To know the location of the browser .exe on my machine, I used a simple technique of checking the properties of the browser shortcut and copying the path from the ‘Target’ field. For example: Here’s how the path of the Internet Explorer (IE) .exe can be obtained

    image

    Opening Multiple Files using a Batch File

    If you have been looking out for a simple way to open multiple files, then you can create a batch file and specify the files to open. This example assumes that there are 2 text and 1 pdf file in a folder. Follow these steps to open all of them at once:

    Open Notepad and copy and paste the lines below:

    @echo off
    start Copy1.txt
    start Copy2.txt
    start Copy3.pdf

    Save the notepad file with the .bat extension in the same folder where the .txt and .pdf files are kept. Now to open all these files at once, just execute the .bat file by double clicking it

    ASP.NET 4.0 “Quick Hit” Videos

    Joe Stagner ‘aka’ the Misfit Geek has been posting some cool short ASP.NET 4.0 videos that he calls the “Quick Hit” Videos. Check them out to get started with ASP.NET 4.0 new features:

    You can find an updated list of the videos over here http://www.asp.net/learn/aspnet-4-quick-hit-videos/.

    You can also check Joe’s blog for updates over here http://misfitgeek.com/blog/aspnet/asp-net-4-vs-2010-ldquo-quick-hit-rdquo-videos/

    Note: As of this writing, ASP.NET 4.0 is still in beta

    Power Commands in Visual Studio

    A great addition to Visual Studio is an application called PowerCommands which has been developed by Microsoft. PowerCommands is a set of useful extensions for the Visual Studio 2008 adding additional functionality to various areas of the IDE. Some of the features available in Visual Studio are:

    · Open command prompt

    · Unload project

    · Edit project file

    · Copy & paste class

    · Show all files

    clip_image002

    If you’re using Visual Studio 2010, Microsoft has created a new version of PowerCommands. It can be downloaded from here. This is a great addition to Visual Studio.

    Clear Items of a DropDownList using jQuery

    A user on a forum recently asked a question on how you clear the items in a drop down list using jQuery.

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

    The answer to the problem is in the jQuery Selector. The person was using the following jQuery to try and clear the items, but it wasn’t working:

    $("select[id$=ddlPeople]").remove();

    The items weren’t being removed because the jQuery Selector is wrong. What you need to do is tell the Selector to remove all the children (<option> tags). Like this:

    $("select[id$=ddlPeople] > option").remove();

    “> option” matches all child elements. Because each item in the drop down list is rendered as an <option> tag, you need to clear the child <option> tags in order to clear the items in a drop down list.

    Free Training Kits for Developers and IT Professionals (Microsoft Technologies)

    Trainings kits contain presentations, hands-on-labs, demos and other training material designed to help you learn how to use a technology. Here are some Free Training Kits released by Microsoft which cover the latest technologies in the market:

    Visual Studio 2010 and .NET Framework 4 Training Kit - October Preview - The Visual Studio 2010 and .NET Framework 4 Training Kit includes presentations, hands-on labs, and demos. This content is designed to help you learn how to utilize the Visual Studio 2010 features and a variety of framework technologies

    WF 4 Migration Guidance - These documents help .NET developers better understand and evaluate Windows Workflow Foundation (WF) in the Microsoft .NET Framework 4, and the impact of WF 4 on existing WF workflows and code

    SQL Server 2008 Developer Training Kit - The SQL Server 2008 Developer Training Kit will help you understand how to build web applications which deeply exploit the rich data types, programming models and new development paradigms in SQL Server 2008

    ASP.NET MVC Training Kit - The ASP.NET MVC Training Kit includes presentations, hands-on labs, demos, and event materials. This content is designed to help you learn how to utilize ASP.NET MVC.

    Windows Azure Platform Training Kit - October Update - The Azure Services Training Kit includes a comprehensive set of technical content including hands-on labs, presentations, and demos that are designed to help you learn how to use the Windows Azure platform including: Windows Azure, SQL Azure and .NET Services. The October release includes new videos and labs in addition to VB code snippets and updated content for SQL Azure October CTP.

    Windows 7 Training Kit For Developers - The Windows 7 Training Kit for Developers includes presentations, hands-on labs, and demos designed to help you learn how to build applications that are compatible with and shine on Windows 7

    Windows Server 2008 R2 Developer Training Kit - July 2009 - A collection of presentations, demos, and hands-on-labs for Windows Server solution developers

    Prevent an ASP.NET Application Restart when a Configuration Setting is changed

    A change to configuration settings in your web.config leads to an application restart, affecting the Session and Cache objects. How do you prevent it? The answer is by placing configuration information in an external file. To do so, use the little known attribute called ‘configSource’ as shown below:

    <connectionStrings configSource="Myconn.config"/>

    In the Myconn.config file, declare the connectionStrings as follows:

    <connectionStrings>
    <
    add name="nwstring" connectionString="Data Source=(local);Initial
    Catalog=Northwind;Integrated Security=true;
    "
    providerName="System.Data.SqlClient" />
    </
    connectionStrings>

    Now you can go ahead and change the connectionString even in a live application without worrying about an application restart!

    Make sure you also read about the RestartOnExternalChanges property.

    Disabling Debug Mode and Tracing in your ASP.NET applications

    To improve the performance of our ASP.NET application, a recommended practice is to make sure that the application is not deployed with Debug=True attribute.

    One of my clients had a production server which hosted multiple websites. Although some of the applications were deployed keeping debug=false, however the rest of the applications had the attribute set to true. They now wanted to control the setting from the machine.config file which would apply to all the applications running on that server.

    Here’s a technique that most of the users to not know about. In your machine.config, locate the <system.web> section and add the following entry

    <deployment retail=“true”/>

    That’s it. Now this setting will automatically disable the debug mode and tracing on your applications.

    8 Useful FireFox Addons For Web Designers

    Here are some FireFox Add-ons I have found extremely useful while designing web applications. The description of each add-on has been taken from the the official page.

    ColorZilla - With ColorZilla you can get a color reading from any point in your browser, quickly adjust this color and paste it into another program. You can Zoom the page you are viewing and measure distances between any two points on the page. The built-in palette browser allows choosing colors from pre-defined color sets and saving the most used colors in custom palettes. DOM spying features allow getting various information about DOM elements quickly and easily. A very useful FireFox extension indeed!

    Pencil – A very handy add-on to create diagrams and GUI prototyping

    ColorSuckr – Extracts colors from images and builds color schemes

    Yet Another Window Resizer - Resize browser window to default screen resolutions

    FireShot - A Firefox extension that creates screenshots of web pages (entirely or just visible part). You can also insert text annotations and graphical annotations to the screenshot.

    MeasureIt - Draw out a ruler to get the pixel width and height of any elements on a webpage

    Web Developer - Adds a menu and a toolbar with various web developer tools

    and the last one which is a must have for every web developer/designer

    FireBug - Firebug integrates with Firefox to put a wealth of web development tools at your fingertips while you browse. You can edit, debug, and monitor CSS, HTML, and JavaScript live in any web page.

    Using IsDebuggingEnabled in ASP.NET

    A cool feature in the .NET library that I rarely see used is the IsDebuggingEnabled property. This returns a value indicating whether the current HTTP request is in debug mode. I’ve found this useful in the past where I wanted something displayed on the screen to distinguish if the website I’m working on is a debug build or not. To change the compilation of a website, you update the compilation element in the web.config file:

    Debugging is off: <compilation debug="false">
    Debugging is on: <compilationdebug="true">

    The following code demonstrates how to use this property. When page is loaded and debugging is enabled, a JavaScript alert will be displayed:

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <
    head id="Head2" runat="server">
    <
    title></title>
    <
    script language="javascript" type="text/javascript"
    src="http://code.jquery.com/jquery-latest.js"></script>
    <
    script language="javascript" type="text/javascript">
    $(document).ready(function() {
    if ('<%= System.Web.HttpContext.Current.IsDebuggingEnabled %>' == 'True') {
    alert("Debugging enabled!");
    }
    });
    </script>
    </
    head>
    <
    body>
    <
    form id="form1" runat="server">
    <
    div>

    </
    div>
    </
    form>
    </
    body>
    </
    html>

    I find this piece of code very useful if I want to see results that I would not want to be displayed, in a production environment.

    Find the Last Day of the Previous Month using C# and VB.NET

    A couple of days ago, I had written a post to Find the First and Last Day of the Current Quarter using C#/VB.NET. A user commented asking how to find the last day of the previous month. Here’s how it can be done:

    C#

    DateTime dt = DateTime.Now;
    DateTime lstDay = new DateTime(dt.Year, dt.Month, 1);
    lstDay = lstDay.AddDays(-1);
    Console.WriteLine("Month: {0}, LastDate: {1}",lstDay.Month, lstDay.Day);
    Console.Read();

    VB.NET

    Dim dt As DateTime = DateTime.Now
    Dim lstDay As New DateTime(dt.Year, dt.Month, 1)
    lstDay = lstDay.AddDays(-1)
    Console.WriteLine("Month: {0}, LastDate: {1}",lstDay.Month, lstDay.Day)
    Console.Read()

    Output

    image

    The current month is November, so the last day of the previous month (October) is 31.

    Check if a Float number falls within a range using Extension Methods

    Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. I was having a conversation with a bunch of C# 2.0 developers the other day who were planning to move to C# 3.0 and then 4.0. They had a requirement to check if a number falls within a specific range and wanted to see how this could be done in 3.0. I said use Extension Methods. Here’s some code that checks if a float number falls within a range, using an Extension Method

    C#

    static class Program
    {
    public static void Main(string[] args)
    {
    float number = 23.5f;
    if (number.CheckRange(20.0f, 25.5f))
    {
    Console.WriteLine("In Range");
    }
    else
    {
    Console.WriteLine("Out of Range");
    }
    Console.ReadLine();
    }

    static bool CheckRange(this float num, float min, float max)
    {
    return num > min && num < max;
    }
    }

    VB.NET

    Module Module1
    Public Sub Main(ByVal args() As String)
    Dim number As Single = 23.5F
    If number.CheckRange(20.0F, 25.5F) Then
    Console.WriteLine("In Range")
    Else
    Console.WriteLine("Out of Range")
    End If
    Console.ReadLine()
    End Sub

    <System.Runtime.CompilerServices.Extension()> _
    Private Function CheckRange(ByVal num As Single, _
    ByVal min As Single, _
    ByVal max As Single) As Boolean
    Return
    num > min AndAlso num < max
    End Function
    End Module

    Add a DotNetKicks button to your Webpage

    DotNetKicks is a popular .NET community based news site. A lot of users use the DotNetKicks social bookmarking button which makes it easier for viewers to submit or ‘kick’ a story. If you have been wondering how to add the DotNetKicks button to every post on your website, here’s the code for it.

    <div>
    <script type="text/javascript">
    document.write('<a href="http://www.dotnetkicks.com/submit?url='+document.location.href+'&amp;title='+document.title+'"> <img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url='+document.location.href+'" border="0"></a>');
    </script>
    </div>

    This piece of code determines the URL using ‘document.location.href’ and the Title using ‘document.title’. This information is submitted to the dotnetkicks site when the user click on the link/image. When this code is placed on a page, the output generated is as shown below:

    image

    How to access parts of a URL in ASP.NET

    A user asked me the simplest way to dissect a URL and list down the different parts of it in ASP.NET. I advised him to use the URI class. Here’s an example:

    C#

    Uri someUri = Page.Request.Url;
    string urlstr = string.Format(
    "AbsoluteUri: {0}<br/> Scheme: {1}<br/> Host: {2}<br/> Query: {3} ",
    someUri.AbsoluteUri, someUri.Scheme, someUri.Host, someUri.Query);
    Response.Write(urlstr);

    VB.NET

    Dim someUri As Uri = Page.Request.Url
    Dim urlstr As String = String.Format( _
    "AbsoluteUri: {0}<br/> Scheme: {1}<br/> Host: {2}<br/> Query: {3} ", _
    someUri.AbsoluteUri, someUri.Scheme, someUri.Host, someUri.Query)
    Response.Write(urlstr)

    The output is as shown below:

    image

    7 Free Tools to Minify your Scripts and CSS

    I have been doing a lot of Client-Side development recently and I have found these 7 tools of great help to improve the performance of the website by ‘shrinking’ the size of JavaScript and CSS files, referenced in the site.

    JSMin (JavaScript Minifier) - removes comments and unnecessary whitespace from JavaScript files

    JSO (JavaScript Optimizer) - allows you to manage your JavaScript and CSS resources and to reduce the amount of data transfered between the server and the client.

    Packer – An online JavaScript Compressor

    JSCompress.com – Online tool that uses either JSMin or Packer to compress your files

    CSS Compressor – Online tool that compresses your CSS file

    DigitalOverload JavaScript Minifier – Online tool that minifies your JavaScript files and finally the one I use most frequently:

    YUI Compressor – A JavaScript minifier designed to be 100% safe and yields a higher compression ratio than most other tools.