Adventures of Sudheer

A Resource Puller’s Blog

9 Useful jQuery Calendar And Date Picker Plugins For Web Designers December 21, 2009

Filed under: PHP — Sudheer @ 11:06 am
Tags: , , , , ,

I am a big fan of jQuery, so i always use jQuery Calendar plugins to accomplish my tasks when the clients asked me to implement an event caldendar for them. In this article, i would like to share 9 really useful jQuery Event Calendar and Date Picker plugins that every web designers and developers should know.

1. FullCalendar

FullCalendar is a famous jQuery calendar plugin which offers features like drag-and-drop, integration with Google Calendar and able to fetch events through JSON. Designers can easily customize the look and feel of the calendar, while developers can utilize the exposed hooks for user-triggered events.
FullCalendar

2. Astonishing iCal-like Calendar

This is a tutorial which uses both jQuery and CSS to build an iPhone styled calendar application. The author also implement the Coda-like effect for the popup event.
Astonishing iCal-like Calendar

3. jQuery UI Datepicker

The jQuery UI Datepicker is a highly configurable plugin that adds date picker functionality to your pages. You can customize the date format and language, restrict the selectable date ranges and add in buttons and other navigation options easily.
jQuery UI Datepicker

4. jMonthCalendar

jMonthCalendar supports full month calendar and events. The interesting part of this plugin is it allows developers to interact with the calendar.
jMonthCalendar

5. Date Picker

Date Picker is a jQuery calendar plugin released under MIT and GPL licenses. It has a lot of options and features. For example, you can have multiple calendars in the component, mark dates as special days, easy to customize through CSS and allow different selection modes. All these can be easily setup though the configuration options.
Date Picker

6. jQuery Week Calendar

jQuery Week Calendar is a plugin which will include a weekly calendar in the web application. The events can be supplied as an array or JSON, and these events can be easily drag, drop and resize. There are a lot of options and event callbacks which you can refer through the official plugin page.
jQuery Week Calendar

7. Simple jQuery Date-picker Plugin

This is a very simple date picker plugin. However, it provides a lot of useful and necessary features for a date picker. For example, you can easily navigate to the months and years through the drop down selection boxes.
Simple jQuery Date-picker Plugin

8. jQuery Date Picker Plugin

This is an clean, unobtrusive plugin for jQuery which allows you to easily add date picker to your web forms and pages. There are a lot of configurations and options for this simple plugin. You can refer to the plugin page for more examples of how to use this plugin.
jQuery Date Picker Plugin

9. jQuery Interactive Date Range Picker

This powerful date range picker is a modified version of jQuery UI’s Datepicker component. It has a quicker date selection from a list of preset dates/ranges and a smooth transitions. The latest version uses the jQuery UI 1.7 and jQuery UI CSS Framework. With the power of jQuery UI, user can now switch the calendar theme easily.
jQuery Interactive Date Range Picker

Ref:9 Useful jQuery Calendar And Date Picker Plugins For Web Designers

 

Installing SQL Server 2008 December 17, 2009

Filed under: Database — Sudheer @ 4:47 pm
Tags: , , ,

Introduction

The installation process for SQL Server 2008 has many different options. These options allow you more control over your SQL Server Instance configuration. Having this additional control allows you to set up your SQL Server 2008 instances out of the box with the appropriate configuration, like directory structure, accounts, etc. In this article I’ll walk you through the SQL Server installation process.

Machine Set Up

Prior to installing SQL Server 2008 you need to make sure your SQL Server machine will meet the requirements for SQL Server 2008. There are many different requirements that your SQL Server 2008 machine must meet depending on what version of SQL Server you are installing and the base operating system you are going to use. It is out of the scope of this article to describe all the different machine setups and dependences. Prior to installing SQL Server 2008 you should review the following webpage to identify the correct machine setup for your environment: http://msdn.microsoft.com/en-us/library/ms143506.aspx.

For the purpose of this article I will be installing an evaluation copy of SQL Server 2008 Enterprise Edition. The base operating system I will be installing SQL Server on will be Windows 2003 Enterprise Edition SP1 version. My machine is also configured with a C, D, E, F, and G drives. I will use these different drives to place different components of SQL Server.

Initial Setup Process

When you first stick the SQL Server 2008 CD into your drive it will automatically startup the setup process for SQL Server 2008. If the setup doesn’t start then find the “setup.exe” file and run it. When the setup process starts it will check your machine to make sure the .Net Framework and an updated copy of Windows Installer are on your machine. If these are not on your machine then setup will require that these be installed first before you can install SQL Server 2008. The setup process will walk you through installing these prerequisites if they are not already installed. If you have to install them a reboot will be required before you can perform the actual install of SQL server 2008. Once your machine has all the prerequisites installed the setup process will bring up the following window:

Click here for larger image

On this window you can see you have a number of different hyperlinks you can use. There is a navigation pane on the left that has different SQL Server 2008 items you can pick from and on the right pane are the items associated with the selected left pane item. In my case I have the “Planning” item selected. Note it is displayed in bold font. To install SQL Server 2008 I will need to click on the “Installation” item. When I do that the following screen is displayed:

Click here for larger image

On this window you can also do a number of different things related to installing SQL Server. For the purpose of this article I will be going through the first item “New SQL Server stand-alone installation or add features to an existing installation” item to create a brand new SQL Server 2008 instance.

SQL Server 2008 Installation Process

Once you click on the “New SQL Server stand-alone installation or add features to an existing installation” item a series processes will run and some dialog boxes will be displayed to allow you to configure SQL Server 2008 the way you would like. In SQL Server 2008 a number of new configuration options are available at installation time, which in prior releases had to be done after you installed SQL Server.

After the stand-alone instance installation item is click the set up process runs through a number of rule check processes to verify that your system is setup correctly. The first one does a system configuration check. After each one of these rule check processes you are given a summarized report telling you whether or not your system passed the rules checked. In that summary report you are given the option to view a detailed report of each rule. I would suggest you look at the detail rules report to verify each rule. If you find a rule that needs to be fixed you will need to resolve the issue and then re-run the rule checks.

The next window displayed is the “Product Key” window. On this window you will need to select the version you want to install and enter the product key. The list of versions displayed will depend on what media you use for the installation. Select the appropriate version and key and then click on the “Next” button. This will bring up the “License Terms” window. On this screen you should read the license terms. If you agree with the licensing terms then click on the accept checkbox followed by the “Next” button to move on with the installation. Next, you will be prompted to install the setup files. Click on the “Install” button to start the setup file installation process. Once all the setup files are installed a summary of the setup installation process will be displayed. If all the critical setup rules where meet then you will be allowed to proceed with the installation, if not you will need to fix the reported problems and re-run the setup installation. Once again this setup process has a link where you can review the details of the setup installation. I recommend you review the details prior to proceeding, so you know exactly the status of each rule installed. Once you are ready to move on with the installation click on the “Next” button. This will bring up the following window:

Click here for larger image

This window displays the different SQL Server 2008 feature you can install. Here you will click on the appropriate check boxes for the features you want to install for your instance. For the purpose of this article I’m going to only select the “Database Engine Services”, “SQL Server Books Online”, the “Management Tools – Basic”, and the “Management Tools -Complete”. Also on this screen you can select the directory where you want to install the shared features. In my case I’m installing my shared features on the “E:\” drive. Once all the features are selected and you have identified the location where you want the shared features to be installed you can then click the “Next” button to proceed. Doing that will bring up the following window:

Click here for larger image

On this window you specify whether or not you what to install a default instance or a named instance, what you want for an instance ID and the root directory of the instance. For my install I’m just going to take the defaults and install a default instance and identify that instance with an instance id ofMSSQLSERVER. But for the instance root directory I’m going to specify the “E:\”as a location. Once you are ready to move forward click on the “Next” button. The installation process will then calculate the amount of disk space required for the features you selected. The process will report the disk space requirements for each drive. Review the disk space requirements. If you realized you need to specify a different location you can use the “Back” button to go back and change installation location. once you are satisfied with the disk space allocations and placement click on the “Next” button. Doing that will bring up the following screen:

Click here for larger image

On this window you can use the “Server Accounts” tab to specify the accounts that will be used to run the different SQL Server 2008 services and use the “Collation” tab to specify the collation you would like to use. I like to use domain accounts to run my services. In my case I am just going to use the same account for all SQL Server services. So I can either enter that account multiple times next to each service or I can click on the “Use the same account for all SQL Server services” and only enter the account and password once. On this screen you can also identify the status you would like each service to be placed in at startup. Your choices are “Manual”, “Automatic” or “Disabled”. I prefer that my SQL Server Agent and SQL Server Database engine to start automatically and the SQL Server Browser service to be disabled. To set the collation for your instance use the “Collation” tab. The default collation setting is “SQL_Latin1_General_CP1_CI_AS”. I’d suggest you click on the collation tab to verify the correct collation is specified prior to proceeding. Once you are satisfied with the Server Configuration settings click on the “Next” button to proceed with the installation. Doing this will bring up the following window:

Click here for larger image

On this screen you identify database engine configuration information. There are three different tabs to accomplish this: Account Provisioning, Data Directories, and FILESTREAM. Above you can see the “Account Provisioning” configuration options. Here you can specify whether your instance is to use Windows Authentication only or you want to run in mixed mode to support SQL Server and Windows authenticated logins. If you select “Mixed Mode” then you will need to specify a password for the SA account (no more mistakes in having a blank SA account). Another change is that the “BUILTIN\Administrators” user is no longer added by default, so no more back door for member of the Administrators group. You also now have an option to add users that you want placed in the “sysadmin” built-in server role. I suggest you place at least one user in here. This will allow that user to be able to login to your instance of SQL Server 2008 after the installation is complete. You do that by adding them use the “Add” button in the screen above. You can also use the “Add Current User” button to add the user that is doing the installation to the sysadmin role.

You now have a lot more options for how you want to configure your data directories at installation time, to specify that information click on the “Data Directories” tab on the window above. Upon doing this the following window will be displayed:

Click here for larger image

As you can see here you can specify different directories for: user database DATA files, user database LOG files, tempdb DATA/LOG files, and the back up directory. This allows you to more easily separate your databases DATA and LOG files across different drives. As well allows you to make sure the system databases and tempdb files are also on different drives. Allowing you to do this now allows you to more optimally place your components at installation time to help minimize I/O bottlenecks. Here is how I configured my directories:

Click here for larger image

I have placed my user database DATA file on the E drive, where as the user LOG files are on the G drive. I also placed the tempdb DATA and LOG files on the F drive. This provided me some disk separation between components.

If you want to configure FILESTREAM during the setup process you can by using the “FILESTREAM” tab. The information under this tab allows you to specify exactly how you would like to enable and configure FILESTREAM.

Once you are happy with your Database Engine Configuration option click on the “Next” button. Doing this will bring up an “Errors and Usage Reporting” window where you can send errors and feature usage information to Microsoft. Once you have decided how to report to Microsoft there is another “Next” button to click to move on to the next step of the installation process, which is verifying all the Installation Rules. You should check this window to verify that all installation rules are successful for the components you are installing, and then click on the “Next” button. This will bring you to the final installation window. Here you get make a final review of the installation options you have selected. If there is something you want to change you can use the “Back” button to change it. once you are satisfied with the installation configuration you have identified click on the “install” button. this will start the installation process and install the components you selected in the locations you identified. once the installation process is finished the following window will be displayed:

Click here for larger image

Here you can see all the components I selected have been installed successfully. The install of my SQL Server 2008 instance with the components I selected is now done. When I click on the “Next” button here the final “Close” screen is displayed where I can click on the “Close” button to close the SQL Server 2008 setup process.

Conclusion

Now that I have walked you through the installation process you can see that there are many different options for how might want to configure SQL Server 2008. Hopefully this article has given you a sense of the different options you will need to consider in order to make sure your installation configuration goes smoothly. I suggest you do some planning up front for how best to map out each of the SQL Server components across the different disks drives you have and what account or accounts you want to use for the different SQL Server services. Doing this additional planning will help you be successful in setting up your SQL Server instance configuration the way you want it the first time you install SQL Server 2008.

Ref: Installing-SQL-Server-2008

 

Cross-Platform Development December 16, 2009

Filed under: DotNet, JAVA, OpenSource — Sudheer @ 1:42 pm
Tags: , , , ,

Windows developer use Windows API for developing applications where as Mac developers use Cocoa or Carbon for developing applications.

If we want to develop a thick client application which can run on both Mac and Windows then we have the following preferred technological options.

Visual Basic:

Microsoft doesn’t provide any support for Mac compatibility. We have one 3party solution provider RealSoftware. He offer RealBasic which is similar to VB and which can be used to develop thick client applications for both Mac and Windows.

Ref: REALbasic is a rapid application development environment that enables developers to create high-quality, native software for Windows, Mac and Linux.

REALbasic includes:

  • an integrated environment designed for developer productivity
  • a modern, object oriented programming language
  • a cross-platform object framework
  • a cross compiler that produces native executables

REALbasic is used to create all types of applications, including database clients, commercial software, custom business solutions, educational products and more. In fact, REALbasic itself is written in REALbasic.

REAL Software ships updates to REALbasic every 90 days. No other software tools company ships updates at this pace.

Each new REALbasic license includes all updates for six months. When your REALbasic update plan ends you can either purchase a one year update plan renewal or continue using any release that shipped during your update plan.

http://www.realsoftware.com/support/whitepapers/portingvisualbasic/

VB.NET:

Microsoft Visual Basic .NET doesn’t have any support for Mac. There is a new technology introduced by Microsoft i.e., SilverLight which will be used to execute .NET application with out deploying the complete .NET framework at the client machine. But these applications will we based not thick clients.

SilverLight:

Microsoft® Silverlight™ is a cross-browser, cross-platform plug-in for delivering the next generation of .NET based media experiences and rich interactive applications for the Web. Silverlight offers a flexible programming model that supports AJAX, VB, C#, Python, and Ruby, and integrates with existing Web applications. Silverlight supports fast, cost-effective delivery of high-quality video to all major browsers running on the Mac OS or Windows.

Ref: http://silverlight.net/default.aspx

JAVA:

Java is an platform independent language. We an build thick client application which can be deployed on both Windows and Mac.

Ref: http://java.sun.com/developer/technicalArticles/JavaLP/JavaToMac/

 

Open Source Licensing Detection Gets More Competitive December 16, 2009

Filed under: OpenSource — Sudheer @ 1:05 pm
Tags: ,

With the current economic recession, open source software is a route that some enterprise developers are increasingly considering as a lower-cost alterative to proprietary solutions. However, one of the potential issues with open source software adoption is license compliance—ensuring that developers and enterprises are not in violation with a particular license.

There are a few companies in the market today with solutions to help serve the need for open source license identification, including Black Duck, Palamida and now OpenLogic. The business itself is also evolving from just being about detecting licenses to becoming part of an entire open source software adoption lifecycle process.

“Open source has made its way into enterprises of all sorts, and because open source software is so pervasive now, it’s critical for companies to look at how they comply with open source licenses,” Kim Weins, senior vice president of products and marketing at OpenLogic, told InternetNews.com.”Before they can comply with open source licenses, they need to know which open source licenses they are using. As much as you might think that’s easy to track, it’s not.”

OpenLogic is an open source stack and services support vendor. While it provides commercial support for open source software—most recently including the Red Hat Enterprise Linux clone, CentOS—OpenLogic’s flagship service is OpenLogic Exchange (OLEX), which enables enterprises to manage their open source usage.

This week, the company announced new OLEX services to provide license discovery and compliance.

Weins said the difficulty in license identification is that open source software is often bundled together in sophisticated ways. As a result, a single open source project can often have additionally open source projects inside of it—with bits of code inside that can all be under different licenses.

“It’s not as simple as saying this particular application is licensed under Apache and being done with it,” Weins said.

The issue has led to a number of high-profile legal spats over the last two years. For instance, the Software Freedom Law Center has settled out-of-court disputes with at least four different vendors over license violation issues that arose because of open source code buried with their software.

The business of license identification is one that Black Duck software has been involved in since 2002. For CEO Tim Yeaton, it’s a business that has evolved over the last few years to be about more than just license identification.

“We’ve expanded our capabilities from just being a compliance platform to being a full-on, open source lifecycle adoption platform,” Yeaton said. “We enable customers to search and select open source components, validate them against their process, put in workflows to automate polices, catalogue the resulting components and then attach them directly to their existing development infrastructure.”

Black Duck began its broader lifecycle adoption effort nearly two years ago with the launch of its Code Center application.

OpenLogic’s Weins said she felt her company could offer a new competitive choice by producing fewer false positives than rivals. She also added that OpenLogic’s new services are cloud-focused and leverage the power of Hadoop open source technology to deliver fast, accurate scans.

Black Duck’s Yeaton noted that his company has hosted and Software-as-a-Service offerings. He added that his concern is false negatives more so than false positives.

“If you’ve built a quality tool, done right, there is no such thing as a false positive—there are only things that you’d rather not see because they create noise,” Yeaton said, adding that scans can produce a lot of granular information that a user may not want or need.

