Tuesday, July 6, 2010

Introduction to XAML

 

XAML stands for Extensible Application Markup Language. Its a simple language based on XML to create and initialize .NET objects with hierarchical relations. Although it was originally invented for WPF it can by used to create any kind of object trees.

Today XAML is used to create user interfaces in WPF, Silverlight, declare workflows in WF and for electronic paper in the XPS standard.

All classes in WPF have parameterless constructors and make excessive usage of properties. That is done to make it perfectly fit for XML languages like XAML.

 

Advantages of XAML

All you can do in XAML can also be done in code. XAML ist just another way to create and initialize objects. You can use WPF without using XAML. It's up to you if you want to declare it in XAML or write it in code. Declare your UI in XAML has some advantages:

  • XAML code is short and clear to read
  • Separation of designer code and logic
  • Graphical design tools like Expression Blend require XAML as source.
  • The separation of XAML and UI logic allows it to clearly separate the roles of designer and developer.

 

XAML vs. Code

  <StackPanel>
<TextBlock Margin="20">Welcome to the World of XAML</TextBlock>
<Button Margin="10" HorizontalAlignment="Right">OK</Button>
</StackPanel>
   

The same expressed in C# will look like this:


// Create the StackPanel
StackPanel stackPanel = new StackPanel();
this.Content = stackPanel;   // Create the TextBlock
TextBlock textBlock = new TextBlock();
textBlock.Margin = new Thickness(10);
textBlock.Text = "Welcome to the World of XAML";
stackPanel.Children.Add(textBlock);   // Create the Button
Button button = new Button();
button.Margin= new Thickness(20);
button.Content = "OK";
stackPanel.Children.Add(button);   

As you can see is the XAML version much shorter and clearer to read. And that's the power of XAMLs expressiveness.

 

Properties as Elements


Properties are normally written inline as known from XML <Button Content="OK" />. But what if we want to put a more complex object as content like an image that has properties itself or maybe a whole grid panel? To do that we can use the property element syntax. This allows us to extract the property as an own child element.

<Button>
<Button.Content>
<Image Source="Images/OK.png" Width="50" Height="50" />
</Button.Content>
</Button> 

 


Markup Extensions


Markup extensions are dynamic placeholders for attribute values in XAML. They resolve the value of a property at runtime. Markup extensions are surrouded by curly braces (Example: Background="{StaticResource NormalBackgroundBrush}"). WPF has some built-in markup extensions, but you can write your own, by deriving from MarkupExtension. These are the built-in markup extensions:


  • Binding
    To bind the values of two properties together.
  • StaticResource
    One time lookup of a resource entry
  • DynamicResource
    Auto updating lookup of a resource entry
  • TemplateBinding
    To bind a property of a control template to a dependency property of the control
  • x:Static
    Resolve the value of a static property.
  • x:Null
    Return null
The first identifier within a pair of curly braces is the name of the extension. All preciding identifiers are named parameters in the form of Property=Value. The following example shows a label whose Content is bound to the Text of the textbox. When you type a text into the text box, the text property changes and the binding markup extension automatically updates the content of the label.
<TextBox x:Name="textBox"/>
<Label Content="{Binding Text, ElementName=textBox}"/>

 


Namespaces


At the beginning of every XAML file you need to include two namespaces.
The first is http://schemas.microsoft.com/winfx/2006/xaml/presentation. It is mapped to all wpf controls in System.Windows.Controls.
The second is http://schemas.microsoft.com/winfx/2006/xaml it is mapped to System.Windows.Markup that defines the XAML keywords.
The mapping between an XML namespace and a CLR namespace is done by the XmlnsDefinition attribute at assembly level. You can also directly include a CLR namespace in XAML by using the clr-namespace: prefix.


<Window xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”>
</Window> 

Friday, July 2, 2010

Difference between Silverlight and WPF

 

Silverlight and Windows Presentation Foundation (WPF) are 2 different products from Microsoft, but has lot of overlap. Silverlight is a sub set of WPF in terms of features and functionality.

Silverlight is a Microsoft technology, competing with Adobes Flash and is meant for developing rich browser based internet applications.

Silverlight is on the web. What you create is an application that can be hosted either in an html page or an asp.net page. To watch it from your browser it requires to have installed in your browser the Silverlight plug-in. Silverlight uses very fewer libraries than WPF does, and that's pretty logical because Silverlight's CLR is in the plug-in which is about 5-10 MB.

WPF is a Microsoft technology meant for developing enhanced graphics applications for desktop platform. In addition, WPF applications can be hosted on web browsers which offers rich graphics features for web applications. Web Browser Applications (WBA) developed on WPF technology uses XAML to host user interface for browser applications. XAML stands for eXtended Application Markup Language which is a new declarative programming model from Microsoft. XAML files are hosted as discrete files in the Web server, but are downloaded to the browsers and converted to user interface by the .NET runtime in the client browsers.

