Sunday, 5 May 2013

ASP.NET - Validation Server Controls

Validation server controls are used to validate user-input. If the user-input does not pass validation, it will display an error message to the user.
Each validation control performs a specific type of validation (like validating against a specific value or a range of values).
By default, page validation is performed when a Button, ImageButton, or LinkButton control is clicked. You can prevent validation when a button control is clicked by setting the CausesValidation property to false.
The syntax for creating a Validation server control is:
< asp:control_name id="some_id" runat="server" />
In the following example we declare one TextBox control, one Button control, and one RangeValidator control in an .aspx file. If validation fails, the text "The value must be from 1 to 100!" will be displayed in the RangeValidator control:

Example

< html>
< body>

< form runat="server">
< p>Enter a number from 1 to 100:
< asp:TextBox id="tbox1" runat="server" />
< br /><br />
< asp:Button Text="Submit" runat="server" />
< /p>

< p>
< asp:RangeValidator
ControlToValidate="tbox1"
MinimumValue="1"
MaximumValue="100"
Type="Integer"
Text="The value must be from 1 to 100!"
runat="server" />
< /p>
< /form>

< /body>
< /html>

Web Server Controls

Like HTML server controls, Web server controls are also created on the server and they require a runat="server" attribute to work. However, Web server controls do not necessarily map to any existing HTML elements and they may represent more complex elements.
The syntax for creating a Web server control is:
< asp:control_name id="some_id" runat="server" />
Web Server ControlDescription
AdRotatorDisplays a sequence of images
ButtonDisplays a push button
CalendarDisplays a calendar
CalendarDayA day in a calendar control
CheckBoxDisplays a check box
CheckBoxListCreates a multi-selection check box group
DataGridDisplays fields of a data source in a grid
DataListDisplays items from a data source by using templates
DropDownListCreates a drop-down list
HyperLinkCreates a hyperlink
ImageDisplays an image
ImageButtonDisplays a clickable image
LabelDisplays static content which is programmable (lets you apply styles to its content)
LinkButtonCreates a hyperlink button
ListBoxCreates a single- or multi-selection drop-down list
ListItemCreates an item in a list
LiteralDisplays static content which is programmable(does not let you apply styles to its content)
PanelProvides a container for other controls
PlaceHolderReserves space for controls added by code
RadioButtonCreates a radio button
RadioButtonListCreates a group of radio buttons
BulletedListCreates a list in bullet format
RepeaterDisplays a repeated list of items bound to the control
StyleSets the style of controls
TableCreates a table
TableCellCreates a table cell
TableRowCreates a table row
TextBoxCreates a text box
XmlDisplays an XML file or the results of an XSL transform

Friday, 3 May 2013

C# removing duplicate records from DataTable

/// <summary>
/// Remove duplicate records from data table
/// </summary>
/// <param name="table">DataTable for removing duplicate records</param>
/// <param name="DistinctColumn">Column to check for duplicate values or records</param>
/// <returns></returns>
public DataTable RemoveDuplicateRows(DataTable table, string DistinctColumn)
{
try
{
ArrayList UniqueRecords = new ArrayList();
ArrayList DuplicateRecords = new ArrayList();
// Check if records is already added to UniqueRecords otherwise,
// Add the records to DuplicateRecords
foreach(DataRow dRow in table.Rows)
{
if (UniqueRecords.Contains(dRow[DistinctColumn]))
DuplicateRecords.Add(dRow);
else
UniqueRecords.Add(dRow[DistinctColumn]);
}
// Remove dupliate rows from DataTable added to DuplicateRecords
foreach (DataRow dRow in DuplicateRecords)
{
table.Rows.Remove(dRow);
}
// Return the clean DataTable which contains unique records.
return table;
}
catch (Exception ex)
{
return null;
}
}

TextBox AutoComplete with ASP.NET and jQuery UI

