Find Out the Image Type without Checking its Extension

My colleague called up with a query. His application accepted images to be uploaded to a central server. Later the application processed the images and separated them according to the Image Type. They determined the image type by checking the extension of the image uploaded –- a very common practice of detecting the image type.

The issue here was that some images which were actually gif’s were renamed as jpeg’s and then uploaded, which led to faulty image processing. The requirement was to determine the correct image type in the simplest possible way even if the extension was renamed. Here’s what I suggested:

C#

try
{
Image imgUp = Image.FromFile(Server.MapPath("~/images/abc.jpg"));
if (imgUp.RawFormat.Equals(ImageFormat.Jpeg))
Response.Write("JPEG");
else if (imgUp.RawFormat.Equals(ImageFormat.Gif))
Response.Write("GIF");
}
catch (Exception ex)
{
}

VB.NET

Try
Dim
imgUp As Image = Image.FromFile(Server.MapPath("~/images/abc.jpg"))
If imgUp.RawFormat.Equals(ImageFormat.Jpeg) Then
Response.Write("JPEG")
ElseIf imgUp.RawFormat.Equals(ImageFormat.Gif) Then
Response.Write("GIF")
End If
Catch
ex As Exception
End Try

The Image.RawFormat property is extremely useful in this situation to get the file format of the image.

Note: Alternatively you can also use Magic Numbers

How to calculate the CPU Usage Programmatically using C# or VB.NET

The PerformanceCounter class represents a WindowsNT performance counter component. To read from a performance counter, we first create an instance of the PerformanceCounter class supplying the CategoryName, CounterName, and InstanceName as parameters to the constructor and then call the NextValue() method to take a performance counter reading.

Import the namespaces System.Diagnostics and System.Threading.

C#

static PerformanceCounter cpuUsage;
public static void Main(string[] args)
{
cpuUsage =
new PerformanceCounter("Processor", "% Processor Time", "_Total");

Console.WriteLine(cpuUsage.NextValue() + " %");
Thread.Sleep(1000);
Console.WriteLine(cpuUsage.NextValue() + " %");
Console.Read();
}

VB.NET

Private Shared cpuUsage As PerformanceCounter
Public Shared Sub Main(ByVal args() As String)
cpuUsage = _
New PerformanceCounter("Processor", "% Processor Time", "_Total")

Console.WriteLine(cpuUsage.NextValue() & " %")
Thread.Sleep(1000)
Console.WriteLine(cpuUsage.NextValue() & " %")
Console.Read()
End Sub

Note: Observe that we are calling NextValues() twice and after a delay of 1 second. This is because performance counters need two samples to perform the calculation and the counter value is updated once per second, hence the 1 second delay between the two calls.

The output on running this code is as shown below:

image

Find Out the Users Connected to a Windows Server using C# or VB.NET

I was recently asked this question on the forums – How do I find out and list the users connected to a server? I said use Cassia

A standard way of achieving this requirement is to use P/Invoke to access the Windows Terminal Services API. Cassia is a .NET library that acts as a wrapper on the native Windows Terminal Services API.

Cassia has been tested on Windows Server 2008 R2 Beta, Windows Server 2008, Windows Server 2003, Windows XP, and Windows Server 2000. It should work on Windows Vista as well. I haven’t tried it on Windows 7. If any of you does, kindly drop in a comment and let the users know of your experience.

Check out Cassia!

Inject jQuery into a webpage using a FireFox addon - FireQuery

I found a really cool Firefox addon called FireQuery. This addon enables you to inject jQuery into any web page. This is a nice way to see how any web page behaves with jQuery.

Normally I would write a small article on how to use this technology, but I felt like doing something different so I made a short screencast on FireQuery and how to use it. Hopefully you’ll find it a useful tool as well.

You can watch the screencast here or can see it below:

ASP.NET 4.0 (Beta) Resources

Here are some useful resources to get started with the latest version of ASP.NET 4.0. Currently ASP.NET 4.0 is in Beta 2

ASP.NET 4.0 and Visual Studio 2010 Beta 2 Released

ASP.NET 4 and Visual Studio 2010 Web Development Beta 2 Overview

ASP.NET 4.0 Training Lessons on Channel 9

Exploring ASP.NET 4.0—Web Forms and Beyond

URL Routing with ASP.NET 4 Web Forms (VS 2010 and .NET 4.0 Series)

