Friday, April 22, 2011

jQuery Split revisited

Split method split the string into array of substring and return a new array. The basic syntax for split method is,


1
string.split(separator, limit)
It takes 2 parameters,
1. separator - This is optional. It specifies the character to use for splitting the string. If omitted, the entire string will be returned.
2. limit - This is also optional. This will be an integer value that specifies the number of splits to be made.

Let's see some examples.

Example 1:

1
2
var element = 'jQuery By Example Rocks!!';
var arrayOfStrings = element.split();
In this example, I have not used any separator and not defined any element. So the whole string will be returned back to arrayOfStrings variable.

Example 2:
?
1
2
var element = 'jQuery By Example Rocks!!';
var arrayOfStrings = element.split(" ");
In this example, I have passed space as delimiter or separator to split the string. So arrayOfStrings variable will have 4 items.

1
2
3
4
arrayOfStrings[0] = "jQuery"
arrayOfStrings[1] = "By"
arrayOfStrings[2] = "Example"
arrayOfStrings[3] = "Rocks!"
Example 3:

1
2
var element = 'jQuery By Example Rocks!!';
var arrayOfStrings = element.split(" ",3);
In this example, I have passed space as delimiter or separator to split the string and also passed limit as 3. So arrayOfStrings variable will have only 3 items.

1
2
3
arrayOfStrings[0] = "jQuery"
arrayOfStrings[1] = "By"
arrayOfStrings[2] = "Example"
Hope this post provides you enough information about Split method.

Wednesday, April 13, 2011

after logout back button Problem in asp.net

Put This Code in Page load Event Of login Page

Response.Buffer = true;
            Response.ExpiresAbsolute = DateTime.Now.AddDays(-1d);
            Response.Expires = -1500;
            Response.CacheControl = "no-cache";

Monday, April 11, 2011

Generate Random Numbers

QL Server has a built-in function that generates a random number, the RAND() mathematical function.  The RAND math function returns a random float value from 0 through 1.  It can take an optional seed parameter, which is an integer expression (tinyint, smallint or int) that gives the seed or start value.
To use it, you can simply do a simple SELECT, as follows:
SELECT RAND() AS [RandomNumber]
The result generated by this SELECT statement is as follows (note that your results may be different from the value shown here, hence the name random)
RandomNumber
---------------------
0.34344339282376501
The output of the RAND function will always be a value between 0 and 1.  If you want to generate a random integer number, all you have to do is multiply it by the maximum value you want generated and then get rid of the decimal places.  One way of getting rid of the decimal places is by CASTing it to INT.  Here's an example of generating a random number with a maximum value of 999,999:
SELECT CAST(RAND() * 1000000 AS INT) AS [RandomNumber]
And here's an example result of this SELECT statement:
RandomNumber 
------------ 
163819

The Downside of the RAND Function
One thing to take note with the RAND function is that if the seed parameter is passed to it, the output will always be the same.  This can be seen with the following:
SELECT RAND(1) AS [RandomNumber]
Running this SELECT statement multiple times with 1 as the seed of the RAND function will always yield the same result:
RandomNumber
---------------------
0.71359199321292355
Another thing to take note with the RAND function is that if it is included in a SELECT statement on a table, the value returned for each row will be the same, as can be seen with the following example.
SELECT TOP 10 RAND() AS [RandomNumber], [CustomerID], [CompanyName], [ContactName]
FROM [dbo].[Customers]
RandomNumber         CustomerID CompanyName                         ContactName
-------------------- ---------- ----------------------------------- -------------------
0.21090395019612362  ALFKI      Alfreds Futterkiste                 Maria Anders
0.21090395019612362  ANATR      Ana Trujillo Emparedados y helados  Ana Trujillo
0.21090395019612362  ANTON      Antonio Moreno Taquería             Antonio Moreno
0.21090395019612362  AROUT      Around the Horn                     Thomas Hardy
0.21090395019612362  BERGS      Berglunds snabbköp                  Christina Berglund
0.21090395019612362  BLAUS      Blauer See Delikatessen             Hanna Moos
0.21090395019612362  BLONP      Blondesddsl père et fils            Frédérique Citeaux
0.21090395019612362  BOLID      Bólido Comidas preparadas           Martín Sommer
0.21090395019612362  BONAP      Bon app'                            Laurence Lebihan
0.21090395019612362  BOTTM      Bottom-Dollar Markets               Elizabeth Lincoln

