Search (Google -CodeProject -Youtube ) one click

Google
 

Saturday, September 25, 2010

Using Microsoft's Chart Controls In An ASP.NET Application: Using the Chart Controls with ASP.NET MVC

Introduction

The Microsoft Chart controls are a series of classes in the System.Web.UI.DataVisualization.Charting
namespace
that allow web developers to ability to add charts to their ASP.NET applications. The most pertinent charting-related class is the
Chart class, which contains information about
the chart's appearance, series, charting areas, and so forth. In most of the demos and code samples we've explored thus far, we've used the Chart class
as a Web control, adding the <asp:Chart> declarative markup to our ASP.NET page, setting a few properties and, occasionally, writing a few lines
of code. When used as a Web control, the Chart class both creates the chart (as an image) and then renders an <img> element that points
to the generated chart image.


Using the Chart Web control is a standard practice in a WebForms application, but it is not suggested when building an
ASP.NET MVC application. (While it is possible to add Web controls - including the Chat Web control - to the views of an
ASP.NET MVC application, it is generally frowned upon.) So, if we can't use the Chart Web control in an ASP.NET MVC application, how do we display a chart?
In addition to being used as a Web control, the Chart class can also be used programmatically. It is quite possible to create a new Chart object,
set some properties, plot the data points, and then generate the chart image. In fact, we looked at using this technique in an earlier installment,
Programmatically Generating Chart Images, in which we saw (among other things) how to generate chart
images programmatically and add them as attachments in an email message.


This article explores how to display charts in an ASP.NET MVC application.
An Overview of Displaying Charts in an ASP.NET MVC Application

Using the Chart Web control in an ASP.NET WebForms application typically involves adding the Chart control to a page, setting a few properties and, perhaps, writing a
few lines of code. When a visitor arrives at such a page, the Microsoft Chart Controls take the data to be plotted, dynamically generates an image, and then stores this
image either in memory. The Chart Web control itself doesn't return the binary contents of the image; rather, it renders an <img> element whose
src attribute points to a file named ChartImg.axd, which grabs the just-created image file from memory and returns it.
(This is a bit of an oversimplification and does not describe all of the possible ways the Chart Web control can generate and serve the chart image; refer to the
Rendering the Chart article for a more in-depth examination on this topic.)


In an ASP.NET MVC application we do not have the Chart Web control or the ChartImg.axd file at our disposal. Instead, we are on the hook for:


  1. Defining a URL that, when visited, plots the chart data, generates chart image, and returns its contents, and

  2. Adding the HTML to our views to display the chart image


Consider an ASP.NET MVC application that displays sales data charts from the Northwind database. One chart of interest is the annual sales chart, which displays the
total sales for all products in a specified category for a specified year (such as the total sales for all Beverages products in 1997). Our first step to displaying
such a chart would be to define a URL that, when visited, would return the corresponding chart image. You have total flexibility in the URL pattern you choose to render
a report. I like to create a controller named Charts with actions for each type of chart I offer, using querystring parameters to indicate the input
parameters for the chart (if any). In other words, for the annual sales chart I'd use a URL pattern like
Charts/SalesByYear?CategoryName=CategoryName&OrderYear=Year. With such a pattern in place, visiting
www.yoursite.com/Charts/SalesByYear?CategoryName=Beverages&OrderYear=1997 would return the contents of an image file that displays the annual sales data
for 1997 for those products in the Beverages category. Bear in mind that this URL returns just the image contents and not any other markup. To display the chart in
a view you would add an <img> element to the view, like so:




<img ... src="/Charts/SalesByYear?CategoryName=Beverages&OrderYear=1997" />


I've created an ASP.NET MVC 2 application using C#, Visual Studio 2010, and ASP.NET 4, which is available for download at the end of this article. The remainder of
this article shows how to display charts in an ASP.NET MVC application by walking through some of the more interesting aspects of this demo application.


Creating the Charts Controller and SalesByYear Action

In ASP.NET MVC, incoming URLs are mapped to actions, which are methods in a controller. Typically, actions return the HTML markup rendered by a view, but actions can
actually return any kind of markup, including plain text, JSON, and binary content. In other words, it's quite possible to create an
action that returns the binary contents of an image.