He also said that Black Duck has filtering and automation features that lets users customize the information returned from a compliance scan, though they’re not enabled by default.

“The way we built our product and the way it’s deployed by default is that it provides access to all the information,” Yeaton said. “So shame on us for not helping customers upfront to filter. We are getting smarter to help customers to configure their systems.”

But Yeaton said the real issue for him is false negatives—that is, code that isn’t detected.

“There is clutter, because you got more information than you want, but you can turn on a filter,” he said. “But there is real corporate risk of a false negative … you don’t find something that you’re supposed to.”

By Developer.com

 

Uploading an Image and Creating a Thumbnail in ASP.NET October 19, 2009

Filed under: DotNet — Sudheer @ 5:12 am
Tags: , , , ,

There are literally thousands of facets to the .NET Framework, and writing them down functions as a way to learn, memorize or work out the details. This is especially useful for things you use infrequently, such as thumbnail images. I wrote an application several years ago to manage label images, but when I sat down to try to upload an image, I discovered that I had forgotten how to create a thumbnail image—a subject that makes a useful article topic.

This article shows you how to use an <input> control to browse and upload images, and then convert those images to thumbnail versions for display on the web site. The code is straightforward without a lot of sanity checking, as is the ASPX, and works fine for example purposes, but for a production application you’ll want to add validation and error checking (but that’s another article).

Uploading Files with the <input> Element

The <input> HTML element is a versatile HTML control. Based on the value you supply for the element’s type attribute, the <input> element can function (and display) as a general-purpose button, a radio, reset, or submit button, a checkbox, a file uploader, a hidden control, an image, a password field, or a text control. For the file uploader, set the <input> element’s type attribute to file, and the <input> control displays a textbox and a button labeled “Browse.” While you can code this manually, the easiest way to display a file uploader is to select the Input (File) item from the HTML tab of Visual Studio’s Toolbox.



Figure 1. Design-Time View:
From this design-time view, you can see how the sample page uses the table to lay out the other HTML elements.

The sample ASPX page contains this type of <input> element, as well as a label, a button to submit a selected image file, and an image element. The server creates a thumbnail of that image and returns it to the browser, which displays it in an <img> element on the same page. An HTML table handles the control layout (see Listing 1). At design-time, the page looks like Figure 1.

// HTML tables are pretty versatile and easy to use. If you want a simple spreadsheet-like table then use <tr> elements to add rows and <td> elements to add cells. If you want a single cell to span multiple rows then set the <td> element’s rowspan attribute, or to span multiple columns, set its colspan attribute.

The only other interesting aspect of the HTML in Listing 1 is that the <img> control (in column 2 in Figure 1) has an ID attribute, and its runat attribute is set to server. Setting the runat attribute lets you manipulate the <img> control in the server-side code behind. You’ll use this to display the created thumbnail image.

Saving the Uploaded Image

When an <input> control has its type attribute set to file, a user can click the Browse button to select a file. After selecting a file, when the user submits the page the <input> control will have a populated PostedFile property, which is a class that will contain the file’s contents and other file information, such as its file name. To be specific, PostedFile is an instance of the HttpPostedFile class.

To use the GUI, a user clicks the Browse button, selects a file, and then clicks the Upload button. On the server, you can save the posted file by calling the <input> control’s PostedFile.SaveAs method, passing the path and file name where you want to save the file. The following code shows just how easy this part of the process is:

Private Const imagePath As String = “~/Images/”

Private Sub SaveUploadedFile(ByVal filename As String)

File1.PostedFile.SaveAs(MapPath(imagePath) + filename)

End Sub

In the preceding code, File1 is the ID of the <input> control. (The <input> control has the runat=”server” attribute set, so even though it’s an HTML control, it is available on the server side too.)

Creating and Display the Thumbnail

The sample program uses a Button control to submit the default form containing the <input> element. The <input> element has the posted file. The complete code, shown in Listing 2, performs four steps:

  1. Extract the file name from the posted file path
  2. Save the uploaded file to a pre-determined server path
  3. Save a thumbnail copy of the image
  4. Set the <img> element’s src attribute to the thumbnail’s location

When the user submits the file, File1.PostedFile.FileName contains the client’s local path (the location of the file on the user’s machine). You will want to extract the filename without the path, which you can do with the System.IO.Path class’s GetFileName method.

The SaveUploadedFile method shown earlier uses the PostedFile.SaveAs method to save the file. Note that it uses the MapPath method, which maps a server-side relative path to its physical path. It appends the file name to that path, which creates a complete pathname where it saves the uploaded file. (You could also save the file to a database or display the file contents on the web page.)

The next step is to create the thumbnail image. The SaveThumbnail method creates a thumbnail copy of the image.

Private Sub SaveThumbnail(ByVal filename As String)

Dim image As Image = image.FromStream( _

File1.PostedFile.InputStream)

Dim thumbnail As Image = image.GetThumbnailImage( _

100, 100, AddressOf Callback, IntPtr.Zero)

thumbnail.Save(MapPath(GetThumbnailPath(filename)))

End Sub

Private Function GetThumbnailPath( _

ByVal filename As String) As String

Return “~/Images/” + _

String.Format(thumbnailMask, filename)

End Function

The SaveThumbnail method creates an in-memory System.Drawing.Image instance from the HttpPostedFile’s InputStream property by passing the input stream to the Image.FromStream method. Next, it creates a thumbnail copy of the image by calling the Image’s GetThumbnailImage method. GetThumbnailImage has some odd arguments, mostly because its implementation calls into unmanaged code. The first two arguments are the width and height of the thumbnail image, the third argument is an unused callback delegate, which you must provide, even though it’s unused. The fourth argument is another unused relic to satisfy the native code call. The final argument must be IntPtr.Zero. (Obviously, a better thumbnail wrapper probably needs to be created.) Finally, the method saves the thumbnail in the same location as the original image, but with the prefix thumbnail_ added to the file name.

Finally, the SetPreviewImage uses the virtual path for the thumbnail and assigns it to the <img> element’s src property.

Private Sub SetPreviewImage(ByVal filename As String)

PreviewImage.Src = GetThumbnailPath(filename)

End Sub

The topic of uploading files is a bit of an oldie, but it is still a goody. Creating and showing thumbnails is a good way to let users preview numerous images, and then select a full-sized version. The GetThumbnailImage method makes a call into unmanaged native code, so it has some unused “junk” arguments that make it a little cumbersome to use—but now you have the CliffNotes.

Uploading an Image and Creating a Thumbnail in ASP.NET

 

Obtaining Client-Specific Information with a Web Application September 30, 2009

Filed under: DotNet — Sudheer @ 4:28 am
Tags: , , , ,

Obtaining Client-Specific Information with a Web Application

Introduction

An Editor friend and some of my co-workers have taken occasion to remind me that some people don’t like Internet Explorer or don’t see why anyone would ever develop Web applications just for Internet Explorer. Some of these same smart people have expressed the opinion that they don’t like ActiveX in Web applications much either. I respect their opinions. Everyone is entitled to an opinion.

I understand. I have read the Cathedral and the Bazaar by Eric Raymond. I have even exchanged a couple of emails with him. I understand that some people think open source software and uniform standards is the way to go. However, I think about these kinds of issues-open source versus proprietary solutions and IE-only development versus multi- browser platform development-differently, from my own perspective.

First, IE is the most popular browser and is the most widely used. Second, I have actually worked on applications that were Web-based intranet applications and the customer requested IE only. The latest two applications had multi- million dollar budgets. If you are targeting the World Wide Web then IE only development may be short sighted. And, when it comes to ActiveX I think of all available code and solutions as possibilities. Most code has pluses and minuses. My criteria for using something are really just a matter of does it solve the issue expediently, efficiently, and cost effectively and are the risks manageable. Other than that I don’t care where the code comes from, which language it is in, or what coding standard was applied.

This article is limited to IE web-based development and just a few odds and bobs that let your JavaScript code obtain some client/user specific information.

Enabling and Disabling Script Debugging in IE8

Visual Studio 2008 automatically enables script debugging for Internet Explorer 8 sessions started from Visual Studio. You know longer have to uncheck this option (Disable script debugging (Internet Explorer)) in the IE Tools|Options in the Advanced tab. In fact, regardless of the debugging settings script debugging will be enabled for IE8 sessions started from Visual Studio.

There exists a potential for performance problems associated with script debugging always being on. For a registry hack that disables script debugging refer to my DevExpress blog entry here.

Enabling ActiveX in IE8