http://www.sql-server-helper.com/tips/generate-random-numbers.aspx

Date and Time Data Types and Functions

9999-12-31
0.00333 second
8
No
No
datetime2
YYYY-MM-DD hh:mm:ss[.nnnnnnn]
0001-01-01 00:00:00.0000000 through 9999-12-31 23:59:59.9999999
100 nanoseconds
6 to 8
Yes
No
datetimeoffset
YYYY-MM-DD hh:mm:ss[.nnnnnnn] [+|-]hh:mm
0001-01-01 00:00:00.0000000 through 9999-12-31 23:59:59.9999999 (in UTC)
100 nanoseconds
8 to 10
Yes
Yes
Note Note
The Transact-SQL rowversion data type is not a date or time data type. timestamp is a deprecated synonym for rowversion.
The Transact-SQL date and time functions are listed in the following tables. For more information about determinism, see Deterministic and Nondeterministic Functions.

Functions That Get System Date and Time Values

All system date and time values are derived from the operating system of the computer on which the instance of SQL Server is running.

Higher-Precision System Date and Time Functions

SQL Server 2008 R2 obtains the date and time values by using the GetSystemTimeAsFileTime() Windows API. The accuracy depends on the computer hardware and version of Windows on which the instance of SQL Server is running. The precision of this API is fixed at 100 nanoseconds. The accuracy can be determined by using the GetSystemTimeAdjustment() Windows API.

Frequently Asked Questions - SQL Server Data Types





Comma-Delimited Output

DECLARE cCustomerIDs CURSOR FOR
    SELECT [CustomerID] FROM [dbo].[Customers] ORDER BY [CustomerID]
DECLARE @CustomerIDs    VARCHAR(8000)
DECLARE @CustomerID     VARCHAR(10)

OPEN cCustomerIDs
FETCH NEXT FROM cCustomerIDs INTO @CustomerID
WHILE @@FETCH_STATUS = 0
BEGIN
    SET @CustomerIDs = ISNULL(@CustomerIDs + ',', '') + @CustomerID
    FETCH NEXT FROM cCustomerIDs INTO @CustomerID
END

CLOSE cCustomerIDs
DEALLOCATE cCustomerIDs

SELECT @CustomerIDs AS CustomerIDs
GO
A sample output of this script is as follows, using just the first 10 Customer IDs from the Customers table.
CustomerIDs
-----------------------------------------------------------
ALFKI,ANATR,ANTON,AROUT,BERGS,BLAUS,BLONP,BOLID,BONAP,BOTTM


http://www.sql-server-helper.com/tips/comma-delimited-output.aspxhttp://www.sql-server-helper.com/tips/comma-delimited-output.aspx

Splash Screen in Silverlight 4

In this post I will show you how to create the custom splash screen for your Silverlight application. You have seen many software which use nice splash screen during loading of the software applications like Microsoft office, excel and many others. I have also created splash screen for my desktop applications which I have developed during my professional life. But I didn’t created any for the web application which I have developed in asp.net. But now the Silverlight provide the functionality of the splash screen. Splash screens provide something interesting and creative to increase anticipation and excitement for the application.
The splash screen is displayed while the .xap file is downloading when the .xap file is downloaded the splash screen disappear. So xaml file for the splash screen is not included in the Silverlight application rather the splash screen file which is of xaml is placed in the web application. When Silverlight application start the default splash screen which you can see is the shown in the image 1. Here you can see the spinning blue balls animation splash screen.

Image 1

Let us start with the our own splash screen , the splash screen which I have created is shown in the Image 2. In Image 2 you can see that I have created simple splash screen for my application which will show the percentage complete in digits so that user can see how much the application is downloaded.
Image 2