Auto-Start ASP.NET Applications (VS 2010 and .NET 4.0 Series)

Channel 9 Video Interviews with the ASP.NET 4 Team

ASP.NET 4 Beta 2 forums

5 jQuery Plugins to Manipulate and add effects to Images

Here is a list of 5 plugins you can use to manipulate images on client-side. This section has been taken from my eBook 51 Tips, Tricks and Recipes using jQuery and ASP.NET Controls

ImageOverlay - Allows you to display additional information in a translucent pane above an image that gracefully appears when a user hovers over the image

jCrop - jCrop is the quick and easy way to add image cropping functionality to your web application. It combines the ease-of-use of a typical jQuery plugin with a powerful cross-platform DHTML cropping engine that is faithful to familiar desktop graphics applications.

jLoupe - jLoupe adds a "loupe" or "magnifying glass" effect to images. Applying the plugin is as easy as adding the class "jLoupe" to the images you want to enable the effect on.

Magnify - Magnify allows you to easily create a "magnifier" on your images. You just need to create a small and large image which are proportionally sized, configure your markup accordingly and let Magnify do the rest

Reel - Reel is a jQuery plugin which takes an image tag and makes it a live "projection" of pre-built animation frames sequence. Its aim is to provide a 360° view of something or someplace. Like a turntable or a panorama for instance

14 Expression Web 3 Tips and Articles

If you use Expressions Web 3, check out a link list by Expression Web MVP Minal where she has written some useful Expression Web 3 tips and tricks

14 Microsoft Expression Web 3 Articles and Tips you should read

Here’s an excerpt

Microsoft Expression Web is a ’WYSIWYG’ HTML editor as well as a graphical web design program developed by Microsoft that has today replaced Microsoft FrontPage. Expression Web is a part of the Expression Studio suite. Expression Web provides support for integrating XML, XHTML, XSLT, CSS, ASP.NET and other standard Web technologies into the websites.

I have been using Microsoft Expression Web 2 for quite some time now and I love it! Now with release of Expression Web 3, with features like SuperPreview, Snapshot Panel, new improved toolbars like the Code Toolbar, integration with VSTS, Silverlight support and an enhanced FTP client, you get a better control over your web pages. Believe me, designing has never been so simple and interesting before.

You can also read some additional Tips on Microsoft Expression Web 2 and Tutorials on Microsoft Expression Web 2 written by Minal

Visual Studio 2010 and .NET Framework 4 Beta 2 Released

Microsoft recently announced (21st October) the immediate availability of Microsoft Visual Studio 2010 Beta 2 and Microsoft .NET Framework 4 Beta 2 to general public

Here are some important links related to the release

Visual Studio 2010 Beta 2 including Express downloads

Channel 9 Video: How to Install the Beta

Visual Studio 2010 and .NET Framework 4 Training Kit - October Preview

Featured Overviews and Walkthroughs

Other important information

Silverlight Toolkit October 2009 Released

Microsoft has released a new set of Silverlight components and features in the Silverlight Toolkit (October 2009).

A prominent change i found was the support for Visual Studio 2010 and drag & drop support for some key controls.

Here are some important links related to the download:

Silverlight Toolkit October 2009

Silverlight Toolkit October 2009 change list

Online Silverlight 3 Toolkit samples

Windows 7 Launched!

The much awaited Windows 7 OS was launched today in a keynote by Microsoft’s Chief Executive Steve Ballmer

Here are some useful links:

Read the 32-bit and 64-bit Windows FAQ.

Top 10 reasons to upgrade to Windows 7

Choose the Windows 7 Edition that works best for you.

Daily Offers till October 28th, 2009

Purchase it on Amazon

Microsoft Windows 7 Home Premium Upgrade
Microsoft Windows 7 Professional Upgrade
Microsoft Windows 7 Ultimate Upgrade
Microsoft Windows 7 Home Premium
Microsoft Windows 7 Ultimate
Microsoft Windows 7 Professional

51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls eBook Released!

I am glad to announce the release of my eBook 51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls. In the first book of its kind on using jQuery with ASP.NET Controls, I show you how to use jQuery to solve some common and not-so-common client-side programming challenges while dealing with ASP.NET Controls.

You can download the Table of Contents and 5 Sample Chapters of the eBook before buying.

You can purchase the eBook over here

Last Chance to Pre-Order my EBook – 51 Recipes with jQuery and ASP.NET Controls