WPF runs on .NET runtime and developers can take advantage of the rich .NET Framework and WPF libraries to build really cool windows applications. WPF supports 3-D graphics, complex animations, hardware acceleration etc.

WPF is for desktop applications- you create an .exe file when you build WPF applications. To run a WPF exe requires you to have Framework 3 or higher on your pc.

WPF and Silverlight though use the same logic in development and the same technology.

Summary:

1. Silverlight is simply a subset of WPF.
2. Silverlight is meant to be used online, while WPF is for local use.
3. You can use Silverlight applications regardless of the operating system you use, while WPF applications are restricted to later versions of the Windows operating system.
4. Silverlight lacks access to local resources, while WPF can utilize local resources.
5. Silverlight only has perspective 3D support, while WPF is capable of full 3D images.

Monday, June 28, 2010

WCF : Developing a basic WCF Client and Service

 

  • Create a blank solution in VS 2005. To get better understanding of code we will not use WCF project templates installed with WCF sdk.
  • Add a class library
  • Add reference to System.Service Model assembly and namespace.
  • Create interface .. apply Attributes
namespace MathUtility
{
[ServiceContract]
public interface IMath
{
[OperationContract]
int AddNumbers(int x, int y);
[OperationContract]
int SubstractNumbers(int from, int number);
}
}


  • Create Service Class from interface. Implement Interface.

namespace MathUtility
{
public class MathService : IMath
{
public int AddNumbers(int x, int y)
{
return (x + y);
}

public int SubstractNumbers(int from , int number)
{
return (from - number);
}
}
}


  • Now we need to host this as a service. We will host in a console application.

  • Add a console application project. Add Application Configuration file to the project.

  • Add Reference to System.ServiceModel.

  • Modify the app.config file as following.

<configuration>
<!-- This Section is exclusive for WCF configuration for both service and client -->
<system.serviceModel>
<!-- This section is to declare services hosted using this cofig file -->
<services>
<!-- This section declares individual service. name=type name which implements service contract -->
<!-- behaviorConfiguration = name of bahavior config which we will define later -->
<service name="MathUtility.MathService" behaviorConfiguration="MathServiceBehavior">
<host>
<!-- base address of the hosted service to which clients will connect-->
<baseAddresses>
<add baseAddress="http://MyMachine:8080/WCFServices/MathService" />
</baseAddresses>
</host>
<!-- the actual address where service is exposed -->
<endpoint address="" binding="wsHttpBinding" contract="MathUtility.IMath"></endpoint>
<!-- The address where metadata is exposed and will be used by Svcutil.exe to generate client classes -->
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<!-- The behavior which we mentioned above in <service> section-->
<behavior name="MathServiceBehavior">
<!-- Exposing metadata on http. Not mandatory for fuctioning of service if client already has metadata-->
<serviceMetadata httpGetEnabled="True"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>


  • Change host app as following.

namespace MathServiceHost
{
class Program
{
static void Main(string[] args)
{
try
{
ServiceHost serviceHost = new ServiceHost(typeof(MathService));
serviceHost.Open();
Console.WriteLine("The Math Service is running");
Console.WriteLine("Press <ENTER> to stop the service.");
Console.ReadLine();
serviceHost.Close();
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
}
}
}


  • Start the service.

  • Use Svcutil.exe to generate the client classes and app.config file.


>svcutil /language:C# /config:app.config http://MyMachine:8080/WCFServices/MathService/mex



  • Create a new console project. add generated .cs and app.config.

  • add reference to System.ServiceModel and give namespace to generated .cs file

  • You may have to remove identity tag from client config file if it has been generated. We will cover the reasons later.

  • Use the generated classes as follows :

namespace MathClient
{
class Program
{
static void Main(string[] args)
{
try
{
MathClient mathClient = new MathClient();
Console.WriteLine(mathClient.AddNumbers(1, 1));
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.InnerException.Message);
}
}
}
}


  • Pls leave a comment to this post if you face any issue in executing the above tutorial.

What's New in the .NET Framework 4

 

This topic contains information about key features and improvements in the .NET Framework version 4. This topic does not provide comprehensive information about all new features and is subject to change. 

The .NET Framework 4 introduces an improved security model. Other new features and improvements in the .NET Framework 4 are described in the following sections:

Application Compatibility and Deployment


The .NET Framework 4 is highly compatible with applications that are built with earlier .NET Framework versions, except for some changes that were made to improve security, standards compliance, correctness, reliability, and performance.

The .NET Framework 4 does not automatically use its version of the common language runtime to run applications that are built with earlier versions of the .NET Framework. To run older applications with .NET Framework 4, you must compile your application with the target .NET Framework version specified in the properties for your project in Visual Studio, or you can specify the supported runtime with the <supportedRuntime> Element in an application configuration file.

If your application or component does not work after .NET Framework 4 is installed, please submit a bug on the Microsoft Connect Web site. You can test compatibility as described in the .NET Framework 4 Application Compatibility topic and learn about new features by using the Visual Studio 2010 and .NET Framework 4 Walkthroughs. For additional information and known migration issues, visit the .NET Framework Compatibility blog