The code for the splash screen which is written in the file SilverlightLoader.xaml is place in the web project which you can see after downloading the source code. The code consist of the grid layout and then Border and the textblock which will shown the download complete in percentage. I have also set drop shadow effect for the border which contain the text block control.
The next step is to integrate the custom splash screen with the web application. You can see in the List 1 splashScreenSource property is used to reference the splash screen. By using this property, you can point to where a custom splash screen’s XAML is stored.

<div id="silverlightControlHost"> <object id="SilverlightPlugIn" data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%"> <param name="source" value="ClientBin/Custom Splash Screen.xap" /> <param name="onError" value="onSilverlightError" /> <param name="background" value="white" /> <param name="minRuntimeVersion" value="4.0.50401.0" /> <param name="splashScreenSource" value="SilverlightLoader.xaml" /> <param name="onSourceDownloadProgressChanged" value="appDownloadProgressChanged" /> <param name="autoUpgrade" value="true" /> <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50401.0" style="text-decoration: none"> <img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style: none" /> </a> </object> <iframe id="_sl_historyFrame" style="visibility: hidden; height: 0px; width: 0px; border: 0px"></iframe> </div>
List 1

The next step is to monitor the download progress of the .xap file for this you  need to wire up JavaScript event handlers to the onSourceDownload-ProgressChanged events defined by the plug-in. The definition of the changed event is listed in the List 2 as shown below. The onSourceDownloadProgressChanged event will fire any time the progress of a download has changed by 0.5 percent or more. If this event is triggered, you may access the total progress through the second parameter of the onSourceDownloadProgressChanged event. This parameter exposes a floating-point property called progress. The value of  this property is between 0.0 and 1.0, so you must multiply the value by 100 in order to convert the value to a percentage. When the progress has reached 1.0, the onSource- DownloadComplete event will fire.

function appDownloadProgressChanged(sender, args) { var host = document.getElementById("SilverlightPlugIn"); var percentTextBlock = host.content.findName("PercentageTextBlock"); percentTextBlock.Text = "" + Math.round(args.progress * 100) + "%"; }
List 2

Hope you get idea of how to integrate the custom splash screen with the silverlight application. I have created simple splash screen you can create animations during the download progress.

Note: As I have used the control of silverlight application like border, grid and text block I have added the reference of the PresentationCore and PresentationFramework in my web application.

I have not not included the silverlight application in the source project. As I was testing the output locally so I have embed large image files in the silverlight application so that size of the .xap file will  increase and it will take some time to download locally. 

Wednesday, April 6, 2011

Presenting Data with the DataGridView Control in .NET 2.0

Defining Custom Column and Cell Types

With the DataGridView, you are already leaps and bounds ahead of the DataGrid for presenting rich data because of the built-in column types that it supports out of the box. But there are always custom scenarios that you will want to support to display custom columns. Luckily, another thing the DataGridView makes significantly easier is plugging in custom column and cell types.
If you want to customize just the painting process of a cell, but you don’t need to add any properties or control things at the column level, you have an event-based option rather than creating new column and cell types. You can handle the CellPainting event and draw directly into the cell itself, and you can achieve pretty much whatever you want with the built-in cell types and some (possibly complex) drawing code. But if you want to be able to just plug your column or cell type in a reusable way with the same ease as using the built-in types, then you can derive your own column and cell types instead.
The model you should follow for plugging in custom column types matches what you have already seen for the built-in types: You need to create a column type and a corresponding cell type that the column will contain. You do this by simply inheriting from the base DataGridViewColumn and DataGridViewCell classes, either directly or indirectly, through one of the built-in types.
The best way to explain this in detail is with an example. Say I wanted to implement a custom column type that lets me display the status of the items represented by the grid’s rows. I want to be able to set a status using a custom-enumerated value, and cells in the column will display a graphic indicating that status based on the enumerated value set on the cell. To do this, I define a StatusColumn class and a StatusCell class (I disposed of the built-in type naming convention here of prefixing DataGridView on all the types because the type names get sooooooooooo long). I want these types to let me simply set the value of a cell, either programmatically or through data binding, to one of the values of a custom-enumerated type that I call StatusImage. StatusImage can take the values Green, Yellow, or Red, and I want the cell to display a custom graphic for each of those based on the value of the cell. Figure 6.7 shows the running sample application with this behavior.
06fig07.jpg Figure 6.7 Custom Column and Cell Type Example