If you have not yet pre-ordered my EBook - 51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls, then here’s the last chance to pre-order the EBook at a discounted price. This offer will expire in 13 hours from now!

The EBook will be released tomorrow (October 21st, 2009).

You can download the Table of Contents and 5 Sample Chapters of the upcoming EBook before purchasing.

Pre-Order the EBook here

Ebook

Display Currency Symbols using ISO standards in ASP.NET

I stumbled across an interesting question about localization/globalization recently. The user wanted to print currency symbols using the ISO standards and wanted to find out if there was an easy way to do so using ASP.NET


Yes, there is! Use the RegionInfo.ISOCurrencySymbol Property. Here’s how


C#

string symbol = RegionInfo.CurrentRegion.ISOCurrencySymbol;

Response.Write(symbol);

VB.NET

Dim symbol As String = RegionInfo.CurrentRegion.ISOCurrencySymbol

Response.Write(symbol)

The output on my system is USD, which is according to the ISO 4217 standards

Microsoft Ajax Library Preview 6 and Ajax Minifier

Microsoft recently announced a new update to Microsoft Ajax Library (Preview 6) and introduced the Microsoft Ajax Minifier.

What is the Ajax Library Preview 6?

The Ajax Library is a pure JavaScript library that enables you to build highly interactive Ajax applications. You can use the Microsoft Ajax Library in both ASP.NET Web Forms and ASP.NET MVC applications and this library works with most of the modern browsers

What is Ajax Minifier?

In simple words, this tool improves the performance of your websites by reducing the size of your JavaScript files

Here are some important links to help you out with this new update

Microsoft Ajax Library Preview 6 - Download link

Announcing Microsoft Ajax Library (Preview 6) and the Microsoft Ajax Minifier - ScottGu’s blog

Announcing Microsoft Ajax Library Preview 6 - Channel 9

Entirely unobtrusive and imperative templates with Microsoft Ajax Library Preview 6

Let Me Bing That For You – New Service announcement

Many a times on the forums, I have seen users ask very basic questions that can easily be ‘searched out’. Answerers usually respond to these basic question by guiding the original poster to a search engine and tell them what to search. WAWOT (What a waste of time!)

Here’s how you can now help this OP with some style. Many of you must be familiar with lmgtfy.com or Let me Google that for you

Maarten Balliauw, Juliën Hanssens and Phil Haack got together and created a new website called Let Me Bing That For You

Let Me Bing That For You is a service for our lazy friends who are just too lazy to search out for answers on their own. Here’s how the service works. Assuming the user asked you a query ‘How to lose your Job’. Here’s how you can teach him how to search

- Go to Let Me Bing That For You

- Type in the users query ‘How to lose your Job’ in the search box and click the search button

- The service provides you a link to pass on to that lazy bum

The link guides the user step by step on how to Bing that query. Check the results here :)

http://tinyurl.com/yfd4vbd

Go Search Go!!

Allow Only Alphanumeric Characters in a TextBox using jQuery

In this short post, I will demonstrate how to allow only alphanumeric characters in a TextBox. This article is a sample chapter from my upcoming EBook called 51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls. The chapter content has been modified a little to publish it as a blog post. Also please note that for demonstration purposes, I have included JavaScript and CSS into the same file. Ideally, these resources should be created in separate folders for maintainability.

Requirement:

Users should be allowed to enter only Alphabets and Numbers in a TextBox. Non-alphanumeric characters should be disallowed. You also want to prevent users from copying and pasting non-alphanumeric characters into the TextBox.

Solution:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head id="Head1" runat="server">
<
title>Allow Only Alphanumeric Characters in a TextBox</title>
<
link href="../CSS/Demos.css" rel="stylesheet" type="text/css" />
<
script type='text/javascript'
src='../Scripts/jquery-1.3.2.min.js'>
</
script>

<
script type="text/javascript">
$(function() {
$('input.alpha[$id=tb1]').keyup(function() {
if (this.value.match(/[^a-zA-Z0-9 ]/g)) {
this.value = this.value.replace(/[^a-zA-Z0-9 ]/g, '');
}
});
});
</script>
</
head>
<
body>
<
form id="form1" runat="server">
<
div class="bigDiv">
<
h2>Allow Only Alphanumeric Characters in a TextBox</h2>
<
asp:TextBox ID="tb1" runat="server" class="alpha"
Text="Try entering Non alphanumeric char"
ToolTip="Try entering Non alphanumeric char"/>
<
br /><br />
Tip: Examples of some non-alphanumeric characters <br />
are ~!@~#$%^&* and so on.
</div>
</
form>
</
body>
</
html>