To display charts in an ASP.NET MVC application we need to create an action that returns the binary contents of a specific chart image. As I noted earlier in this article,
I like to put all of my chart-generating actions in a single controller named Charts. The name of the action determines the URL that will be used to view
a chart image. For example, in the demo application I created an action in the Charts controller named SalesByYear. A simplified version
of this action is shown below:




public class ChartsController : Controller

{

   public ActionResult SalesByYear(string categoryName, int orderYear = 1995, bool showTitle = true)

   {

      ...

   }

}


Note that this action takes three input parameters: categoryName, orderYear, and showTitle. These input parameters are automatically
assigned the values of the querystring parameters with a matching name. If a visitor requests the URL Charts/SalesByYear, without specifying any querystring
parameters, the three input parameters will be assigned their default values - null, 1995, and true, respectively. However, if appropriately named
querystring fields are present in the request, such as Charts/SalesByYear?CategoryName=Condiments&OrderYear=1996&ShowTitle=false, then the three input fields
will be assigned those values - Condiments, 1996, and false, in this example. (The showTitle input parameter is used to indicate whether to display
the chart title in the rendered image.)


The job of the SalesByYear action is to:


  1. Generate the annual sales chart for the requested category and year,

  2. Generating the chart image, and

  3. Return the chart image's binary contents


Back in the Programmatically Generating Chart Images article, we looked at how to work with charts
in lieu of the Chart Web control by programmatically creating the Chart object, setting its properties, specifying its data points, and generating the
chart image. To start, we need to create an instance of the Chart object and set properties like the Width and Height:




public ActionResult SalesByYear(string categoryName, int orderYear = 1995, bool showTitle = true)

{

   // Create the Chart object and set some properties

   var salesChart = new Chart() {

      Width = 600,

      Height = 400

   };




   ...


Next, we need to plot the chart's data points. There are a variety of ways to do this programmatically, as covered in the Plotting Chart
Data
installment. If you are going to be frequently creating charts through programmatic means, I recommend that you familiarize yourself with
K. Scott Allen's ChartBuilder
class
, which provides a simple API for plotting the points in a Chart object. (Scott introduced his ChartBuilder class in
Charting With ASP.NET And LINQ.)


The following four lines of code uses Scott's ChartBuilder class to create a Sales By Category chart. All of the heavy lifting is handled by the
SalesByCategoryChartBuilder class, which we examined in a demo in Plotting Chart Data. (The SalesByCategoryChartBuilder class extends Scott's
ChartBuilder class.) In a nutshell, the SalesByCategoryChartBuilder class
takes two inputs - the category name and order year - and plots the gross sales for the specified year for all products in the specified category.




   var builder = new SalesByCategoryChartBuilder(salesChart);

   builder.CategoryName = categoryName;

   builder.OrderYear = orderYear;

   builder.BuildChart();


After the BuildChart method has completed, the Chart object contains information about its chart areas, series, and, most importantly, its data points, which are
the sales figures for each of the products in the specified category. At this point the title has been added to the chart, so we can hide it, if needed.




   if (!showTitle)

      salesChart.Titles[0].Visible = false;


We are now ready to generate the chart image! The Chart object has a SaveImage method that can save the chart image to a file or a stream.
In this case we want to save the image to a stream so that we can send back the binary contents directly to the client without having to first save the image to disk
on the web server. To accomplish this, we: create a new MemoryStream object; save the image as a PNG, sending the image contents to the just-created
MemoryStream; return to the beginning of the stream; and then return the binary contents of the stream to the client, specifying a content-type of
"image/png", which tells the browser that the binary data it is receiving the binary contents of a PNG image.




   // Save the chart to a MemoryStream

   var imgStream = new MemoryStream();

   salesChart.SaveImage(imgStream, ChartImageFormat.Png);

   imgStream.Seek(0, SeekOrigin.Begin);



   // Return the contents of the Stream to the client

   return File(imgStream, "image/png");

}


That's all there is to it! With this code in place, visiting www.yoursite.com/Charts/SalesByYear?CategoryName=Condiments&OrderYear=1998 returns the following
image:



The sales for Condiments in 1998 chart.


Displaying the Chart in a View

At this point we have a URL that, when visited, generates the chart image and returns it. The next question is, how do we display this chart in a view? Because we have
a URL that, when requested, returns an image, we can display this image in a web page by using the <img> element. For example, in the demo application's
Home controller's Index view you'll find the following <img> element, which displays the annual sales chart for the Beverages
category for 1997:




<div style="text-align: center">

   <img ... src="/Charts/SalesByYear?CategoryName=Beverages&OrderYear=1997" />

</div>


To facilitate displaying charts, I added a number of extension methods to the
HtmlHelper class - see the MyHtmlHelpers.cs class in the
demo. This adds a Chart extension method to HtmlHelper, allowing you to use syntax in your view like
<%: Html.Chart(actionName, controllerName, routeValues) %>. This renders an <img> element with the appropriate
src attribute. (For more information on creating your own custom HTML helpers, refer to Creating Custom HTML Helpers.)
For example, the following syntax renders the same <img> element from the code snipped above:




<div style="text-align: center">

   <%: Html.Chart("SalesByYear", "Charts", new { CategoryName="Beverages", OrderYear = 1996 }) %>

</div>


What's more, the Chart extension method also can accept a collection of HTML attributes. For example, the following syntax generates an <img> element
whose src attribute references the Charts/SalesByYear?CategoryName=Beverages&OrderYear=1996 URL and whose alt attribute is set to
"Beverage sales for 1996."




<div style="text-align: center">

   <%: Html.Chart("SalesByYear", "Charts", new { CategoryName="Beverages", OrderYear = 1996 }, new { alt = "Beverage Sales for 1996" }) %>

</div>


The demo includes two views for displaying the annual sales data. The first one is Home/SalesData, which contains a form with two drop-down lists, one for
the set of categories and another for the available years. The screen shot below shows this view in action.



The sales for the Meat/Poultry products in 1997.


The second view, Home/SalesDataFancy, hides the title in the chart and instead replaces it with text so that the category name and year can be displayed
as drop-down lists. In this example, I use JavaScript and jQuery to change the URL of the <img> element whenever the
drop-down list selection changes. For example, imagine the user is viewing the sales for the Condiments category for 1998. In that case, the <img> element
on the page will have its src attribute referencing Charts/SalesByYear?CategoryName=Condiments&OrderYear=1998. If the user then changes the
categories drop-down list to Seafood, rather than doing a postback or requiring the user to click a button, I execute JavaScript code that changes the src
of the <img> tag from Charts/SalesByYear?CategoryName=Condiments&OrderYear=1998 to
Charts/SalesByYear?CategoryName=Seafood&OrderYear=1998. This has the effect of instantaneously changing the chart and does
not require an extra click from the user or the entire page to be reloaded.



The sales for the Condiments products in 1998.


Conclusion

The Microsoft Chart controls include a Chart Web control that simplifies adding charts to an ASP.NET WebForms application. While this Web control can be used in an
ASP.NET MVC view, mixing Web controls in MVC views is generally frowned upon. Fortunately, a chart's image can be generated programmatically and its binary contents
returned from an action. In this way, it is possible to associate a URL - like Charts/SalesByYear?CategoryName=CategoryName&OrderYear=Year
with the image contents of a particular type. Once such a URL has been defined and the action implemented, displaying the chart in a view is as simple as adding an
<img> element whose src attribute points to the URL. To simplify this process, I created an extension method for the HtmlHelper
class named Chart, which you can find in the demo available for download at the end of this article.


Happy Programming!

Wednesday, December 26, 2007

pp Windows xp Run Commands..!

99 Commands the Windows XP Command prompt can run.

Here is a list of commands that you can run off from the Run Command prompt in XP:
Go to Start Menu > Run… and type in the command to run


Accessibility Controls = access.cpl

Add Hardware Wizard = hdwwiz.cpl

Add/Remove Programs = appwiz.cpl

Administrative Tools = control admintools

Automatic Updates = wuaucpl.cpl

Bluetooth Transfer Wizard = fsquirt

Calculator = calc

Certificate Manager = certmgr.msc

Character Map = charmap

Check Disk Utility = chkdsk

Clipboard Viewer = clipbrd

Command Prompt = cmd

Component Services = dcomcnfg

Computer Management = compmgmt.msc

Date and Time Properties = timedate.cpl

DDE Shares = ddeshare

Device Manager = devmgmt.msc

Direct X Control Panel (If Installed)* = directx.cpl