Defining a Custom Cell Type

To achieve this, the first step is to define the custom cell type. If you are going to do your own drawing, you can override the protected virtual Paint method from the DataGridViewCell base class. However, if the cell content you want to present is just a variation on one of the built-in cell types, you should consider inheriting from one of them instead. That is what I did in this case. Because my custom cells are still going to be presenting images, the DataGridViewImageCell type makes a natural base class. My StatusCell class isn’t going to expose the ability to set the image at random, though; it is designed to work with enumerated values. I also want the cell value to be able to handle integers as long as they are within the corresponding numeric values of the enumeration, so that I can support the common situation where enumerated types are stored in a database as their corresponding integer values. The code in Listing 6.4 shows the StatusCell class implementation.

Example 6.4. Custom Cell Class

namespace CustomColumnAndCell
{
   public enum StatusImage
   {
      Green,
      Yellow,
      Red
   }

   public class StatusCell : DataGridViewImageCell
   {
      public StatusCell()
      {
         this.ImageLayout = DataGridViewImageCellLayout.Zoom;
      }

      protected override object GetFormattedValue(object value,
         int rowIndex, ref DataGridViewCellStyle cellStyle,
         TypeConverter valueTypeConverter,
         TypeConverter formattedValueTypeConverter,
         DataGridViewDataErrorContexts context)
      {

         string resource = "CustomColumnAndCell.Red.bmp";
         StatusImage status = StatusImage.Red;
         // Try to get the default value from the containing column
         StatusColumn owningCol = OwningColumn as StatusColumn;
         if (owningCol != null)
         {
            status = owningCol.DefaultStatus;
         }
         if (value is StatusImage || value is int)
         {
            status = (StatusImage)value;
         }
         switch (status)
         {
            case StatusImage.Green:
               resource = "CustomColumnAndCell.Green.bmp";
               break;            case StatusImage.Yellow:
               resource = "CustomColumnAndCell.Yellow.bmp";
               break;
            case StatusImage.Red:
               resource = "CustomColumnAndCell.Red.bmp";
               break;
            default:
               break;
         }
         Assembly loadedAssembly = Assembly.GetExecutingAssembly();
         Stream stream =
            loadedAssembly.GetManifestResourceStream(resource);
         Image img = Image.FromStream(stream);
         cellStyle.Alignment =
            DataGridViewContentAlignment.TopCenter;
         return img;
      }
   }
}
The first declaration in this code is the enumeration StatusImage. That is the value type expected by this cell type as its Value property. You can then see that the StatusCell type derives from the DataGridViewImageCell, so I can reuse its ability to render images within the grid. There is a default status field and corresponding property that lets the default value surface directly. The constructor also sets the ImageLayout property of the base class to Zoom, so the images are resized to fit the cell with no distortion.
The key thing a custom cell type needs to do is either override the Paint method, as mentioned earlier, or override the GetFormattedValue method as the StatusCell class does. This method will be called whenever the cell is rendered and lets you handle transformations from other types to the expected type of the cell. The way I have chosen to code GetFormattedValue for this example is to first set the value to a default value that will be used if all else fails. The code then tries to obtain the real default value from the containing column’s DefaultValue property if that column type is StatusColumn (discussed next). The code then checks to see if the current Value property is a StatusImage enumerated type or an integer, and if it is an integer, it casts the value to the enumerated type.
Once the status value to be rendered is determined, the GetFormattedValue method uses a switch-case statement to select the appropriate resource name corresponding to the image for that status value. You embed bitmap resources in the assembly by adding them to the Visual Studio project and setting the Build Action property on the file to Embedded Resource. The code then uses the GetManifestResourceStream m