The following sections describe deployment improvements.

Client Profile

The .NET Framework 4 Client Profile supports more platforms than in previous versions and provides a fast deployment experience for your applications. Several new project templates now target the Client Profile by default. For more information, see .NET Framework Client Profile.

In-Process Side-by-Side Execution

This feature enables an application to load and start multiple versions of the .NET Framework in the same process. For example, you can run applications that load add-ins (or components) that are based on the .NET Framework 2.0 SP1 and add-ins that are based on the .NET Framework 4 in the same process. Older components continue to use the older .NET Framework version, and new components use the new .NET Framework version. For more information, see In-Process Side-by-Side Execution.

Core New Features and Improvements


The following sections describe new features and improvements provided by the common language runtime and the base class libraries.

Diagnostics and Performance

Earlier versions of the .NET Framework provided no way to determine whether a particular application domain was affecting other application domains, because the operating system APIs and tools, such as the Windows Task Manager, were precise only to the process level. Starting with the .NET Framework 4, you can get processor usage and memory usage estimates per application domain.

You can monitor CPU and memory usage of individual application domains. Application domain resource monitoring is available through the managed and native hosting APIs and event tracing for Windows (ETW). When this feature has been enabled, it collects statistics on all application domains in the process for the life of the process. See the new AppDomain.MonitoringIsEnabled property.

You can now access the ETW events for diagnostic purposes to improve performance. For more information, see CLR ETW Events and Controlling .NET Framework Logging. Also see Performance Counters and In-Process Side-By-Side Applications.

The System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptionsAttribute attribute enables managed code to handle exceptions that indicate corrupted process state.

Globalization

The .NET Framework 4 provides new neutral and specific cultures, updated property values, improvements in string handling, and other improvements. For more information, see What's New in Globalization and Localization.

Garbage Collection

The .NET Framework 4 provides background garbage collection. This feature replaces concurrent garbage collection in previous versions and provides better performance. For more information, see Fundamentals of Garbage Collection.

Code Contracts

Code contracts let you specify contractual information that is not represented by a method's or type's signature alone. The new System.Diagnostics.Contracts namespace contains classes that provide a language-neutral way to express coding assumptions in the form of preconditions, postconditions, and object invariants. The contracts improve testing with run-time checking, enable static contract verification, and support documentation generation. For more information, see Code Contracts.

Design-Time-Only Interop Assemblies