Internet Explorer security is established by zone. There are five zones: Internet, Local Intranet, Trusted Sites, Restricted Sites, and My Computer. The Internet zone is represented by Web sites on your computer that haven’t been assigned to another zone. The Local Intranet zone is represented by network connections established using a UNC path, Web sites that by-pass the proxy server, or sites that have not been assigned to the Restricted or Trusted zone. Also, if you use a fully qualified domain name (FQDN) or IP address then the site is considered part of the Internet zone. The Trusted Sites zone is for adding web sites that you trust, like FedEx.com, Dell.com, Amazon.com, and the Restricted Sites zone is for web sites that you don’t trust. My Computer is exactly what it sounds like.

If you want to enable ActiveX support for desktop development then you want to adjust the Local Intranet zone. If you add ActiveX controls to your public web site then your users will need to adjust the Internet zone.

If you write some JavaScript that uses an ActiveX object and your browser isn’t configured to permit ActiveX objects then you will get an error dialog like the one shown in Figure 1. To configure support for ActiveX controls on your workstation or laptop, the machine you are developing on, follow these steps (using Figure 2 as a guide):

  1. In Internet Explorer 8 select Tools|Options
  2. Change to the Security tab and click Local intranet in the zones section
  3. Click Custom level
  4. In the Security Settings dialog scroll to the ActiveX controls and plug-ins
  5. Change the “Initialize and script ActiveX controls not marked as safe for scripting” from Disable to Enable or Prompt. (If you want to remember that you have turned on ActiveX support then select Prompt)
  6. Click OK to close the Security Settings dialog
  7. Click OK to close the Internet options dialog



Click here for larger image

Figure 1: If you see this dialog then you need to enable ActiveX objects for the Local Intranet zone.


Figure 2: To let ActiveX objects that you create in script run on your workstation’s browser set “Initialize and script ActiveX controls not marked as safe…” to Enable or Prompt.

Creating an ActiveX Object

ActiveX objects for ascertaining client information include WScript.Network and WScript.Shell. WScript.Network can be used to determine the active user, for example, and WScript.Shell can be used to query information like the path to the MyDocuments folder. For a complete reference for these ActiveX libraries refer to the MSDN help documentation.

Tip: You can use script languages to run JavaScript at a command prompt by running the .js script file in the WScript.exe host.

To create an instance of the desired ActiveXObject you can invoke new ActiveXObject passing in the name of the library as a string that you want to create. The following code demonstrates how to use the debugger; statement to break into the code and create an instance of WScript.Network and WScript.Shell. With these two objects the UserName and the path to the special folder MyDocuments is obtained (refer to Listing 1).

Listing 1: Some JavaScript in a Web page that obtains client-specific information using ActiveX.

// <script type=”text/javascript”>

debugger;

var o = new ActiveXObject(“WScript.Network”);

//UserDomain

//ComputerName

//UserName

alert(o.UserName);

var w = new ActiveXObject(“WScript.Shell”);

alert(w.SpecialFolders(“MyDocuments”));

//CreateShortcut

//SpecialFolders

var jsonObject = { “UserName”: o.UserName,

“MyDocuments”: w.SpecialFolders(“MyDocuments”)

};

</script>

The end of the listing contains a statement that starts with var jsonObject. Programmers used to create objects by writing new Object() and referring to the desired properties. The revised syntax above is part of JSON (pronounced Jason), or JavaScript Object Notation. JSON is a lightweight data-interchange format that is a subset of JavaScript. JSON is used in objects and arrays in a highly readable form, and the technology plays in the same space as XML. The statement above creates an object with two properties: UserName and MyDocuments.

Summary

Now that you have the tools to configure a browser for ActiveX features and obtain client-specific information, it is up to you to figure out how you are going to use it. To recap JavaScript debugging is enabled automatically when Visual Studio starts an instance of IE8. Security settings like ActiveX support are managed by zone. For local workstation ActiveX support modify the Local Intranet zone. You can choose between enabling ActiveX support or prompting for permission. (I choose the latter, so I turn it off when not needed.) Finally, two of the objects that support discovering client-side information are WScript.Shell and WScript.Network. You can explore the integrated MSDN help for more information.

As a final note JavaScript Object Notation (JSON) was briefly introduced. JSON is subset of JavaScript and is a lightweight data-interchange format. JSON is picking up steam and becoming more popular, so I wedged it into the sample.

Biography

Paul Kimmel is the VB Today columnist for www.codeguru.com and has written several books on object- oriented programming and .NET. Check out his upcoming book Professional DevExpress ASP.NET Controls (from Wiley) now available on Amazon.com and fine bookstores everywhere. Look for his upcoming book Teach Yourself the ADO.NET Entity Framework in 24 Hours (from Sams). You may contact him for technology questions at pkimmel@softconcepts .com. Paul Kimmel is a Technical Evangelist for Developer Express, Inc, and you can ask him about Developer Express at paulk@devexpress.com and read his DX blog at http:// community.devexpress.com/blogs/paulk.

Ref: Obtaining Client-Specific Information with a Web Application

 

Implementing Skins and Themes for ASP.NET September 30, 2009

Filed under: DotNet — Sudheer @ 4:18 am
Tags: , , , ,

Implementing Skins and Themes for ASP.NET

This article will show you how to define both a custom skin and a theme for a web application.

Adding a Theme to Your Web Application

You can add a custom theme to your web project from the Solution Explorer. Right-click the root project name and click “Add ASP.NET Folder” from the context menu, and then select the Theme item. This step adds an App_Themes folder containing a Theme1 subfolder. The intent is that each theme subfolder should contain all the elements for a particular theme. Therefore, if you want to have multiple themes, simply add additional Theme sub-folders to the App_Themes folder.

Author’s Note: You can also click App_Themes, select Add ASP.NET Folder and pick “Theme” from the context menu after you’ve added the

App_Themes

folder to your project.

Defining a Skin File

Skin files are XML files with a .skin extension. To add a skin file to your web project’s Theme folder, right-click the Theme folder (Theme1 in this example), and select Add New Item. From the Add New Item dialog select the Skin File item.

Visual Studio inserts a skin file template that initially contains a comment and some boilerplate heading information that shows you two examples:

<%--
Default skin template. The following skins are provided as examples only.
1. Named control skin. The SkinId should be uniquely defined because
   duplicate SkinId's per control type are not allowed in the same theme.
<asp:GridView runat="server" SkinId="gridviewSkin" BackColor="White" >
   <AlternatingRowStyle BackColor="Blue" />
</asp:GridView>
2. Default skin. The SkinId is not defined. Only one default
   control skin per control type is allowed in the same theme.
<asp:Image runat="server" ImageUrl="~/images/image1.jpg" />
--%>

Figure 1. Associating Controls with Skins:
If your skin files contain control properties with a SkinId attribute set, then you can select a specific value for the control’s SkinID property.

The first example in the preceding skin file contains a SkinId, while the second example does not. That’s important, because when a skin element has a SkinId it belongs to the group of items having that same SkinId. However, elements without a SkinId become part of the default Skin definition.

A skin file can contain multiple skins. You can have one default skin—control properties without a SkinId—and as many named skins as you want: control properties with SkinId attributes. If your skin elements have a SkinId then Visual Studio will let you select the various SkinId values from a control’s SkinID property (see Figure 1).

One reasonable way to define control properties for a skin file is to format the item’s appearance directly in an ASP.NET web page—and then copy and paste the applicable elements from the ASPX file to the .skin file. The following code shows the skin file elements defined for the example application:

<asp:GridView runat="server"
  AllowPaging="true" Font-Names="Tahoma"
  Font-Size="9pt" CellPadding="4">
  <HeaderStyle BackColor="#C1DBFA" />
  <AlternatingRowStyle BackColor="#ECF4FE" />
  <RowStyle />
  <PagerStyle CssClass="PagerStyleClass" BackColor="#C1DBFA" />
</asp:GridView>

Figure 2. Skinned GridView:
Here’s how the GridView looks with a skin file applied.

Notice that the boilerplate comments were removed from the preceding code, which provides HeaderStyle, AlternatingRowStyle, and PagerStyle settings. The skin contents also look very similar to the HTML/XML that defines a GridView in an ASPX page.

These control properties define a default skin. The skin specifies BackColor attributes for the header and alternating rows, and references a cascading style sheet class for the PagerStyle (discussed in more detail in the next section). It’s worth noting that the runat attribute has to be set to server in the .skin file. Figure 2 shows the result when this skin file is applied to a GridView.

Building Out a Cascading Style Sheet

While writing my latest book, I got so used to looking at the Aqua theme provided with the DevExpress controls that I decided to approximate it for the demo. The style employs a subtle contrast between the header and footer and the alternating rows. The preceding skin file defines the control properties, including fonts and colors; however, skin files do not support style information for HTML elements. You need to define those in a cascading style sheet. The good news is that adding a cascading style sheet to your theme automatically incorporates it as part of the theme, without you having to add a specific reference in your web page.