Direct X Troubleshooter = dxdiag

Disk Cleanup Utility = cleanmgr

Disk Defragment = dfrg.msc

Disk Management = diskmgmt.msc

Disk Partition Manager = diskpart

Display Properties = control desktop/desk.cpl

Dr. Watson System Troubleshooting Utility = drwtsn32

Driver Verifier Utility = verifier

Event Viewer = eventvwr.msc

File Signature Verification Tool = sigverif

Findfast = findfast.cpl

Folders Properties = control folders

Fonts = control fonts

Fonts Folder = fonts
FreeCell Card Game = freecell
GameControllers = joy.cpl
Group Policy Editor (XP Prof) = gpedit.msc

Hearts Card Game = mshearts

Iexpress Wizard = iexpress

Indexing Service = ciadv.msc

Internet Properties = inetcpl.cpl

IP Configuration = ipconfig
Java Control Panel (If Installed) = jpicpl32.cpl
JavaApplication Cache Viewer (If Installed) = javaws

Keyboard Properties = control keyboard

Local Security Settings = secpol.msc

Local Users and Groups = lusrmgr.msc
Logs You Out Of Windows = logoff
MicrosoftChat = winchat
Minesweeper Game = winmine

Mouse Properties = control mouse

Mouse Properties = main.cpl

Network Connections = control netconnections

Network Connections = ncpa.cpl

Network Setup Wizard = netsetup.cpl

Notepad = notepad
Nview Desktop Manager (If Installed) = nvtuicpl.cpl

Object Packager = packager
ODBCData Source Administrator = odbccp32.cpl

On Screen Keyboard = osk
Opens AC3 Filter (If Installed) = ac3filter.cpl

Password Properties = password.cpl

Performance Monitor = perfmon.msc

Performance Monitor = perfmon

Phone and Modem Options = telephon.cpl

Power Configuration = powercfg.cpl

Printers and Faxes = control printers

Printers Folder = printers
PrivateCharacter Editor = eudcedit

Quicktime (If Installed) = QuickTime.cpl

Regional Settings = intl.cpl

Registry Editor = regedit

Registry Editor = regedit32

Remote Desktop = mstsc

Removable Storage = ntmsmgr.msc

Removable Storage Operator Requests = ntmsoprq.msc

Resultant Set of Policy (XP Prof) = rsop.msc

Scanners and Cameras = sticpl.cpl

Scheduled Tasks = control schedtasks

Security Center = wscui.cplServices = services.msc

Shared Folders = fsmgmt.msc

Shuts Down Windows = shutdown

Sounds and Audio = mmsys.cpl

Spider Solitare Card Game = spider

SQL Client Configuration = cliconfg

System Configuration Editor = sysedit

System Configuration Utility = msconfig

System File Checker Utility = sfc

System Properties = sysdm.cpl

Task Manager = taskmgr

Telnet Client = telnet

User Account Management = nusrmgr.cpl

Utility Manager = utilman

Windows Firewall = firewall.cpl

Windows Magnifier = magnify

Windows Management Infrastructure = wmimgmt.msc

Windows System Security Tool = syskey

Windows Update Launches = wupdmgr

Windows XP Tour Wizard = tourstart

Wordpad = write

Sunday, December 16, 2007

First, the Google phone , Android..


By now, everyone knows that there is really no Google phone but an open source phone platform. I am not sure how to make of it. Android is certainly not the first attempt of its kind. The SavaJe Technology (acquired by Sun) and Sun JavaFx Mobile are some of the examples of Java phone platforms. They did not quite take off for varieties of reasons. Would Google phone follow the same fate? Only time will tell.
Google does provide access to the kernel source code which is based upon Linux, and is built for Qualcomm chipset. So you could imagine that the Google engineers will be using these devices to test the platform. You could see the phone from the video below from Google Android web site. The prototype phone is eerily similar to the screenshot from emulator. Somehow I have a hunch that someone will port this kernel and the Android platform to existing real phones soon. There are already some discussions going on for Dell Axim X50v, HTC Kaiser (also known as AT&T Tilt), and HTC Universal (also known as T-Mobile MDA-IV, etc).