You no longer have to ship primary interop assemblies (PIAs) to deploy applications that interoperate with COM objects. In the .NET Framework 4, compilers can embed type information from interop assemblies, selecting only the types that an application (for example, an add-in) actually uses. Type safety is ensured by the common language runtime. See Using COM Types in Managed Code and Walkthrough: Embedding Type Information from Microsoft Office Assemblies (C# and Visual Basic).

Dynamic Language Runtime

The dynamic language runtime (DLR) is a new runtime environment that adds a set of services for dynamic languages to the CLR. The DLR makes it easier to develop dynamic languages to run on the .NET Framework and to add dynamic features to statically typed languages. To support the DLR, the new System.Dynamic namespace is added to the .NET Framework.

The expression trees are extended with new types that represent control flow, for example, System.Linq.Expressions.LoopExpression and System.Linq.Expressions.TryExpression. These new types are used by the dynamic language runtime (DLR) and not used by LINQ.

In addition, several new classes that support the .NET Framework infrastructure are added to the System.Runtime.CompilerServices namespace. For more information, see Dynamic Language Runtime Overview.

Covariance and Contravariance

Several generic interfaces and delegates now support covariance and contravariance. For more information, see Covariance and Contravariance in Generics.

BigInteger and Complex Numbers

The new System.Numerics.BigInteger structure is an arbitrary-precision integer data type that supports all the standard integer operations, including bit manipulation. It can be used from any .NET Framework language. In addition, some of the new .NET Framework languages (such as F# and IronPython) have built-in support for this structure.

The new System.Numerics.Complex structure represents a complex number that supports arithmetic and trigonometric operations with complex numbers.

Tuples

The .NET Framework 4 provides the System.Tuple class for creating tuple objects that contain structured data. It also provides generic tuple classes to support tuples that have from one to eight components (that is, singletons through octuples). To support tuple objects that have nine or more components, there is a generic tuple class with seven type parameters and an eighth parameter of any tuple type. 

File System Enumeration Improvements

New file enumeration methods improve the performance of applications that access large file directories or that iterate through the lines in large files. For more information, see How to: Enumerate Directories and Files.

Memory-Mapped Files

The .NET Framework now supports memory-mapped files. You can use memory-mapped files to edit very large files and to create shared memory for interprocess communication.

64-Bit Operating Systems and Processes

You can identify 64-bit operating systems and processes with the Environment.Is64BitOperatingSystem and Environment.Is64BitProcess properties.

You can specify a 32-bit or 64-bit view of the registry with the Microsoft.Win32.RegistryView enumeration when you open base keys.

Other New Features

The following list describes additional new capabilities, improvements, and conveniences. Several of these are based on customer suggestions.

 

Managed Extensibility Framework


The Managed Extensibility Framework (MEF) is a new library in the .NET Framework 4 that helps you build extensible and composable applications. MEF enables you to specify points where an application can be extended, to expose services to offer to other extensible applications and to create parts for consumption by extensible applications. It also enables easy discoverability of available parts based on metadata, without the need to load the assemblies for the parts. For more information, see Managed Extensibility Framework Overview and Managed Extensibility Framework. For a list of the MEF types, see the System.ComponentModel.Composition namespace.

 

Parallel Computing


The .NET Framework 4 introduces a new programming model for writing multithreaded and asynchronous code that greatly simplifies the work of application and library developers. The new model enables developers to write efficient, fine-grained, and scalable parallel code in a natural idiom without having to work directly with threads or the thread pool. The new System.Threading.Tasks namespace and other related types support this new model. Parallel LINQ (PLINQ), which is a parallel implementation of LINQ to Objects, enables similar functionality through declarative syntax. For more information, see Parallel Programming in the .NET Framework.

 

Networking


Networking improvements include the following:

 

Web


ASP.NET version 4 introduces new features in the following areas:

  • Core services, including a new API that lets you extend caching, support for compression for session-state data, and a new application preload manager (autostart feature).
  • Web Forms, including more integrated support for ASP.NET routing, enhanced support for Web standards, updated browser support, new features for data controls, and new features for view state management.
  • Web Forms controls, including a new Chart control.
  • MVC, including new helper methods for views, support for partitioned MVC applications, and asynchronous controllers.
  • Dynamic Data, including support for existing Web applications, support for many-to-many relationships and inheritance, new field templates and attributes, and enhanced data filtering.
  • Microsoft Ajax, including additional support for client-based Ajax applications in the Microsoft Ajax Library.
  • Visual Web Developer, including improved IntelliSense for JScript, new auto-complete snippets for HTML and ASP.NET markup, and enhanced CSS compatibility.
  • Deployment, including new tools for automating typical deployment tasks.
  • Multi-targeting, including better filtering for features that are not available in the target version of the .NET Framework.

For more information about these features, see What's New in ASP.NET 4 and Visual Web Developer.

 

Client


Windows Presentation Foundation (WPF) version 4 contains changes and improvements in the following areas:

  • New controls, including Calendar, DataGrid, and DatePicker.
  • VisualStateManager supports changing states of controls.
  • Touch and Manipulation enables you to create applications that receive input from multiple touches simultaneously on Windows 7.
  • Graphics and animation supports layout rounding, Pixel Shader version 3.0, cached composition, and easing functions.
  • Text has improved text rendering and supports customizing the caret color and selection color in text boxes.
  • Binding is supported on the Command property of an InputBinding, dynamic objects, and the Text property.
  • XAML browser applications (XBAPs) support communication with the Web page and support full-trust deployment.
  • New types in the System.Windows.Shell namespace enable you to communicate with the Windows 7 taskbar and pass data to the Windows shell.
  • The WPF and Silverlight Designer in Visual Studio 2010 has various designer improvements to help create WPF or Silverlight applications.

For more information, see What's New in WPF Version 4.

 

Data


ADO.NET

ADO.NET provides new features for the Entity Framework, including persistence-ignorant objects, functions in LINQ queries, and customized object layer code generation. For more information, see What's New in ADO.NET.

Dynamic Data

For ASP.NET 4, Dynamic Data has been enhanced to give you even more power for quickly building data-driven Web sites. This includes the following:

  • Automatic validation that is based on constraints that are defined in the data model.
  • The ability to easily change the markup that is generated for fields in the GridView and DetailsView controls by using field templates that are part of a Dynamic Data project.

For more information, see What's New in ASP.NET 4 and Visual Web Developer.

WCF Data Services

ADO.NET Data Service has been renamed to WCF Data Services, and has the following new features

  • Data binding.
  • Counting entities in an entity set.
  • Server-driven paging.
  • Query projections.
  • Custom data service providers.
  • Streaming of binary resources.

For more information, see What's New in WCF Data Services.

 

Windows Communication Foundation


Windows Communication Foundation (WCF) provides the following improvements:

  • Configuration-based activation: Removes the requirement for having an .svc file.
  • System.Web.Routing integration: Gives you more control over your service's URL by allowing the use of extensionless URLs.
  • Multiple IIS site bindings support: Allows you to have multiple base addresses with the same protocol on the same Web site.
  • Routing Service: Allows you to route messages based on content.
  • Support for WS-Discovery: Allows you to create and search for discoverable services.
  • Standard endpoints: Predefined endpoints that allow you to specify only certain properties.
  • Workflow services: Integrates WCF and WF by providing activities to send and receive messages, the ability to correlate messages based on content, and a workflow service host.
  • WCF REST features:
    • Web HTTP caching: Allows caching of Web HTTP service responses.
    • Web HTTP formats support: Allows you to dynamically determine the best format for a service operation to respond in.
    • Web HTTP services help page: Provides an automatic help page for Web HTTP services, similar to the WCF service help page.
    • Web HTTP error handling: Allows Web HTTP Services to return error information in the same format as the operation.
    • Web HTTP cross-domain JavaScript support: Allows use of JSON Padding (JSONP).
  • Simplified configuration: Reduces the amount of configuration a service requires

For more information, see What's New in Windows Communication Foundation.

 

Windows Workflow Foundation


Windows Workflow Foundation (WF) provides improvements in the following areas:

  • Improved workflow activity model: The Activity class provides the base abstraction of workflow behavior.
  • Rich composite activity options: Workflows benefit from new flow-control activities that model traditional flow-control structures, such as Flowchart, TryCatch, and Switch<T>.
  • Expanded built-in activity library: New features of the activity library include new flow-control activities, activities for manipulating member data, and activities for controlling transactions.
  • Explicit activity data model: New options for storing or moving data include variable and directional arguments.
  • Enhanced hosting, persistence, and tracking options: Hosting enhancements include more options for running workflows, explicit persistence using the Persistactivity, persisting without unloading, preventing persistence by using no-persist zones, using ambient transactions from the host, recording tracking information to the event log, and resuming pending workflows by using a Bookmark object.
  • Easier ability to extend the WF Designer: The new WF Designer is built on Windows Presentation Foundation (WPF) and provides an easier model to use when rehosting the WF Designer outside of Visual Studio.

Friday, June 18, 2010

Credit Card CVV Code Validation in ASP.NET



What is CVV?

The Card Verification Value (CVV) is an extra code printed on your debit or credit card. It sometimes called Card Verification Value (CVV or CV2), Card Verification Value Code (CVVC), Card Verification Code (CVC), Verification Code (V-Code or VCode), or Card Code Verification (CCV). CVV is a new authentication procedure established by credit card companies to further efforts towards reducing fraud for internet transactions. It consists of requiring a card holder to enter the CVV number in at transaction time to verify that the card is on hand.

CVV Code in Credit Cards

CVV for Visa, MasterCard, BankCard and Diners is the final three digits of the number printed on the signature strip on the back of your card. CVV for American Express appears as a separate 4-digit code printed on the front of your card.

CVV Code Validation

We will see how to validate a CVV number using JavaScript as well as C# in this article. I have written methods/functions in C# and JavasScript respectively for this validation. The JavaScript function validateCvvCode() is used to validate a CVV code at client side. The ValidateCVVCode() written in C# is used to check the CVV code at server side. These functions determines number of digits required for the given card type and then checks if the CVV Code have the required count of digits and have only numeric digits 0 to 9 using a regular expression. The regular expression is formed dynamically based on the card type.

Validation Using JavaScript


The following code contains the javascript function to validation CVV code with
HTML markup of the demo application.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CVVValidationDemo.aspx.cs"
Inherits="CVVValidationDemo" %>
<!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>CVV Credit Card Number Validation </title>
<script type="text/javascript" language="javascript">

function validateCvvCode() {

//Get the text of the selected card type
var cardType = document.getElementById('ddlCardType')
.options[document.getElementById('ddlCardType').selectedIndex].text;
// Get the value of the CVV code
var cvvCode = document.getElementById('txtCVVCode').value;

var digits = 0;
switch (cardType.toUpperCase()) {
case 'MASTERCARD':
case 'EUROCARD':
case 'EUROCARD/MASTERCARD':
case 'VISA':
case 'DISCOVER':
digits = 3;
break;
case 'AMEX':
case 'AMERICANEXPRESS':
case 'AMERICAN EXPRESS':
digits = 4;
break;
default:
return false;
}

var regExp = new RegExp('[0-9]{' + digits + '}');
return (cvvCode.length == digits && regExp.test(cvvCode))
}

function checkCvvCode() {

var result = validateCvvCode();
if (result)
alert('Valid CVV Code');
else
alert('Invalid CVV Code');
}

</script>

<style type="text/css">
.style1
{
font-size: large;
font-weight: bold;
font-family: Arial;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table width="100%" cellspacing="0" cellpadding="0">
<tr>
<td width="200px">
</td>
<td class="style1">
CVV Code Validation
</td>
</tr>
<tr>
<td width="200px">

</td>
<td>
<asp:ValidationSummary ID="vsCVVValidationSummary" runat="server" />
</td>
</tr>
<tr>
<td width="200px">
Card Type
</td>
<td>
<asp:DropDownList ID="ddlCardType" runat="server" Width="250px">
</asp:DropDownList>
</td>
</tr>
<tr>
<td width="200px">

</td>
<td>

</td>
</tr>
<tr>
<td width="200px">
CVV Code
</td>
<td>
<asp:TextBox ID="txtCVVCode" runat="server"></asp:TextBox>
<asp:CustomValidator ID="custValidCVV" runat="server"
ErrorMessage="Invalid CVV Code">*</asp:CustomValidator>
</td>
</tr>
<tr>
<td width="200px">

</td>
<td>

</td>
</tr>
<tr>
<td width="200px">

</td>
<td>
<asp:Button ID="btnCvvServerValidate" runat="server" Text="Server Side Validation"
OnClick="btnCvvServerValidate_Click" />

<input id="hbtnCvvClientValidate" type="button" value="Client Side Validation"
onclick="checkCvvCode()" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>


Validation Using C#


The following code snippet has server side written in C# to demonstrate the CVV
code validation. I have loaded and checked the following card types in a dropdown
list for demonstration purpose: MASTERCARD, EUROCARD, EUROCARD/MASTERCARD, VISA,
DISCOVER and AMERICAN EXPRESS.

using System;
using System.Data;
using System.Text.RegularExpressions;

public partial class CVVValidationDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindCardType();
}

private void BindCardType()
{
System.Data.DataTable dtCardType = new System.Data.DataTable();
dtCardType.Columns.Add(new DataColumn("Card_Type_Id", typeof(int)));
dtCardType.Columns.Add(new DataColumn("Card_Type_Name", typeof(string)));

dtCardType.Rows.Add(new object[] { 1, "MASTERCARD" });
dtCardType.Rows.Add(new object[] { 2, "EUROCARD" });
dtCardType.Rows.Add(new object[] { 3, "EUROCARD/MASTERCARD" });
dtCardType.Rows.Add(new object[] { 4, "VISA" });
dtCardType.Rows.Add(new object[] { 5, "DISCOVER" });
dtCardType.Rows.Add(new object[] { 6, "AMEX" });
dtCardType.Rows.Add(new object[] { 7, "AMERICANEXPRESS" });
dtCardType.Rows.Add(new object[] { 8, "AMERICAN EXPRESS" });

ddlCardType.DataSource = dtCardType;
ddlCardType.DataValueField = "Card_Type_Id";
ddlCardType.DataTextField = "Card_Type_Name";
ddlCardType.DataBind();

}
protected void btnCvvServerValidate_Click(object sender, EventArgs e)
{
custValidCVV.ErrorMessage = "Invalid CVV Code";
custValidCVV.IsValid = ValidateCVVCode();
}

private bool ValidateCVVCode()
{
var cardType = ddlCardType.SelectedItem.Text;
var cvvCode = txtCVVCode.Text;

var digits = 0;
switch (cardType.ToUpper())
{
case "MASTERCARD":
case "EUROCARD":
case "EUROCARD/MASTERCARD":
case "VISA":
case "DISCOVER":
digits = 3;
break;
case "AMEX":
case "AMERICANEXPRESS":
case "AMERICAN EXPRESS":
digits = 4;
break;
default:
return false;
}

Regex regEx = new Regex("[0-9]{" + digits + "}");
return (cvvCode.Length == digits && regEx.Match(cvvCode).Success);
}
}



Verifying Credit Card Numbers Using Regular Expressions



With a few simple regular expressions, you can easily verify whether your customer entered a valid credit card number on your order form. You can even determine the type of credit card being used. Each card issuer has its own range of card numbers,identified by the first 4 digits.

You can use a slightly different regular expression to find credit card numbers,or number sequences that might be credit card numbers, within larger documents. This can be very useful to prove in a security audit that you're not improperly exposing your clients' financial details.

Validating credit card numbers is the ideal job for regular expressions. They're just a sequence of 13 to 16 digits, with a few specific digits at the start that identify the card issuer. You can use the specific regular expressions below to alert customers when they try to use a kind of card you don't accept, or to route orders using different cards to different processors.


  • Visa:^4[0-9]{12}(?:[0-9]{3})?$ All Visa card numbers start with a 4. New cards have 16 digits. Old cards have 13.
  • MasterCard:^5[1-5][0-9]{14}$ All MasterCard numbers start with the numbers 51 through 55. All have 16 digits.
  • American Express:^3[47][0-9]{13}$ American Express card numbers start with 34 or 37 and have 15 digits.
  • Diners Club:^3(?:0[0-5]|[68][0-9])[0-9]{11}$ Diners Club card numbers begin with 300 through 305, 36 or 38. All have 14 digits. There are Diners Club cards that begin with 5 and have 16 digits. These are a joint venture between Diners Club and MasterCard, and should be processed like a MasterCard.
  • Discover:^6(?:011|5[0-9]{2})[0-9]{12}$ Discover card numbers begin with 6011 or 65. All have 16 digits.
  • JCB:^(?:2131|1800|35\d{3})\d{11}$ JCB cards beginning with 2131 or 1800 have 15 digits. JCB cards beginning with 35 have 16 digits.

If you just want to check whether the card number looks valid, without determining the brand, you can combine the above six regexes into ^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$ You'll see I've simply alternated all the regexes, and used a non-capturing group to put the anchors outside the alternation. You can easily delete the card types you don't accept from the list.

These regular expressions will easily catch numbers that are invalid because the customer entered too many or too few digits. They won't catch numbers with incorrect digits. For that, you need to follow the Luhn algorithm, which cannot be done with a regex. And of course, even if the number is mathematically valid, that doesn't mean a card with this number was issued or if there's money in the account. The benefit or the regular expression is that you can put it in a bit of JavaScript to instantly check for obvious errors, instead of making the customer wait 30 seconds for your credit card processor to fail the order. And if your card processor charges for failed transactions, you'll really want to implement both the regex and the Luhn validation.

Monday, June 14, 2010

JSON Inroducation


JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.


JSON is built on two structures:



  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array,vector, list, or sequence.


These are universal data structures. Virtually all modern programming languages
support them in one form or another. It makes sense that a data format that is interchangeable with programming languages also be based on these structures.


In JSON, they take on these forms:


An object is an unordered set of name/value pairs. An object begins with
{ (left brace) and ends with } (right brace). Each name is followed by : (colon)and the name/value pairs are separated by , (comma).


What is jQuery And Why jQuery?

What is jQuery?
jQuery is great library for developing ajax based application. jQuery is great library for the JavaScript programmers, which simplifies the development of web 2.0 applications. You can use jQuery to develop cool web 2.0 applications. jQuery helps the programmers to keep code simple and concise. The jQuery library is designed to keep the things very simple and reusable.

jQuery library simplifies the process of traversal of HTML DOM tree. You can use jQuery to handle events, perform animation, and add the ajax support into your web applications with ease.

Why jQuery?
You can use simple JavaScript to perform all the functions that jQuery provides. Then why jQuery? The jQuery library is providing many easy to use functions and methods to make rich applications. These functions are very easy to learn and even a designer can learn it fast. Due to these features jQuery is very popular and in high demand among the developers. You can use jQuery in all the web based applications irrespective of the technology.

jQuery is java script and can be used with JSP, Servlets, ASP, PHP, CGI and almost all the web programming languages.

The jQuery code is very simple and easy to learn.

Here are the features of jQuery

  • DOM element selections functions
  • DOM traversal and modification
  • Events
  • CSS manipulation
  • Effects and animations
  • Ajax
  • Extensibility
  • Utilities - such as browser version and the each function.
  • JavaScript Plugins

Saturday, June 12, 2010

Free ASP.NET MVC Tutorial


The announcement made by Scoot Guthrie on 11-March-2009 that you can now download the tutorial for MVC.

The free ASP.NET MVC Tutorial having following points covered along with images.

  • File->New Project
  • Creating the Database
  • Building the Model
  • Controllers and Views
  • Create, Update, Delete Form Scenarios ViewData and ViewModel
  • Partials and Master Pages
  • Paging Support
  • Authentication and Authorization
  • AJAX Enabling RSVPs Accepts
  • Integrating an AJAX Map
  • Unit Testing

You can find the original post by ScootGu from here, and the PDF from here.

A sample application for ASP.NET MVC you can find it from Codeplex.



Friday, June 11, 2010

JSON Calling from MVC Page


HTML:

<%= Html.DropDownList("", new SelectList(ViewData["States"] as IEnumerable, "Id", "Name", Model))%>
<%= Html.DropDownList("", new SelectList(ViewData["Cities"] as IEnumerable, "Id", "Name", Model))%>


Javascript:

<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("select[id='StateId']").change(function() {
$.ajax({
type: "POST",
url: "/Supplier/StateCityInfo/",
data: { StateId: $(this).val() },
dataType: "json",
error: function(xhr, status, error) {
// you may need to handle me if the json is invalid
// this is the ajax object
alert(status);
},
success: function(data) {
$("#CityId").empty();
$.each(data, function(key, City) {
$("#CityId").append($("<option></option>").val(City.Id).html(City.Name));
});
}
});
})
})
</script>