The example in Figure 2 shows a GridView populated with information from the Northwind database’s Customers table. The grid is inside a <div> tag with some padding applied, and the table header <th> and table cell <td> use a solid thin blue border. (Remember that controls such as GridViews are rendered as HTML.) The pager is also rendered as an HTML table, but I didn’t want a border around the pager items. To eliminate the border around the pager items the PagerStyleClass uses a combinatory * and td to indicate that descendant td elements inside of the PagerStyleClass will use the PagerStyleClass settings. Here’s the CSS file added to Theme1:

body {
}
.divClass
{
  border:solid thin Silver;
  margin: 10px 20px 10px 20px;
  padding: 10px 20px 10px 20px;
}
.PagerStyleClass * td
{
  border-style: none;
}
th, td
{
  border:solid thin #A3C0E8;
}

The .divClass entry defines a border, margin, and padding. This .divClass is assigned to the page’s main <div> tag’s class attribute. The element styles for the th (table header) and td (table cell) define a solid, thin, bluish border. All <th> and <td> elements will employ this style unless it’s overridden by some other style. You could also define a specific style class for the grid using the combinator approach used with the .PagerStyleClass. Finally, the .PagerStyleClass * td uses the combinator * to mean that the style information applies to descendant table cells.

With the theme complete, you can remove all redundant control properties from the ASPX pages to unclutter the ASPX code. You don’t have to do this because theme information overrides local property settings—but doing so may eliminate some confusion. Here’s the ASPX code for the sample solution:

<%@ Page Language="VB" AutoEventWireup="false"
  CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
        DataKeyNames="CustomerID" DataSourceID="SqlDataSource1">

        <Columns>
          <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True"
            SortExpression="CustomerID" />
          <asp:BoundField DataField="CompanyName" HeaderText="CompanyName"
            SortExpression="CompanyName" />
          <asp:BoundField DataField="ContactName" HeaderText="ContactName"
            SortExpression="ContactName" />
          <asp:BoundField DataField="ContactTitle" HeaderText="ContactTitle"
            SortExpression="ContactTitle" />
          <asp:BoundField DataField="Address" HeaderText="Address"
            SortExpression="Address" />
          <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
          <asp:BoundField DataField="Region" HeaderText="Region"
            SortExpression="Region" />
          <asp:BoundField DataField="PostalCode" HeaderText="PostalCode"
            SortExpression="PostalCode" />
          <asp:BoundField DataField="Country" HeaderText="Country"
            SortExpression="Country" />
          <asp:BoundField DataField="Phone" HeaderText="Phone" SortExpression="Phone" />
          <asp:BoundField DataField="Fax" HeaderText="Fax" SortExpression="Fax" />
        </Columns>
        <PagerStyle BorderStyle="None" />
      </asp:GridView>
      <asp:SqlDataSource ID="SqlDataSource1" runat="server"
        ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
        SelectCommand="SELECT * FROM [Customers]"></asp:SqlDataSource>
    </div>
    </form>
</body>
</html>

Adding the Theme to a Web Page

You can apply a theme to an individual web page by adding either a Theme or a StyleSheetTheme attribute to the page’s @Page directive. The following code fragment demonstrates how to use the Theme attribute; you use the StyleSheetTheme attribute in the same way:

<%@ Page Language="VB" AutoEventWireup="false"
  CodeFile="Default.aspx.vb" Inherits="_Default" Theme="Theme1"%>

Author’s Note: The difference between Theme and StylesheetTheme is that if you apply the Theme attribute then the theme’s control property settings take precedence over any local property settings. In contrast, if you apply the StylesheetTheme attribute, local property settings take precedence over theme-based settings.

Adding a Theme to an Entire Web Application

If you want to apply a theme to your entire web application, then you set the theme attribute of the <pages> tag in the web.config file as shown below:

<pages theme="Theme1">

You’ve seen the rudiments of custom themes, skin files, and cascading style sheets, including the subtle yet important difference between the @Page Theme and @Page StylesheetTheme attributes. For some great ideas for defining custom themes, look at some of the pre-defined themes used for other sample projects and existing web sites. You can also check out DevExpress’s ASP.NET controls for good theme ideas. You can download trial versions at http://www.devexpress.com.

About the Author

Paul Kimmel is the VB Today columnist for www.codeguru.com. He has written several books on object-oriented programming and .NET. Check out his latest book Professional DevExpress ASP.NET Controls (from Wiley), and watch for his upcoming book Teach Yourself the ADO.NET Entity Framework in 24 Hours (from Sams). Paul is also a Technical Evangelist for Developer Express, Inc. You can ask him about Developer Express or read his DX blog here.

Ref: Implementing Skins and Themes for ASP.NET

 

Sending Email Both in HTML and Plain Text July 9, 2009

Filed under: DotNet — Sudheer @ 9:37 am
Tags: , , , ,

In this article you will learn how to send email using ASP.NET. Yes, there are plenty of other articles that cover sending email via .NET, but after spending a day doing research, I was amazed at how many articles failed to provide either a correct solution or a real world example. I found that many articles suggest you create your HTML email by using a string with the HTML markup in it. That’s crazy and not at all a real world solution, at least not for most situations. In this article we will look at a more realistic solution. One in which we use a regular HTML file as our template for the email. The template file will be a standard HTML file with the exception of some placeholders that we will use to populate our content and images right before we send the email. Think mail-merge in Microsoft Word. Finally, we will also learn how to send the email in such a way that if the email recipient’s mail-client can’t render HTML they will get an alternate plain text version.

Let’s start by looking at the code in its entirety; the people that just want to grab the code and use it can do so. I will then explain the code.

PLAIN TEXT

C#:

  1. // CREATE EMAIL
  2. // first we create a plain text version and set it to the AlternateView
  3. // then we create the HTML version
  4. MailMessage msg = new MailMessage();
  5. msg.From = new MailAddress(TextBoxYourEmail.Text);
  6. msg.Subject = “Event: ” + labelEventName.Text;
  7. msg.To.Add(TextBoxEmail1.Text);
  8. // create a string to hold all email addresses
  9. StringBuilder sbEmailTo = new StringBuilder();
  10. sbEmailTo.Append(TextBoxEmail1.Text);
  11. if (!String.IsNullOrEmpty(TextBoxEmail2.Text)) { msg.To.Add(TextBoxEmail2.Text); sbEmailTo.Append(“, ” + TextBoxEmail2.Text); }
  12. if (!String.IsNullOrEmpty(TextBoxEmail3.Text)) { msg.To.Add(TextBoxEmail3.Text); sbEmailTo.Append(“, ” + TextBoxEmail3.Text); }
  13. if (!String.IsNullOrEmpty(TextBoxEmail4.Text)) { msg.To.Add(TextBoxEmail4.Text); sbEmailTo.Append(“, ” + TextBoxEmail4.Text); }
  14. if (!String.IsNullOrEmpty(TextBoxEmail5.Text)) { msg.To.Add(TextBoxEmail5.Text); sbEmailTo.Append(“, ” + TextBoxEmail5.Text); }
  15. String plainEmail = TextBoxYourName.Text + ” has invited you to an event! \r\n \r\n” +
  16. “Event Name: ” + labelEventName.Text + “\n” +
  17. “Event Date: ” + eventTextBox.Text + “\n” +
  18. “Event Description: ” + labelEventDescription.Text + “\r\n \r\n” +
  19. “Message: ” + TextBoxPersonalMessage.Text;
  20. //first we create the Plain Text part
  21. AlternateView plainView = AlternateView.CreateAlternateViewFromString(plainEmail, null, “text/plain”);
  22. msg.AlternateViews.Add(plainView);
  23. //now create the HTML version
  24. MailDefinition message = new MailDefinition();
  25. message.BodyFileName = “email.htm”;
  26. message.IsBodyHtml = true;
  27. message.From = TextBoxYourEmail.Text;
  28. message.Subject = “Zoo Event: ” + labelEventName.Text;
  29. //embed images for the email
  30. EmbeddedMailObject emo = new EmbeddedMailObject();
  31. emo.Path = @”~\Images\email\hdr_roar.gif”;
  32. emo.Name = “hdr”;
  33. EmbeddedMailObject emo2 = new EmbeddedMailObject();
  34. emo2.Path = @”~\Images\email\box_top.gif”;
  35. emo2.Name = “box_top”;
  36. message.EmbeddedObjects.Add(emo);
  37. message.EmbeddedObjects.Add(emo2);
  38. //Build replacement collection to replace fields in email.htm file
  39. ListDictionary replacements = new ListDictionary();
  40. replacements.Add(“<%EVENTDATE%>”, eventTextBox.Text);
  41. replacements.Add(“<%EVENTNAME%>”, labelEventName.Text);
  42. replacements.Add(“<%FROMNAME%>”, TextBoxYourName.Text);
  43. replacements.Add(“<%EVENTDESCRIPTION%>”, labelEventDescription.Text);
  44. replacements.Add(“<%PERSONALMESSAGE%>”, TextBoxPersonalMessage.Text);
  45. //now create mail message using the mail definition object
  46. //the CreateMailMessage object takes a source control object as the last parameter,
  47. //if the object you are working with is webcontrol then you can just pass “this”,
  48. //otherwise create a dummy control as below.
  49. MailMessage msgHtml = message.CreateMailMessage(sbEmailTo.ToString(), replacements, new LiteralControl());
  50. AlternateView htmlView = AlternateView.CreateAlternateViewFromString(msgHtml.Body, null, “text/html”);
  51. msg.AlternateViews.Add(htmlView);
  52. // send email now (check web.config)
  53. SmtpClient smtp = new SmtpClient();
  54. smtp.Send(msg);