http://osteele.com/archives/2004/08/web-mvc

ASP.NET MVC Pro’s and Con’s

In our current iteration of improving our software development strategy, ASP.NET WebForms simply doesn’t fit in with the new demands of being unit testable and flexible. It comes as no surprise that ASP.NET MVC has been getting all the headlines lately. Like many others, I’ve gotten the itch to try it out. In this post I’ll talk about what I believe are the main pro’s and con’s of the new style for building web applications.
Scale
PRO – No ViewState or "surprise crap"
In traditional ASP.NET WebForms, the luxury of pretending to behave like a Windows Form comes at a price. The ViewState is a reliable way of storing all of the state information for the form. Unfortunately, due to the limitations of the web, this data needs to be a giant string inside of a hidden form field. This ends up adding a substantial number of bytes to the page, making it slower and requiring extra bandwidth. Of course the ViewState is controllable, much like the dinosaurs in Jurassic Park.
Not only is the ViewState gone, but "mystery" generated HTML is also gone. You have strict control over the HTML. This gives you great power, but with great power comes great responsibility. Use it wisely, and you will have elegant XHTML output with no surprises. You need to really know your HTML, which in today’s web world is a prerequisite anyway.
PRO – Faster server-side
It’s hard to get any real performance data about MVC, but it’s been suggested that it’s potentially 8000 times faster. Supposedly it’s due to less processing since it simply processes a "template" instead of having to build a complicated control tree. Even if it’s twice as fast, or even marginally faster, that would be significant for popular sites, or give at least a slight boost to smaller sites.
PRO – Simplified model for multiple related views
One thing that I found much easier to do with MVC was to have multiple versions of a page that displayed the same data, but in a slightly different format. For example, on my RSS package tracking website, you can look at your tracking information in a full-featured desktop browser, a mobile browser, or an RSS reader. The data being displayed is always the same, but the actual rendered output was different. If I later want to make an iPhone specific version for example, I would simply make a new view, and use an existing controller action.
PRO – Unit testable
One of the biggest challenges with WebForms was that testing was difficult. Not only was the actual output not easy to test, but the code-behind would tend to be a place that would contain important code that would never get unit tested. With both MVC and WebForms, it’s best to keep your logic away from the page, but it’s not always easy or ideal. MVC makes it simple to unit test the logic that is specific to a page. To do so, you simply test the actions in your controllers, which are regular, easy to test classes.
CON – Difficult to convert an existing site
MVC is not only a framework in this case, but a style. It is possible to convert specific pages as needed, but the cost is high. The problem is that MVC is radically different, so the benefit of converting probably isn’t worth it for most of your existing pages.
If you decide to convert your site to MVC, you may also run into issues trying to maintain existing page addresses. The specific issue I’ve ran into is that routes cannot have a trailing slash. If you want to maintain existing URL’s that have trailing slashes, there is no way to have the built-in routing generate URL’s with a trailing slash. You may end up losing one of the big advantages that MVC has to offer.
CON – Not best for SEO out of the box
I’ve mentioned some of the SEO issues before, and all but the trailing slash issue have a reasonable workaround. The routing engine likes to allow multiple addresses to render the same page, instead of enforcing a single address for each page. Luckily, as Scott Hanselman mentions, you can use a URL rewrite engine to bend it to your will. I highly recommend spending some time writing intelligent rules that perform the necessary 301 redirects, because you don’t want to take chances with SEO (Search Engine Optimization).
CON – Challenges if you’re not running IIS7
It’s clear that the last couple of versions of IIS have been major improvements over their predecessors. IIS7 takes .NET integration to an entirely new level. There is already a good page that covers the challenges you’ll face if you’re not running IIS6. I’ll just list them here for brevity:
  • .NET needs to handle all page requests to ensure that the MVC pages will be processed. This leads to bad performance of static files.
  • HTTP Compression through IIS6 doesn’t work, because the MVC pages are dynamic.
  • The homepage gives a 404 when hosted on the root of a domai

http://www.ytechie.com/2008/10/aspnet-mvc-pros-and-cons.html