Supplier Controller:

public class SupplierController : Controller
{
[AcceptVerbs("POST")]
public ActionResult StateCityInfo(int StateId)
{
return Json(this.AllCity(StateId));
}
}


Saturday, June 5, 2010

Merge Statement

 

SQL Statement:

DECLARE @tblMergeOutput TABLE
(
ID BIGINT IDENTITY(1,1)
, MergeAction NVARCHAR(100)
, InsertedId INT
, DeletedId INT
, GroupID INT
)

CREATE TABLE #tblSource ( ID INT, GroupID INT, Name VARCHAR(10) )
CREATE TABLE #tblTarget ( ID INT, GroupID INT, Name VARCHAR(10) )

INSERT INTO #tblSource VALUES (1,1,'a11')
INSERT INTO #tblSource VALUES (2,1,'a21')
INSERT INTO #tblSource VALUES (3,1,'a31')
INSERT INTO #tblSource VALUES (4,1,'a41')

INSERT INTO #tblTarget VALUES (1,1,'a1')
INSERT INTO #tblTarget VALUES (3,1,'a3')
INSERT INTO #tblTarget VALUES (5,1,'a5')
INSERT INTO #tblTarget VALUES (6,2,'b2')
INSERT INTO #tblTarget VALUES (7,2,'b1')