Android platform
The core of Android runs Linux. Underlying C/C++ library is not well documented, and not supported. This is very similar to Apple iPhone. There have been some programmers hacking away, running console C/C++ applications on it. For now, without GUI, it is quite useless. But it could be a starting point to dig up the underlying file systems, etc. Google did mention in the document that Bluetooth and WiFi native APIs will be available, but not now. Hmmm, why am I not surprised?
The Android platform is based on Java. In other words, if an application is not based on Java, it cannot be called Android application, even though it runs on Android-based phones.
Major components in Android platform are shown in the following architecture diagram, taken from Google Android SDK doc.
CLICK TO ENLARGE



One unique thing about Android is that every application has its own Java Virtual Machine (JVM) - Dalvik. The resource consumption for this JVM is not clear and no benchmark information is available. Intuitively it might be problematic but then again Google has proven the intuition wrong a few times. It would be interesting to see the rationales behind this decision.
Key functionalities seem complete from the online resource and SDK document. Most of the networking functionalities will be supported in the final releases, including GSM, Bluetooth, EDGE, 3G, and WiFi. GPS will also be included. But they are not included in this version of Android SDK.

User experience
Phone is so much different from PC. I am not sure phone platform alone can define the user experience. Aesthetics, materials, design, touch, hold, feel and operations are all parts of overall experience that are so crucial to the success of the phone, thus the underlying phone platform. Google certainly has a good start and let's hope Google succeeds in transforming the phone and phone platform landscape.

Android applications
I have been playing with Google Phone Android SDK since it was released. Please note that this is just some first impression, particularly when this SDK is not yet a final release. This article explores the Google Phone platform Android from developer's perspective, partly because I am from programming background and want to focus on development side of things, partly because, well, there is no phone :)
Here are some screenshots from the emulator in SDK. You could download the emulator and give it a try. It is free. After you unzip the SDK, just run Emulator.exe in tools folder. As you can see, the applications available in the SDK emulator are fairly limited so far. Note that Note Pad is a sample I built and deployed from the SDK via Eclipse and the Android plugin.



Overall impression
On the positive sides, Google Android is a drastically different approach from Apple's closed platform policy. I am sure it will be welcomed by all developers. Without a real phone to touch, to hold and to sell, there is not much at stake for Google like Apple does. Apple's one million iPhones in three months is in a league all by itself. Maybe Google is just testing the water. Let's hope that one million Android downloads in three months (wild guess?) translates into something bigger than Apple's stellar record.
However, quite frankly, I am a bit disappointed at the moment (I definitely hope as time goes by the perception will change). Not at the Android phone platform (whether it is complete or polished enough), but at the non-revolutionary aspect of this platform. Granted, I might have high hope after much hyped rumors of Google Phone given track records of Google's innovations that we all grow accustomed to. Perhaps it also has something to do with iPhone's setting such a high standard in terms of innovation. Android platform is evolutionary in nature. I am certainly hoping to see more revolutionary elements going forward. Because of its openness, hardware vendors could also bring on their innovation to the platform. How well the model will work remains to be seen.

Resuscitate Your .NET Programs with the Application Recovery and Restart API

Please your users by making your applications recover intelligently and restart smoothly after failures with this .NET-savvy integration wrapper for the Application Recovery and Restart API.


Microsoft has gone to great lengths to help you make your software applications more appealing to users. You can create rich user experiences with Windows Presentation Foundation, smooth web applications with ASP.NET AJAX, data friendly applications with LINQ, and much more. But when it comes to appeal, nothing beats an application that is always available and doesn't suffer from data loss or corruption. Microsoft's Application Recovery and Restart (ARR) API makes it easier than ever to add this level of appeal to your application. ARR gives you an opportunity to recover data and return to a consistent state when your application terminates or hangs, and it will optionally restart your application.
Application recovery is the process of saving and recovering the state of your application when it terminates unexpectedly or hangs. Application restart is the process of launching an application after it has terminated unexpectedly. The restart functionality in Application Recovery and Restart is independent of the recovery functionality, but the two complement each other well. You may recover an application without automatically restarting it, and you may automatically restart an application without recovering its data.Microsoft released ARR with Windows Vista, but it's particularly relevant in Windows Server 2008, because server applications typically require higher reliability and stability, and servers rarely have a human present to address problems when they arise.To explore ARR, it's easiest to start with an application destined to fail. You'll need Visual Studio 2005 or 2008 running on Windows Vista or Windows Server 2008 to build and run the sample "DevX.ServerApplication" application described in this article. If you haven't yet upgraded to one of these operating systems, but you have an MSDN subscription, you can use Virtual PC 2007 to create a virtual machine test lab.