Explanation:

The code shown above matches a regular expression /[^a-zA-Z0-9 ]/g that finds all characters that are not alphabets or numbers. If the user enters a character that is an alphabet or number, the character is replaced with an empty string. Observe the space after ‘9’ to allow whitespaces. Since we are capturing the keyup event, we are also preventing copying and pasting of non-alphanumeric characters. I have observed people using the keypress event to handle this requirement, but remember that in IE, keypress does not behave as expected for non-character keys.

As Yehuda Katz says – “My mantra has always been: keydown/keyup if you want to know the key that was pressed; keypress if you want to know what text was detected

Note: Javascript can be disabled, so always validate the user input on server side

Tip: If you want to accept only numbers, use /[^0-9 ]/g and for accepting only alphabets, use /[^a-zA-Z ]/g

Browsers Supported:

IE 7, IE 8, Firefox 3, Chrome 2, Safari 4

Useful Links:

http://ejohn.org/blog/keypress-in-safari-31/

http://docs.jquery.com/Events/keyup

LIVE DEMO

There are plenty of such similar tips that I will be covering in my upcoming EBook over here 51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls

Find Long Words in a TextArea Using jQuery

A question popped up on the forums today about a user having a multi line text box. That’s okay but what they wanted was to have each word no longer than 12 characters. Here’s how I said to do it using jQuery.

<html xmlns="http://www.w3.org/1999/xhtml" >
<
head id="Head1" runat="server">
<
title>Find Long Words In TextArea</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() {
var txt = $("textarea[id$=TextBox1]");
var result = $(txt).next();
$(txt).blur(function() {
$(result).text("");
var data = $(this).val().split(" ");
for (var i = 0; i < data.length; i++) {
if (data[i].length >= 13) {
$(result).append(data[i] + "<br />");
}
}
});
});
</script>
</
head>
<
body>
<
form id="form1" runat="server">
<
div>
<
asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine">
</
asp:TextBox>
<
div></div>
</
div>
</
form>
</
body>
</
html>

The code above finds the textarea, and anytime the control loses focus, the code enumerates through all the words and prints which words are longer than twelve characters.


clip_image002

13 'Important' Security Bulletins Released By Microsoft

Microsoft yesterday released a huge software patch that addresses and fixes a number of critical vulnerabilities in its programs. This patch comprises of 13 security bulletins which addresses 34 vulnerabilities across its Windows Media Player, Windows OS, Internet Explorer, Silverlight, .NET, Office and other products, including Windows 7

You can obtain more information on these security bulletins over here http://www.microsoft.com/technet/security/bulletin/MS09-oct.mspx

Microsoft is also hosting a Webcast to address customer questions on these bulletins:

Title: Information about Microsoft July Security Bulletins (Level 200)

Date: Wednesday, October 14, 2009, 11:00 A.M. Pacific Time (U.S. and Canada)

URL: http://msevents.microsoft.com/CUI/WebCastEventDetails.aspx?culture=en-US&EventID=1032407488

An Architect’s perspective on Silverlight 3 - WebCast (October 27th)

If you are interested in developing and architecting RIA apps using Silverlight, make sure you do not miss this webcast. Here are some details:

Title: An Architect’s perspective on Silverlight 3

Presenter: Tim Heuer (Program Manager for Microsoft Silverlight)

Abstract: Many .NET developers are becoming more and more interested in the Rich Internet Application development space, and in particular Silverlight. In this session we will step back from a detailed implementation technology and take a higher level look at Silverlight from the architect’s perspective. We will discuss the types of applications where Silverlight makes sense and some scenarios where Silverlight may not be the appropriate technology. We will also delve into some of the architectural decisions that the architect must consider when writing applications for this platform and where some of the tradeoffs may lie.

Event ID: 1032427862