The Setup

Add the System.Net.Mail namespace. The System.Net.Mail namespace contains everything we need to send email using a Simple Mail Transfer Protocol (SMTP) server for delivery.

Modify the Web.config file to include the below:

PLAIN TEXT

CODE:

  1. <system.net>
  2. <mailSettings>
  3. <smtp from=”admin@company.com”>
  4. <network host=”localhost” port=”25″  />
  5. </smtp>
  6. </mailSettings>
  7. </system.net>

The kicker and not well documented part to note is the from=”admin@company.com” in the smtp tag. You can change the from address later, but the MailDefinition class needs this here.

That’s it for setup. Now let’s look at the first chunk of code.

Create The Plain Text Version

PLAIN TEXT

C#:

  1. MailMessage msg = new MailMessage();

The MailMessage class represents an email message that can be sent using the SmtpClient class.

PLAIN TEXT

C#:

  1. msg.From = new MailAddress(TextBoxYourEmail.Text);
  2. msg.Subject = “Event: ” + labelEventName.Text;
  3. msg.To.Add(TextBoxEmail1.Text);

Pretty straight-forward. This just assigns the From, Subject and To properties to our mail message.

PLAIN TEXT

C#:

  1. // create a string to hold all email addresses
  2. StringBuilder sbEmailTo = new StringBuilder();
  3. sbEmailTo.Append(TextBoxEmail1.Text);
  4. if (!String.IsNullOrEmpty(TextBoxEmail2.Text)) { msg.To.Add(TextBoxEmail2.Text); sbEmailTo.Append(“, ” + TextBoxEmail2.Text); }
  5. if (!String.IsNullOrEmpty(TextBoxEmail3.Text)) { msg.To.Add(TextBoxEmail3.Text); sbEmailTo.Append(“, ” + TextBoxEmail3.Text); }
  6. if (!String.IsNullOrEmpty(TextBoxEmail4.Text)) { msg.To.Add(TextBoxEmail4.Text); sbEmailTo.Append(“, ” + TextBoxEmail4.Text); }
  7. if (!String.IsNullOrEmpty(TextBoxEmail5.Text)) { msg.To.Add(TextBoxEmail5.Text); sbEmailTo.Append(“, ” + TextBoxEmail5.Text); }

In this example they have the option of sending the email to more than one recipient. So we perform a check on the four optional text-boxes to see if they have email addresses and if they are not empty then we add them to our MailMessage instance. In addition, we append them to our StringBuilder instance which we will end up using later.

PLAIN TEXT

C#:

  1. String plainEmail = TextBoxYourName.Text + ” has invited you to an event! \r\n \r\n” +
  2. “Event Name: ” + labelEventName.Text + “\n” +
  3. “Event Date: ” + eventTextBox.Text + “\n” +
  4. “Event Description: ” + labelEventDescription.Text + “\r\n \r\n” +
  5. “Message: ” + TextBoxPersonalMessage.Text;
  6. //first we create the Plain Text part
  7. AlternateView plainView = AlternateView.CreateAlternateViewFromString(plainEmail, null, “text/plain”);
  8. msg.AlternateViews.Add(plainView);

Here we simply create a string which we’ll use as our plain-text email message. But remember, we only want to use the plain-text version of the email if their mail client does not support HTML. Therefore we use the AlternateView class and add it to our MailMessage instance. We could have chosen not to use the alternate view and just made it the body of our MailMessage instance, but not this time.

That’s it for the plain-text version, now we will handle the HTML version.

Create The HTML Version

PLAIN TEXT

C#:

  1. //now create the HTML version
  2. MailDefinition message = new MailDefinition();
  3. message.BodyFileName = “email.htm”;
  4. message.IsBodyHtml = true;
  5. message.From = TextBoxYourEmail.Text;
  6. message.Subject = “Zoo Event: ” + labelEventName.Text;

Notice we use the MailDefinition class this time and not the MailMessage class as we did with the plain-text version. That’s because it’s the MailDefinition class that allows us to to create an email from an HTML file. Notice the BodyFileName property that we have set to our “email.htm” file. This is just a regular old HTML file. Lastly, we set the IsBodyHtml property to true.

PLAIN TEXT

C#:

  1. //embed images for the email
  2. EmbeddedMailObject emo = new EmbeddedMailObject();
  3. emo.Path = @”~\Images\email\hdr_roar.gif”;
  4. emo.Name = “hdr”;
  5. EmbeddedMailObject emo2 = new EmbeddedMailObject();
  6. emo2.Path = @”~\Images\email\box_top.gif”;
  7. emo2.Name = “box_top”;
  8. message.EmbeddedObjects.Add(emo);
  9. message.EmbeddedObjects.Add(emo2);

The above code adds two images to the HTML file. The EmbeddedMailObject represents an item to embed in a mail message. Notice the Name property. This is important because in our HTML file (email.htm) we have this <img src=”cid:hdr” alt=”" /> code which is where it maps to the image. This way of adding images to our MailDefinition object will send the images with the email. If you don’t wish to send images with your email you may choose to simply add absolute paths to your images in your HTML file like normal. Just make sure the paths are absolute.

PLAIN TEXT

C#:

  1. //Build replacement collection to replace fields in email.htm file
  2. ListDictionary replacements = new ListDictionary();
  3. replacements.Add(“<%EVENTDATE%>”, eventTextBox.Text);
  4. replacements.Add(“<%EVENTNAME%>”, labelEventName.Text);
  5. replacements.Add(“<%FROMNAME%>”, TextBoxYourName.Text);
  6. replacements.Add(“<%EVENTDESCRIPTION%>”, labelEventDescription.Text);
  7. replacements.Add(“<%PERSONALMESSAGE%>”, TextBoxPersonalMessage.Text);

This is an important part. This is where we pass in fields to our HTML template. Within our HTML file we find this <%EVENTDATE%> . This is a placeholder that we use to pass in content. Pretty cool eh? Almost like a mail-merge in Word. So all the above gets mapped into our HTML template. Now we see the power of this solution. It sure beats creating a huge string. We have a regular old HTML file with the placeholders that we pass in the content. Any future changes can be done right in the HTML file. Nice…

Now the last code section:

PLAIN TEXT

C#:

  1. //now create mail message using the mail definition object
  2. //the CreateMailMessage object takes a source control object as the last parameter,
  3. //if the object you are working with is webcontrol then you can just pass “this”,
  4. //otherwise create a dummy control as below.
  5. MailMessage msgHtml = message.CreateMailMessage(sbEmailTo.ToString(), replacements, new LiteralControl());
  6. AlternateView htmlView = AlternateView.CreateAlternateViewFromString(msgHtml.Body, null, “text/html”);
  7. msg.AlternateViews.Add(htmlView);
  8. // send email now (check web.config)
  9. SmtpClient smtp = new SmtpClient();
  10. smtp.Send(msg);

The CreateMailMessage method creates the email message and does the merging of our replacement list with the placeholders. We also pass in the string that we created earlier. Remember the string held all the email recipient addresses. The last parameter is looking for a control that owns the MailDefinition. We don’t have one so we just pass in a dummy control.

All that remains is to send the email message via the smtp protocol. If everything in your Web.config file is set up correctly your email should be on the way.

 

Java Internationalization Made Easy June 25, 2009

Filed under: JAVA — Sudheer @ 8:01 pm
Tags: , ,

Gone are the days when your application would be geared only for local users. Today, every application must support internationalization: being accessible to users across the world and customized to the respective local users. As one of the most widely used programming languages, Java must support this requirement.