MERGE #tblTarget
USING (
SELECT *
FROM #tblSource
) AS tblSource
ON tblSource.GroupID = #tblTarget.GroupID
AND tblSource.ID = #tblTarget.ID
WHEN MATCHED THEN
UPDATE
SET Name = tblSource.Name
WHEN NOT MATCHED THEN
INSERT (
ID
, GroupID
, Name
)
VALUES (
tblSource.ID
, tblSource.GroupID
, tblSource.Name
)
WHEN NOT MATCHED BY SOURCE AND #tblTarget.GroupID = 1
THEN DELETE
OUTPUT
$action
, inserted.Id
, deleted.Id
, tblSource.GroupID
INTO @tblMergeOutput;

SELECT * FROM #tblSource
SELECT * FROM #tblTarget order by GroupID, ID
SELECT * FROM @tblMergeOutput

DROP TABLE #tblSource
DROP TABLE #tblTarget
 
Target Table Output:
 ------------------
ID GroupID Name
------------------
1 1 a11
2 1 a21
3 1 a31
4 1 a41
6 2 b2
7 2 b1
------------------
 
Merge Table Output:
----------------------------------------------------
ID Merge Action InsertedID DeletedID GroupID
----------------------------------------------------
1 INSERT 2 NULL 1
2 INSERT 4 NULL 1
3 UPDATE 1 1 1
4 UPDATE 3 3 1
5 DELETE NULL 5 NULL
----------------------------------------------------