Figure 1. DevX.ServerApplication in Action:















The sample application exercises the Application Recovery and Restart API.DevX.ServerApplication is a .NET console application (see Figure 1). Microsoft didn't expose Application Recovery and Restart in the .NET Framework, so the first step to using it with .NET is writing a class to expose the relevant kernel32.dll functions. It turns out that Application Recovery and Restart is one of the more difficult APIs to marshal properly, so you can save valuable time by adding the ApplicationRecoveryRestart class to your application: using System;
using System.Runtime.InteropServices;
using System.Text;

namespace DevX.ServerApplication
{
public static class ApplicationRecoveryRestart
{
public delegate Int32 ApplicationRecoveryCallbackDelegate(
RecoveryInformation parameter);

[DllImport("kernel32.dll")]
public static extern void ApplicationRecoveryFinished(
Boolean success);

[DllImport("kernel32.dll")]
public static extern Int32 ApplicationRecoveryInProgress(
out Boolean canceled);

[DllImport("kernel32.dll")]
public static extern Int32 GetApplicationRecoveryCallback(
IntPtr process,
out ApplicationRecoveryCallbackDelegate recoveryCallback,
out RecoveryInformation parameter,
out UInt32 pingInterval,
out UInt32 flags);

[DllImport("kernel32.dll")]
public static extern Int32 GetApplicationRestartSettings(
IntPtr process,
StringBuilder commandLine,
ref UInt32 size,
out UInt32 flags);

[DllImport("kernel32.dll")]
public static extern Int32 RegisterApplicationRecoveryCallback(
ApplicationRecoveryCallbackDelegate recoveryCallback,
RecoveryInformation parameter,
UInt32 pingInterval,
UInt32 flags);

[DllImport("kernel32.dll")]
public static extern Int32 RegisterApplicationRestart(
String commandLineArgs,
UInt32 flags);

[DllImport("kernel32.dll")]
public static extern Int32 UnregisterApplicationRecoveryCallback();

[DllImport("kernel32.dll")]
public static extern Int32 UnregisterApplicationRestart();
}
}

With the Application Recovery and Restart API exposed to .NET, you're ready to write server applications capable of recovering from failures and restarting.
Download the sample application source code for this article.

coming soon >>

  • Registering for Application Recovery
  • Registering for Application Restart


Saturday, December 15, 2007

Robo fish..LOL

A robotic fish developed by scientists from Essex University is put through its paces in a special tank at the London Aquarium.
It works via sensors and has autonomous navigational control.
here>


Funny japanes moto :))

Watch this....:))

c# glopalization in 20 minutes..!






Globalization of Windows Application in 20 Minutes

Prelude
There was once a time when multiple language support to a windows application used to be a three to six months call, but with the advent of .Net not anymore. Here is a 20 minutes crash course for globalization / Localization of a windows application. I think you'll find it as useful as I do.

Globalization in simple terms means enabling an application so that it works in different national, similar to how a global company operates in different countries. For a windows application globalization means, it is intended for worldwide distribution.
There are two aspects of the Globalization:
Internationalization : Enabling the application to be used without language or culture barriers, i.e. language and cuture information comes from a resource rather than hard coded in the application
Localization : Translating and enabling the product for a specific locale. Based on the resource file translating the application into that language and culture
Target
Modular design: Code Once Use Everywhere (COUE), this is the prime feature which is needed when you globalize an application. All anyone should do is to convert any user interface output/message box /labels text etc, to something like frmMain.RM.GetString("10001"), No culture information or resource manager initialization again in all the forms or anywhere else

Default language: Saving and retrieving the default language selected by the user in registry
Features: How to take care of date/time , multiple forms , images etc
Reusability: Minimum number of effor when you a dd a new form to the application
Extensibility: Support of multiple language, French, Spanish and English using resource files for each

To hold your interest here is how it looks


Friday, December 14, 2007

First step..>>>>

Wow so i did it finally ...this is my technical blog..
I hope that i'll be useful and helpful for all who are intersting in technology and science .
Now what ???
Now the start ;)