WebCast Date: October 27, 2009 at 11:00am – 12:30pm PST (http://www.timeanddate.com/worldclock/converter.html)

Link to Register: An Architect’s perspective on Silverlight 3

Increase and Decrease Font Size Using jQuery

I was asked very recently on a forum how to increase and decrease the font size of an <a> tag using JavaScript. I said this is how you’d do it using jQuery.

Note: I have used an ASP.NET LinkButton in this example, however if you are using this example on a HTML Page, you can easily replace this control with a Hyperlink.

<html xmlns="http://www.w3.org/1999/xhtml" >
<
head id="Head1" runat="server">
<
title>Increase and Decrease Font Using Jquery and CSS</title>
<
script type="text/javascript" language="javascript"
src="http://code.jquery.com/jquery-latest.js"></script>
<
script type="text/javascript" language="javascript">
$(document).ready(function() {
var lb = $('a[id$=LinkButton1]');
$("input[id$=btnIncrease]").click(function() {
var size = $(lb).css("font-size");
var newSize = parseInt(size.replace(/px/, "")) + 1;
$(lb).css("font-size", newSize + "px");
});
$("input[id$=btnDecrease]").click(function() {
var size = $(lb).css("font-size");
var newSize = parseInt(size.replace(/px/, "")) - 1;
$(lb).css("font-size", newSize + "px");
});
});
</script>
</
head>
<
body>
<
form id="form1" runat="server">
<
asp:LinkButton ID="LinkButton1" runat="server">
Sample Text</asp:LinkButton><br />
<
input id="btnIncrease" type="button" value=" + " />
<
input id="btnDecrease" type="button" value=" - " />
</
form>
</
body>
</
html>

I have attached code to run on both button’s click events. I first fetch the current size of the <a> tag then replace the px with an empty string. Then I increase or decrease the size by one:

var size = $(lb).css("font-size");
var newSize = parseInt(size.replace(/px/, "")) + 1;

Then I use the css method to set the font-size. Nice and simple.

You can see a Live Demo

How to Print only Text using CSS

I was recently asked a question of the forums of how to send text only data to a printer. Well it’s not as hard as you think. The <link> tag has an attribute called media. One of the values is called print, which means the style sheet will only be applied when you print the document. You can use this to hide images when you print. Create a new style sheet (print.css) and add the following to it:

img
{
display:none;
}

Then in your page, all you need to do is reference that style sheet, and it will only be used when you print.

<head>
<
title>Print Text Only Using CSS</title>
<
link rel="Stylesheet" media="print" href="print.css" />
</
head>
<
body>
<
img src="http://www.google.com.au/intl/en_au/images/logo.gif"
alt="Google" />
<
p>Faucibus non sit amet elit. Lorem ipsum dolor sit amet,
consectetur adipiscing elit. Integer placerat, dui sed
posuere molestie, urna sapien porta purus, vel sodales ante
erat sed arcu. Nunc semper, diam ut blandit elementum,
ipsum purus vestibulum quam, sit amet auctor est nunc ut
risus. Maecenas vitae justo sit amet erat congue aliquet
molestie commodo odio. Praesent tempor pellentesque nibh.</p>
</
body>

The code above is a small HTML page that displays Google’s logo and well as some sample text. When you print this, the image won’t be displayed. You can also do other stuff like changing the font size, font color for print only. This is a very useful thing to know.

Using jQuery to Click on an Element and return it’s HTML

I was recently searching for a plug-in that returns the HTML for an element. I came across a solution suggested by Keegan that shows how to do so. Here’s the solution to find out the HTML of an element by clicking on it

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Make an Image Clickable</title>
<
script type='text/javascript'
src='http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js'>
</
script>

<
script type="text/javascript">
$(function() {
$(".clickable").click(function() {
alert($(this).returnHTML());
});

$.fn.returnHTML = function() {
return $("<div/>").append($(this).clone()).html();
}
});

</script>
</
head>
<
body>
<
input id="btnClick" type="button" value="Click Me" class="clickable" />
<
br />

</
body>
</
html>

The example starts by capturing the click() event on elements which have the class=”clickable” attribute. The returnHTML() function clones the element and extract the html using html(). The result is appended to a div and returned to the calling function. The output is displayed in an alert() as shown below

image

Quickly Replace the Contents of a Text File using C# or VB.NET

In this post, I will show you how to use the File class to quickly replace the contents of a Text File. Check the contents of the Sample.txt file given below.

image

We will replace the @ with [attherate] and also list the emails one after the other separated by a semicolon(;). Here’s the code to do so:

C#

try
{
string replaceString = string.Join(";",
File.ReadAllLines("D:\\sample.txt")
).Replace("@", "[attherate]");

File.WriteAllText("D:\\sample.txt", replaceString);
Console.WriteLine("Done");
Console.ReadLine();
}
catch (Exception ex)
{
// handle ex
}

VB.NET

Try
Dim
replaceString As String = String.Join(";", _
File.ReadAllLines("D:\sample.txt")).Replace("@", "[attherate]")

File.WriteAllText("D:\sample.txt", replaceString)
Console.WriteLine("Done")
Console.ReadLine()
Catch ex As Exception
' handle ex
End Try

After running the code, the output is as shown below

image

Detecting Ctrl and Shift Keys on a Form using C# or VB.NET

I am not a WinForm programmer anymore but that does not stop me from trying out code when a user asks me a question about it.

I recently got a request where the user wanted to detect Ctrl and Shift keys on his windows form. The keys to be detected were Ctrl+C, Ctrl+V and Ctrl+Shift+C

Here’s how the keys can be detected:

C#

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if ((e.Control & e.Shift) && e.KeyCode == Keys.C)
{
MessageBox.Show("Ctrl+Shift+C");
}
else if (e.Control && e.KeyCode == Keys.C)
{
MessageBox.Show("Ctrl+C detected");
}
else if (e.Control && e.KeyCode == Keys.V)
{
MessageBox.Show("Ctrl+V detected");
}
}