This article explains how to support internationalization in Java. Java internationalization is a simple concept, and when it is implemented correctly, long-term management requires only minimal or no code changes—even when requirements such as additional lingual support keep accumulating.

Author Note: The industry abbreviation for internationalization is i18n, which is the letters i and n with a count of the letters between the two (both inclusive).

Building internationalization support isn’t very difficult. In fact, once you get acquainted with the implementation methodology, you will find it is one of the easiest Java development tasks that you will perform. You can use it as a best practice to ensure internationalization support in all your future applications.

How i18n Works

The classes ResourceBundle and Locale in the java.util package are the building blocks for internationalization. As an example, consider the following code fragment for an application that displays a thank you message to the user along with a localized message:

import javax.swing.*;

public class GenericClass
{
   public static void main(String args[])
   {
      GenericClass genericClass = new GenericClass();
      genericClass.askQ();

   }

   private void askQ()
   {
      JOptionPane.showMessageDialog(null, 

      "The text displayed is specific to locale", 

      "Thanks to visit", JOptionPane.INFORMATION_MESSAGE);
   }
}

Figure 1 shows the output from the above code.

Figure 1: Thank You Message to the User

Figure 1: Thank You Message to the User

Imagine customizing this application to your locale without needing to rewrite it. With Java, you just add a few lines of code and the rest is simple customization.

Take a look at how you would transform the above code using internationalization:

import javax.swing.*;
import java.util.*;

public class InternationalizedClass
{
   //This are the stuff that will help you internationalize
   private static String language = "en"; //Initialize with en
    private static String country = "US"; //Initialize with US
   private static Locale currentLocale;
   private static ResourceBundle localMessagesBundle;

   public static void main(String args[])
   {

      if(args.length == 2)
      {
         language = new String(args[0]);
         country = new String(args[1]);
      }
      currentLocale = new Locale(language, country);

      localMessagesBundle = ResourceBundle.getBundle("LocalMessagesBundle",currentLocale);

      InternationalizedClass internationalizedClass = new InternationalizedClass();
      internationalizedClass.askQ();
   }

   private static void askQ()
   {
      JOptionPane.showMessageDialog(null,
         localMessagesBundle.getString("localeInfo"),
         localMessagesBundle.getString("thanks"),
         JOptionPane.INFORMATION_MESSAGE);
   }
}

When you run the transformed code with the arguments fr and FR, you will see the output shown in Figure 2.

Figure 2: Message Localized to France

Figure 2: Message Localized to France

If you have used the .properties file in Java, you already know how the preceding example worked. It is no different from the key-value pair mapping of information. There are different .properties files created for every locale; the file contents have the same key but different values. In i18n code, you always refer to the key, and based on the values specified for the locale and the country, you retrieve the correct resources and use them in your application.

The internationalization in the above code is supported by the files LocalMessagesBundle_en_US.properties and LocalMessagesBundle_fr_FR.properties (which you can download). The .properties file name is derived from a combination of the filename, language, and country code. For example, the file name LocalMessagesBundle_en_US.properties is for United States of America, with the language (English) denoted by en and the country code by US. Similarly, LocalMessagesBundle_fr_FR.properties is built for France with fr for French and the country code FR.

Transforming Your App for Different Locales

When you have your i18n infrastructure in place, it’s just a matter of minutes to transform your application for any locale you wish. Java supports a set of locales by default. The following snippet helps list the supported locales. The result will vary depending on the platform you use.

import java.util.*;
import java.text.*;

public class SupportedLocales{
   public static void main(String args[])
   {
      Locale list[] = DateFormat.getAvailableLocales();
      //Displays language and the country code
      for (int i=0; i< list.length; i++) {
         System.out.println(list[i].toString());
      }
      System.out.println("----------------------------------------------");
      //Displays the Language; more user readable
      for (int i=0; i< list.length; i++) {
         System.out.println(list[i].getDisplayName());
      }
   }
}

When Things Get a Bit More Complicated

So far, you have seen messages that are simple and mostly just a few words. In real-world scenarios, you may know only part of the message that needs to be localized and the remaining values will be computed at runtime or come from some other source.

For example, consider the following message:

I was born at 5:45 on January 25, 1971

The message contains distinct information (in boldface) that are part of a single statement. The code for this would still be:

ResourceBundle messages = ResourceBundle.getBundle("Messages",locale);

The resource bundle Messages.properties would contain the following:

msgRules = I was born at (2,time,short) on (2,date,long)

The following class uses the above resource bundle to display the desired message:

import java.util.*;
import java.text.*;

public class MessageFormatter
{
   public static void main(String args[])
   {
      showMessage();
   }

   static void showMessage()
   {
      //Defaulting to US
      showMessage("en","US");
   }

   static void showMessage(String language, String country)
   {
      Locale locale = new Locale(language,country);
      ResourceBundle messages = ResourceBundle.getBundle("Messages",locale);

      Object[] messageArguments =
      {
         new Date(74,6,8,12,5,0)
      };

      MessageFormat formatter = new MessageFormat("");
      formatter.setLocale(locale);

      formatter.applyPattern(messages.getString("msgRules"));
      String formattedMessage = formatter.format(messageArguments);

      System.out.println(formattedMessage);
   }
}

Figure 3 shows the output from the above code.

Figure 3: Birth Date and Time Message

Figure 3: Birth Date and Time Message

Not only are the i18n techniques described here simple, but they also have the long-term benefit of enabling you to add internationalization support to applications that are already deployed. In effect, you can utilize the concept in almost every aspect of information display that you can imagine.

Code Download

  Java i18n _src

For Further Reading

  “Java Internationalization” (from Sun Developer Network)

 

Browser Compatibility Development Guide June 25, 2009

Filed under: Development — Sudheer @ 7:53 pm
Tags: , , , , , , ,

Introduction

Creating cross browser web applications impacts the entire Software Development Life Cycle (SDLC). Impacted roles include project managers, web designers, architects, developers and quality assurance.

This guide for browser compatibility development has been designed to answer the following questions about developing cross browser web applications:

  1. Is the browser compatibility problem a business problem?
  2. What is the recommended browser compatibility solution?
  3. What browser families do I need to support?
  4. What environments and tools are required?
  5. What are design and development best practices?
  6. What are design and development pitfalls?
  7. What additional resources are recommended?

The goal of this article is to provide the information needed to start or enhance a browser compatibility development practice in your organization.

Browser Compatibility Now and Then

At the turn of the century, web developers created applications which worked across Netscape and Internet Explorer (IE) browser families as each browser competed for market share. This was an arduous task due to evolving web standards and the lack of adoption across vendors. In the ensuing years, Internet Explorer won the market share battle, but not the war. The additional effort for building applications to work with Netscape was not warranted for many applications.

From the perspective of market share, the current situation looks much more like 2000 than 2003. There are now two very popular browser families, IE and Firefox. Other browsers such as Safari, Chrome and Opera have a significant presence as well.

From the perspective of web standards, it is a totally different game. Browser standards are stable and mature. Their adoption across vendors is very broad. While not a trivial task, it is much easier today to build web applications which work across browser families if standards are followed. Browser compatibility is more of a developer than a vendor problem today.

The Browser Compatibility Problem

Wikipedia defines “cross browser” as the ability for a website to support multiple web browsers. This is essentially what we mean by browser compatibility. In the past, new features were added to IE and Netscape without any coordination between vendors. This resulted in differences between how features worked ranging from slight cosmetic differences to profound conceptual differences.

Today, the maturity and adoption of web standards by vendors has standardized the feature set to a great extent. This is fortunate because the marketplace demands browser agnostic web applications. If your organization creates applications tied to a specific browser, it puts itself at the risk of turning away consumers and partners who prefer to interact with a particular browser. This is the browser compatibility business problem. If your website does not render or operate correctly on a user’s browser, it negatively affects your organizations image and brand. This means your applications should be browser agnostic to the highest degree practical.

The Browser Compatibility Solution

In the past, the requirement for cross browser applications was solved for by creating “forks” in the code to handle the peculiarities of supported browsers. This made it costly and difficult to create and maintain websites due to the redundant development and testing of the various code branches. When new browser versions were introduced, poorly designed forks often created additional work due to the change in browser behavior.

Web standards provide a much simpler solution for building cross browser applications. The web application is designed from the start to support web standards–not a particular browser. To a certain degree, this future proofs the web application from the introduction of new browsers and browser versions.

Structure, Presentation and Behavior Standards

There are three sets of World Wide Web Consortium (W3C) standards which describe the structure, presentation and behavior of a web page. There is also a key Ecma standard tied to manipulating the behavior.