Friday, May 21, 2010

Fill DropDownList with Ajax without Ajax ToolKit

 

CountriesAndStates.xml contain the following info/code:
 
<country name="USA">
<state>Alabama</state>
<state>Alaska</state>
<state>Arizona</state>
<state>Arkansas</state>
</country>
Write following code in Ajaxclient.aspx page:
    <form id="Form1" method="post" runat="server">
<asp:DropDownList id="countryList" onchange="return CountryListOnChange()"
style="Z-INDEX: 101; LEFT: 20px; POSITION: absolute; TOP: 28px" runat="server" Width="174px" Height="28px">
</asp:DropDownList>

<asp:DropDownList id="stateList" style="Z-INDEX: 102; LEFT: 218px; POSITION: absolute; TOP: 28px"
runat="server" Width="174px">
</asp:DropDownList>
</form>
Page_Load Method of AjaxClient.aspx Page 
    private void Page_Load(object sender, System.EventArgs e)
{
CountryStateXml countryStateXml = new CountryStateXml();
ArrayList countries = countryStateXml.GetCountryList();
for(int index = 0; index < countries.Count; index++)
{
countryList.Items.Add(countries[index].ToString());
}
ArrayList states = countryStateXml.GetStateList(countries[0].ToString());
for(int index = 0; index < states.Count; index++)
{
stateList.Items.Add(states[index].ToString());
}
}
Write Javascript code:

    function CountryListOnChange() 
{
var countryList = document.getElementById("countryList");
var selectedCountry = countryList.options[countryList.selectedIndex].value;
var requestUrl = AjaxServerPageName + "?SelectedCountry=" + encodeURIComponent(selectedCountry);
CreateXmlHttp();
if(XmlHttp)
{
XmlHttp.onreadystatechange = HandleResponse;
XmlHttp.open("GET", requestUrl,  true);
XmlHttp.send(null);
}
}