VB.NET

Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs)
If (e.Control And e.Shift) AndAlso e.KeyCode = Keys.C Then
MessageBox.Show("Ctrl+Shift+C")
ElseIf e.Control AndAlso e.KeyCode = Keys.C Then
MessageBox.Show("Ctrl+C detected")
ElseIf e.Control AndAlso e.KeyCode = Keys.V Then
MessageBox.Show("Ctrl+V detected")
End If
End Sub
I have seen users using the KeyPress event to solve this requirement. Remember that non-characters keys like Ctrl do not raise the KeyPress event. I prefer either the KeyUp or KeyDown instead.

Set the DateFormat in Global.asax

How do you centrally control the DateFormat in your ASP.NET application? So for example if you want to display the date in a dd-MM-yyyy format on each page of your application without much efforts, how would you do it?

Use the Global.asax!

The following code:

Response.Write("Today's Date Is :" +
DateTime.Now.ToShortDateString());

produces the result shown below (mm/dd/yyyy):

image

Now to convert this dateformat 'centrally' to ‘dd-mm-yyyy’, follow these steps:

Create a new Global.asax file, if you do not have one in your web application. Import the following namespaces as shown here:

<%@ Import Namespace="System.Globalization" %>
<%
@ Import Namespace="System.Threading" %>

Now in the Application_BeginRequest(), write the following code:

C#

protected void Application_BeginRequest(object sender, EventArgs e)
{
CultureInfo cInfo = new CultureInfo("en-IN");
cInfo.DateTimeFormat.ShortDatePattern = "dd-MM-yyyy";
cInfo.DateTimeFormat.DateSeparator = "-";
Thread.CurrentThread.CurrentCulture = cInfo;
Thread.CurrentThread.CurrentUICulture = cInfo;
}

VB.NET

Protected Sub Application_BeginRequest(ByVal sender As Object, _
ByVal e As EventArgs)
Dim cInfo As New CultureInfo("en-IN")
cInfo.DateTimeFormat.ShortDatePattern = "dd-MM-yyyy"
cInfo.DateTimeFormat.DateSeparator = "-"
Thread.CurrentThread.CurrentCulture = cInfo
Thread.CurrentThread.CurrentUICulture = cInfo
End Sub

Now when you run the same piece of code in any of your pages

Response.Write("Today's Date Is :" +
DateTime.Now.ToShortDateString());

you get the following output:

image

New AJAX Control Toolkit (Version 3.0.30930) Released

Stephen recently announced a new AJAX Control Toolkit (Version 3.0.30930) on his blog

Here are some highlights of this release:

  • Over 20 Bug fixes including some major fixes to the CollapsiblePanel, Calendar and Tabs controls
  • Two new Controls which include a version of Seadragon and a new Asynchronous File Upload control. Seadragon allows zooming in and zooming out of images using your mouse whereas the Asynchronous File Upload control allows users to efficiently upload files without having to send the entire contents of the page back to the server.

You can download the Toolkit over here

How to determine if your ASP.NET application is running as a 32-bit or 64-bit application

When I was first asked this question, I thought to look at the System.IntPtr struct. On further investigation, I found a very simple technique suggested by Perica Zivkovic.