The structure of the web page document is defined by markup language standards (HTML, XHTML, XML). The DOCTYPE descriptor tells the browser what document type definition to use in validating the structure and how strict to apply validation rules. The following DOCTYPE statements instruct the browser to strictly adhere to the HTML 4.01 and XHTML 1.0 specifications in validating the page.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN">

The presentation of the web page uses the CSS standard to control the colors, fonts and layout. CSS separates the content described in the document structure from how it is viewed in different contexts.

The behavior of the web page is controlled by the ability to manipulate a standard document object model (DOM) representation of the structure and presentation elements. ECMAScript, the standard version of JavaScript is the standard language used to manipulate the object model.

Adherence to structure, presentation and behavior standards (and not vendor specific adaptations of these standards) is the essence of the browser compatibility solution.

What Browser Families Should You Support?

You need to consider which browser families, operating systems and configurations are preferred by your customers, partners and employees. In order to understand your audience specifically, you will need to examine the web analytics particular to your web application.

There are many industry resources which provide browser usage analytics. These should be reviewed regularly to stay top of trends. An example is the following W3C website: http://www.w3schools.com/browsers/browsers_stats.asp.

In general, Firefox and IE are the most popular browsers. A good starting point in your browser compatibility practice is to minimally provide formal support for these two browser families, meaning you will fully verify them through the entire software development life cycle. By following web standards, you will be well positioned to support additional families such as Chrome, Safari, Opera or others if required by your audience with minimal additional effort.

In addition to the browsers supported, you should also pay attention to the types of devices and operating system versions being used as well so you can test your applications in environments similar to those being used by your customers, partners and employees.

What Environments and Tools are Required?

A browser compatibility solution requires the properly configured development and quality assurance environments to support web designers, architects, developers and quality assurance personnel throughout the software development life cycle (SDLC).

Development Environment

Web designer and developer desktops will need to be configured with the primary supported browsers. Firefox and Internet Explorer should be considered at minimum. If your audience demands it, other browsers such as Chrome, Safari and Opera should also be included.

Because Firefox more strictly adheres to structure, presentation and behavior standards, it should be the primary browser for development. Firefox should be configured as the default browser on the desktop and in your IDE (Integrated Development Environment), for example, Eclipse. Although Internet Explorer is not the primary browser, it should be utilized in unit testing.

Debugging tools are essential in developing cross browser applications. Firebug and Web Developer are two essential plug-ins which should be included in your Firefox configuration. A rich toolset and plug-in ecosystem is another advantage of the Firefox browser for designers and developers.

QA Environments

Quality assurance environments may be provisioned on site, or remote services may be used. A remote service may be useful for testing odd or uncommon browser and operating system combinations.

Whereas developers and designers should be using Firefox as their primary browser, quality assurance personnel should spend more time with Internet Explorer. This creates balance in the development and testing activities across the primary browser families.

Browser Compatibility Design and Development Best Practices

The following is a starter list of best practices for browser compatibility design and development.

1. Use Firefox as the primary browser for development
The Mozilla team designed Firefox to support W3C standards from the ground up. Because Firefox adheres more strictly to standards, it is much easier to develop a web application on Firefox and then get it to work in Internet Explorer than the reverse. Development IDE such as Eclipse should be configured so that Firefox is the default browser.

2. In development, periodically test the application in Internet Explorer and other supported browsers
Throughout the development phase, test the application in IE. Prior to Quality Assurance, thoroughly test the application in IE. Utilize your onsite or remote compatibility lab to test different versions within the supported browser families.

3. Use IE as the primary browser for Quality Assurance
A significant percentage of end users prefer Internet Explorer. Quality assurance testing the application developed primarily with Firefox on IE will ensure that any IE compatibility issues missed by developers in their unit testing will be identified. The application should also be regression tested versus all supported versions in the IE and Firefox browser families as well as other formally supported browsers.

4. Specify a DOCTYPE to explicitly declare the structure of the web page
A DOCTYPE specifying strict use of HTML or XHTML is recommended. Not being careful in the DOCTYPE declaration can throw a browser into what is known as “Quirks Mode” which allows invalid and vendor specific markup. A page developed unknowingly in quirks mode will not render consistently if at all with other browsers. The strict DOCTYPE keeps you honest in adhering to standard and valid markup document structure.

In Firefox, the “Page Info” dialog box (available from Tools, Page Info) specifies the rendering mode currently in effect. In addition, the document.compatMode property can be checked programmatically.

Although a “strict” DOCTYPE and standards compliance mode are recommended, each project must determine the level of warnings which are acceptable. It is quite possible to have an application that works fine with Firefox and IE, but still has items flagged by validators such as missing alt tags.

5. Utilize global CSS to separate document structure from presentation and to abstract browser presentation differences
Utilize CSS libraries to control the presentation across the site and encapsulate browser differences in the box model which controls white space around block level elements. Any presentation code such as font tags should be forbidden from the markup document and included in the CSS.

6. Use 3rd party libraries in lieu of custom JavaScript code for cross browser support
If you find yourself writing cross browser code, it should raise a red flag. It is a much better practice to use a 3rd party library which has been built and tested for cross browser support. For example, Ajax solutions such as Dojo provide JavaScript libraries which were built from the ground up for cross browser support and accessibility.

7. Utilize Firebug and Web Developer Plug-ins
The Firebug and Web Developer Plug-ins provide a wide variety of features designed to help validate, analyze, debug and correct browser compatibility issues. Try to avoid putting alerts in your JavaScript and markup for debugging which must later be removed. It is very easy to inspect and manipulate the structure, presentation and behavior elements of your web page at run time using these tools.

8. Develop a Browser Compatibility Knowledge Base
Create a Browser Compatibility Knowledge Base to catalog and share browser compatibility lessons learned, perhaps beginning with the previous seven items outlined here. This knowledge base can be as simple as a shared document or wiki.

Browser Compatibility Design and Development Pitfalls

The following is a starter list of pitfalls to avoid in the design and development of cross browser applications.

1. Avoid browser specific plug-ins – The whole purpose of creating cross browser applications is not being tied to a specific browser family. Browser specific plug-ins such as ActiveX controls are a detriment to compatibility.

2. Avoid code forks – If you find yourself coding JavaScript which says if(isIE6), you are introducing a fork, and a non standard feature into the web application. This will create duplicate development, QA, maintenance and production support activities. In addition, this code is likely to cause additional re-work as new IE or Firefox versions are introduced or other browsers such as Chrome or Safari are supported.

Your first course of action is to use standards to meet the stated requirement. If the requirements cannot be met without standard features, then it is better to create a fork which tests for a particular feature such as if (document.getElementById).

3. Not considering the implications of what CSS hacks are used – CSS hacks take advantage of browser deficiencies in supporting standards. These hacks may be used to encapsulate browser compatibility issues. However, care must be used to ensure they do not create maintainability issues, nor impede behavior in future browser versions.

Summary

Browser compatibility is more than a technical problem. It is a business problem. If your website does not render and operate properly on the browsers your customers and partners prefer to use, it may harm the reputation of your organization and turn customers away.

Ensuring browser compatibility of your web applications begins with understanding your end users needs. Compatibility development standards and practices to meet these needs must be defined for your organization and embedded into the entire software development lifecycle. Creating browser compatible applications affects the day to day job of project managers, web designers, architects, developers and quality assurance personnel.

Web standards which define the structure, presentation and behavior of a website are the cornerstone of a browser compatibility development practice. Adhering to these standards make what was once a very arduous job more manageable.

The proper environments and tools are needed for developers and quality assurance personnel to test for browser compatibility and to debug problems. These tools and environments should be designed and configured to simulate the user experience of your audience.

There are a number of best practices and pitfalls shared in this article. Creating a browser compatibility knowledge base will help capture the lessons learned and to share them with the broader development community.

Do you have the statistics which show what browsers your customers, partners and employees prefer to use? Do you have defined standards for creating web applications which will support these browsers? Do you have the appropriate environments and tools to test and debug for browser compatibility? Do you have a knowledge base to share lessons learned and best practices? If your answer is no to any of these questions, consider using the information presented here to start or enhance a browser compatibility development practice in your organization. The rest is up to you!

Browser Compatibility Resources

Anyone wanting to study browser compatibility in more detail would do well to start here.

Developing Web Applications Using Standards

Designing With Web Standards by Jeffrey Zeldman
Migrate Applications from IE to Mozilla by Doron Rosenberg
Using Web Standards by Mozilla
Web Standards Checklist by Max Design
The Business Benefits of Web Standards by Mozilla

Validation Services

W3C markup validation service
W3C CSS Validation Service
Mozilla DOCTYPE Sniffing