The Autocomplete widget is one of the widgets provided in jQuery UI and provides suggestions while you type into the field. jQuery UI is a free widget and interaction library built on top of the jQuery JavaScript Library, that you can use to build highly interactive web applications.
[Note: If you are using jQuery with ASP.NET Controls, you may find my EBook 51 Recipes with jQuery and ASP.NET Controls helpful]
Let us first glance through the entire code with the jQuery UI AutoComplete widget added to the TextBox (tb)
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>AutoComplete Box with jQuery</title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function() {
$(".tb").autocomplete({
source: function(request, response) {
$.ajax({
url: "EmployeeList.asmx/FetchEmailList",
data: "{ 'mail': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function(data) { return data; },
success: function(data) {
response($.map(data.d, function(item) {
return {
value: item.Email
}
}))
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="demo">
<div class="ui-widget">
<label for="tbAuto">Enter Email: </label>
<asp:TextBox ID="tbAuto" class="tb" runat="server">
</asp:TextBox>
</div>
</div>
</form>
</body>
</html>
Now before explaining to you how this code functions, let us go through the WebService first. Assuming you have downloaded the source code and are looking at the EmployeeList.cs/vb file, you will observe that the method has been decorated with the [WebMethod] attribute to allow calls from client script
C#
[WebMethod]
public List<Employee> FetchEmailList(string mail)
{
var emp = new Employee();
var fetchEmail = emp.GetEmployeeList()
.Where(m => m.Email.ToLower().StartsWith(mail.ToLower()));
return fetchEmail.ToList();
}
VB.NET
<WebMethod>
Public Function FetchEmailList(ByVal mail As String) As List(Of Employee)
Dim emp = New Employee()
Dim fetchEmail = emp.GetEmployeeList().Where(Function(m) m.Email.ToLower().StartsWith(mail.ToLower()))
Return fetchEmail.ToList()
End Function
Here the FetchEmailList(string mail) method calls the GetEmployeeList() method on the Employee class which returns a List<Employee>. We then filter the list using the filter string (mail) passed from the UI and then return the list of emails that match the filter string.
Note: If a method is not marked with [ScriptMethod] attribute, the method will be called by using the HTTP POST command and the response will be serialized as JSON.
Going back to code we saw above, observe how the TextBox is wired to the AutoComplete widget.
$(function() {
$(".tb").autocomplete({
source: function(request, response) {
$.ajax({
// consume the webservice
},
minLength: 2
});
});
To consume this web service using jQuery $.ajax(), two important points to note is that the request should be a POST request and the request’s content-type must be ‘application/json; charset=utf-8’. The code structure of the $.ajax() call looks similar to the following:
$.ajax({
url: "EmployeeList.asmx/FetchEmailList",
data: "{ 'mail': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function(data) {
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
}
});
Observe how the parameter (that the user types in the textbox) is passed to the webservice using data: "{ 'mail': '" + request.term + "' }" .You may need to add additional checks to format the data or validate it. Once the Ajax method is completed, the success function will be executed and the matching results (Email) will be returned using the following code.
dataFilter: function(data) { return data; },
success: function(data) {
response($.map(data.d, function(item) {
return {
value: item.Email
}
}))
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}

Thursday, 2 May 2013

Rotate Ads using jQuery and ASP.NET AdRotator Control

We will first create a simple adrotator control and then add some jQuery logic to it.
Step 1: Open VS 2008/2010. Click File > New > Website. Choose ASP.NET Website from the list of installed template, choose target platform as .NET Framework 2.0/3.5/4.0, choose the desired language and enter the location where you would like to store the website on your FileSystem (C:\VS 2010 Projects\AdRotatorjQuery. After typing the location, click OK.
Step 2: Now create some banners images to test out the adrotator functionality and drop them in the images folder of your project. I have designed three 200 * 200 png banners (adone, adtwo and adthree). You can find the images in the source code of this article.
Step 3: The AdRotator control can retrieve the list of advertisements from either a XML file or from the database. To keep things simple, I will be using an XML file. So the next step is to create the advertisement file. I prefer to create this file in the App_Data folder to take advantage of the security this folder provides. To do so, right click the App_Data folder > Add New Item > ‘XML File’ > Rename it to ads.xml and click Add. Now add the following contents to the ‘ads.xml’ file:
<?xml version="1.0" encoding="utf-8" ?>
<Advertisements>
<Ad>
<ImageUrl>~/images/adone.png</ImageUrl>
<NavigateUrl>http://www.dotnetcurry.com</NavigateUrl>
<AlternateText>DotNetCurry Home Page</AlternateText>
<Impressions>30</Impressions>
<Keyword>small</Keyword>
</Ad>
<Ad>
<ImageUrl>~/images/adtwo.png</ImageUrl>
<NavigateUrl>http://www.sqlservercurry.com</NavigateUrl>
<AlternateText>SQLServerCurry Home Page</AlternateText>
<Impressions>30</Impressions>
<Keyword>small</Keyword>
</Ad>
<Ad>
<ImageUrl>~/images/adthree.png</ImageUrl>
<NavigateUrl>http://www.devcurry.com</NavigateUrl>
<AlternateText>DevCurry Home Page</AlternateText>
<Impressions>40</Impressions>
<Keyword>small</Keyword>
</Ad>
</Advertisements>
Step 4: Our next step is to add the AdRotator control and bind it to the advertisement file. Drag and drop an AdRotator control from the toolbox to the Default.aspx. To bind the AdRotator to our XML file, we will make use of the ‘AdvertisementFile’ property of the AdRotator control as shown below:
<div class="ads">
<asp:AdRotator
id="adr"
AdvertisementFile="~/App_Data/Ads.xml"
KeywordFilter="small"
Runat="server" />
</div>
Note: The ‘KeywordFilter’ property enables you to filter advertisement using a keyword. If your Advertisement file contains different kinds of ads (banner, leaderboard, skyscraper etc.), you can use this property to filter out different ads on different sections of the page. If you observe, the ads.xml file also contains a property called ‘Keyword’ which binds that ad with the AdRotator that contains the same KeywordFilter, in our case ‘small’.
So far, we have a fully functional adrotator control which displays a new ad, when you refresh the page. Let’s see how we can use jQuery to rotate ads without page refresh.
Using jQuery to Rotate ads in the ASP.NET AdRotator without Refreshing the Page
Step 5: Time for some jQuery magic! Add the following jQuery code in the <head> section of the page
<head runat="server">
<title>Rotating ads using ASP.NET AdRotator and jQuery</title>
<script type="text/javascript"
src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function () {
setInterval(function () {
$("#adr").load(location.href + " #adr", "" + Math.random() + "");
}, 4000);
});
</script>
</head>
In the code shown above, we are doing a partial page update using jQuery. Using the setInterval function, we call the jQuery load() api, to fetch data after every 4 seconds.
The jQuery load() function allows us to specify a portion of the remote document to be inserted. This is achieved with a special syntax for the url parameter. If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded.
That’s what we are doing in this piece of code. Observe the space before “ #adr” in the load function, which turns it into a jQuery selector.
$("#adr").load(location.href + " #adr", "" + Math.random() + "");
In an ASP.NET Master page, use this piece of code
$('[id$=adr]').load(location.href + " #[id$=adr]", "" + Math.random() + "");
When this method executes, jQuery parses the returned document to find the #adr element and inserts the element with its new content, discarding the rest of the document. That’s how we see a new ad at regular intervals.
Note: We have used Math.random() here so that IE does not treat it as similar requests and cache it. If we do not do this, you will never see a new image loading in IE. Using Firebug, here’s what each request looks like.
image_2
Here’s an output of what the page will look like. I have printed the current time in a label control to be sure that the entire page is not being refreshed.
AdRotator

How to style the ASP.NET GridView using the jQuery Theme Switcher Widget

Step 1: Create an ASP.NET application and add a GridView to it. Now bind the GridView to some datasource. The source code contains a sample with the GridView bound to the SQLDataSource control
Step 2: Now add some references to the jQuery CSS library, jQuery Library, jQuery UI library as shown below:
Step 3: Create a folder called ‘Scripts’ in your application and download the jQuery Theme Switcher Tool in it. Add a reference to this script file in your application. You may be tempted to hotlink the theme tool directly, but do not do so.
The solution is to download the theme switcher JavaScript code and images to your own server and modify the code to point to the images you downloaded. Read more here. For demonstration purposes, I have downloaded the first four images and have kept in the source code of this article.
Step 4: Now create a div called ‘themewidget’ and call the theme switcher tool on this Div using the following code:
Step 5: This is the most important part. The ASP.NET GridView does not render the <thead>, <tbody> <tfoot> tags by default. Use the following code to make it generate these accessibility tags
If you observe, we have set some CSS classes like the ui-widget-content and ui-widget-header on the GridView and its header row. These classes belong to the jQuery UI CSS Framework which includes classes that cover a wide array of common user interface needs, and can be manipulated using jQuery UI ThemeRoller.
Note: In our application, we have only used the Widget Containers classes on the Table. However there are many more classes and you can use them as required.
That’s it. Now run the application and you should see the following:
Click on the ‘Switch Theme’ dropdown to select a theme of your choice (say UI Lightness)
and the GridView will be stylized as shown below:

jQuery with ASP.NET – clone textbox example

Step 1: Create a Master Page (MasterPage.master) and add a reference to the jQuery Library. Now create a folder called ‘Scripts’ and download the latest jQuery library into this folder. Now add references to any CSS files, if any. Create a separate folder to store all CSS and images files. You should always make it a habit to keep your resources in separate folders for better maintainability. The code should look similar to the following:
Step 2: Now create a Content Page called ‘Default.aspx’ and add two TextBox controls to this page as shown below:
Step 3: Now in the ‘Scripts’ folder, create a textboxclone.js file and add the following code in it.
Using the code shown above, as the user types in the first TextBox, we retrieve the value of the first TextBox and set it to the value of the second TextBox. Note: Since we are capturing the keyup event, whenever the user pastes text in the first textbox using Ctrl+v, the contents are cloned into the second textbox, This is however not true when the user right clicks the textbox and chooses paste from the context menu
The last step is to reference this JavaScript file (textboxclone.js) in your Content Page as shown below:
You must be wondering why did we add a link to the textboxclone.js from a Content page rather than doing it from a Master Page. The reason is, if we had referenced the textboxclone.js file in the MasterPage directly, the code would be downloaded for every content page, even if it was not needed. Referencing it from a Content Page makes sure that the resource is used only when this content page is requested. That’s it. Run the code and you will see the textbox text cloning in action.

Enumerable.SequenceEqual Method (IEnumerable, IEnumerable)

The following code examples demonstrate how to use SequenceEqual(IEnumerable, IEnumerable) to determine whether two sequences are equal. In the first two examples, the method determines whether the compared sequences contain references to the same objects. In the third and fourth examples, the method compares the actual data of the objects within the sequences. In this example the sequences are equal.

      class Pet
      {
         public string Name { get; set; }
         public int Age { get; set; }
      }

      public static void SequenceEqualEx1()
      {
         Pet pet1 = new Pet { Name = "Turbo", Age = 2 };
         Pet pet2 = new Pet { Name = "Peanut", Age = 8 };

         // Create two lists of pets.
         List<Pet> pets1 = new List<Pet> { pet1, pet2 };
         List<Pet> pets2 = new List<Pet> { pet1, pet2 };

         bool equal = pets1.SequenceEqual(pets2);

         outputBlock.Text += String.Format(
             "The lists {0} equal.",
             equal ? "are" : "are not") + "\n";
      }

      /* This code produces the following output: The lists are equal. */


The following code example compares two sequences that are not equal. Note that the sequences contain identical data, but because the objects that they contain have different references, the sequences are not considered equal.


public class Product : IEquatable<Product>
{ public string Name { get; set; }    
public int Code { get; set; }    
public bool Equals(Product other)    
{        
//Check whether the compared object is null.        
if (Object.ReferenceEquals(other, null)) return false;        
//Check whether the compared object references the same data.
if (Object.ReferenceEquals(this, other)) return true;        
//Check whether the products' properties are equal.        
return Code.Equals(other.Code) && Name.Equals(other.Name);    
}    
// If Equals() returns true for a pair of objects
// then GetHashCode() must return the same value for these objects.
public override int GetHashCode()    
{
//Get hash code for the Name field if it is not null.        
int hashProductName = Name == null ? 0 : Name.GetHashCode();        
//Get hash code for the Code field.        
int hashProductCode = Code.GetHashCode();
//Calculate the hash code for the product.        
return hashProductName ^ hashProductCode; } }

After you implement this interface, you can use sequences of Product objects in the SequenceEqual<TSource>(IEnumerable<TSource>, IEnumerable<TSource>) method, as shown in the following example.

        Product[] storeA =
{ new Product { Name = "apple", Code = 9 },                               
new Product { Name = "orange", Code = 4 }
 };
Product[] storeB =
{ new Product { Name = "apple", Code = 9 },
  new Product { Name = "orange", Code = 4 }
 };
bool equalAB = storeA.SequenceEqual(storeB);        
outputBlock.Text += "Equal? " + equalAB + "\n";        

/* This code produces the following output: Equal? True */

List Empty Tables in SQL Server


Here’s a simple query to list all empty tables in your SQL Server database that uses a Dynamic Management View called dm_db_partition_stats which returns page and row-count information for every partition in the current database.

;WITH EmptyRows AS
(
SELECT SUM(row_count) AS [TotalRows],
OBJECT_NAME(OBJECT_ID) AS TableName
FROM sys.dm_db_partition_stats
WHERE index_id = 0 OR index_id = 1
GROUP BY OBJECT_ID
)
SELECT * FROM EmptyRows
WHERE [TotalRows] = 0


OUTPUT

image

Note that the results from the view is only approximate. If there are any active transactions that are inserting or deleting rows, the count may not include it.

SQL Server Management Objects 2008 (SMO) New Features

MSDN defines SMO as - SQL Server Management Objects (SMO) is a collection of objects that are designed for programming all aspects of managing Microsoft SQL Server. In this article we will practically explore some features of SQL Server Management Objects.
To start with, let’s create a ‘Windows Application’ using Visual Studio and name the application as ‘SMOExamples’ as shown below –

SQL Server SMO app

Now let’s add the following references to our project.
  1. Microsoft.SqlServer.ConnectionInfo.dll
  2. Microsoft.SqlServer.Smo.dll
  3. Microsoft.SqlServer.SmoExtended.dll
  4. Microsoft.SqlServer.SqlEnum.dll
  5. Microsoft.SqlServer.Management.Sdk.Sfc.dll


All these references can be found in the path – ‘C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies’.

Now let’s design our windows form as shown below –

SMO Examples


Declare an object which will make a connection to our SQL Server instance. For this, we will use a class called ‘Server’ as shown below –


Server srv = new Server(Environment.MachineName);


Now to test the connection to the SQL Server, let’s write the following code on the Form Load event as shown below –

SMO test connection


Now let’s create a Database and Table with the name ‘SMOExample’ and ‘SMOTable’ respectively by writing the following code on the click event of ‘Create Database And Table’ button –

SMO Create Database


For creating a database, we have used a class called ‘Database’ which takes two parameters in the constructor. First one is the SQL Server instance in which we have to create a database. Second is the database name.


Now let’s create a script for all the tables available in our database. Write bee following code on the click event of ‘Generate Script’ button –

SQL Server SMO Generate Tables


For generating the script files we are using a ‘Scripter’ class.


Now let’s write the code to take a backup of the complete database. Write the following code on the click event of ‘Backup Database’ button –

SQL Server SMO BackUp Database


To take a backup of the database, we are using a ‘Backup’ class and to decide what will be the device of backup, we are using ‘BackupDeviceItem’ class.


Now the last thing we will explore is how to verify the backup, which is taken before we restore it to another server/same server. Write the following code on the ‘Verify Backup’ button –

SQL Server SMO Verify Database


Now run your project. This will show you the date and time created for ‘AdventureWorks’ database as shown below –

clip_image001[6]

Now let’s click the button ‘Create Database and Table’ and observe the results in SQL Server Management
Studio Object Explorer –

clip_image002[10]

Now click on the button ‘Generate Script’. Go to ‘C:\’ and verify the script file –

clip_image004

Finally click the button ‘Backup Database’ and check your ‘C:\’ drive. Your backup file should have been created. Similarly click on ‘Verify Backup’ button and it will show you a success message.