Function for Handling Response :

    function HandleResponse()
{
if(XmlHttp.readyState == 4)
{
if(XmlHttp.status == 200)
{
ClearAndSetStateListItems(XmlHttp.responseXML.documentElement);
}
else
{
alert("There was a problem retrieving data from the server." );
}
}
}

Page_Load Method of the AjaxServer.aspx Page

    private void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack )
{
string selectedCountry = Request["SelectedCountry"];
if(selectedCountry.Length > 0)
{
Response.Clear();
CountryStateXml countryStateXml = new CountryStateXml();
string statesString = countryStateXml.GetStatesXMLString(selectedCountry);
Response.Clear();
Response.ContentType ="text/xml";
Response.Write(statesString);
Response.End();
}
else
{
Response.Clear();
Response.End();
}
}
else
{
Response.Clear();
Response.End();
}
}

Thursday, May 20, 2010

AJAX Call from ASP .NET Page

 

Javascript :

function newXMLHttpRequest() {
var xmlreq = false;
if (window.XMLHttpRequest) {
xmlreq = new XMLHttpRequest();
} else if (window.ActiveXObject) {
// Try ActiveX
try {
xmlreq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e1) {
// first method failed
try {
xmlreq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
// both methods failed
}
}
}
return xmlreq;
}

 

function GetUserInfo(PageURL) {
var req = newXMLHttpRequest();

req.open("POST", PageURL, true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.setRequestHeader("content-length", "0"); req.send('');

req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == 200) {
alert(req.responseText.toString());
}
}
}

}