Here’s how to determine if your ASP.NET application is running as a 32-bit or 64-bit application

C#

protected void Page_Load(object sender, EventArgs e)
{
if (IntPtr.Size == 8)
{
Response.Write("Running as a 64-bit app");
}
else if (IntPtr.Size == 4)
{
Response.Write("Running as a 32-bit app");
}

}

VB.NET

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If IntPtr.Size = 8 Then
Response.Write("Running as a 64-bit app")
ElseIf IntPtr.Size = 4 Then
Response.Write("Running as a 32-bit app")
End If

End Sub

Note: There could be a possibility that you are running a 32-bit .NET Framework on a 64-Bit Windows OS. Check a cool technique described by Raymond How to detect programmatically whether you are running on 64-bit Windows

Create PDF documents from .NET applications

I have seen a very common question in the forums – How can I create PDF documents from my .NET application?

Here are some of the OpenSouce and Paid libraries that allow you to do so:

Open Source

PDFSharp - PDFsharp is the Open Source library that easily creates PDF documents from any .NET language

iTextSharp – Library to create/manipulate PDF documents on-the-fly

Report.NET - generate PDF documents in a simple and flexible manner

PDFjet for .NET - royalty-free PDF library

Paid Libraries

PDF4NET - .NET library for adding PDF capabilities your .NET application

ABCpdf - Dynamically create Adobe PDF documents on the fly

DynamicPDF™ Generator for .NET - real-time creation of PDF documents based on dynamic data

Using LINQ to Find Top 5 Processes that are Consuming Memory

A user on a forum recently asked me how to find the processes that were currently running. A quick look at MSDN led me to the Process object. The Process provides access to local and remote processes and enables you to start and stop local system processes. Here’s how to find out the top five processes that are consuming memory.

C#

var query = (from p in System.Diagnostics.Process.GetProcesses()
orderby p.PrivateMemorySize64 descending
select
p)
.Skip(0)
.Take(5)
.ToList();
foreach (var item in query)
{
System.Diagnostics.Debug.WriteLine(item.ProcessName);
}

VB.NET

Dim query = ( _
From p In System.Diagnostics.Process.GetProcesses() _
Order By p.PrivateMemorySize64 Descending _
Select p).Skip(0).Take(5).ToList()
For Each item In query
System.Diagnostics.Debug.WriteLine(item.ProcessName)
Next item

The code above produces the following results on my computer:

clip_image002

ASP.NET MVC 2 Preview 2 Released

Microsoft has released ASP.NET MVC 2 Preview 2.

Amongst the new stuff added like the ModelMetadata and ModelMetadataProvider Classes, HTTP Verb Overrides, Single-Project Areas and much more, I find the support for the jQuery validation library to provide client-side validation, the most interesting bit in this release. This version can work side-by-side with ASP.NET MVC 1

Here are some important links:

Download ASP.NET MVC 2 Preview 2

Download the Release Notes

Download the Source Code on CodePlex

Phil Haack’s post

If you are new to ASP.NET MVC, you can read this ASP.NET MVC - Some Frequently Asked Questions

My New EBook – 51 Recipes with jQuery and ASP.NET Controls

Today I am glad to announce my new EBook – 51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls. Being an ASP.NET Microsoft MVP, I have always had the opportunity to have early access to products and explore new web technologies, first hand. Last year, during the same time, it got me all excited when Microsoft officially announced that jQuery will be part of their official development platform. I have been extensively using jQuery with ASP.NET ever since then. This EBook is the result of my practical experience of using jQuery with ASP.NET controls, all in the pursuit of demonstrating techniques to resolve Client-Side programming challenges, quickly.

In this no-nonsense, to-the-point EBook, I show you 51 useful recipes of using jQuery with various ASP.NET controls, each recipe dedicated towards solving a particular problem. These recipes have been written for real-world developers who need instant solutions to common and not-so-common problems.

So be it tackling ClientID’s in MasterPages or be it creating Cool UI Effects or avoiding enormous amount of code to solve common client-side programming tasks, this book shows you all. Each recipe in this EBook is designed to help you to understand, learn and solve challenges associated with ASP.NET Client-Side Development and to provide you with strategies and anecdotes using jQuery that will make you resolve these issues quickly.

You can download the Table of Contents and 5 Sample Chapters of this EBook

You can check some User Reviews and Comments of people who have already purchased this eBook.

To purchase this eBook, please click here.