Saturday, September 3, 2011

WPF Combobox with auto-complete/auto-filter


You know these nice ajax/javascript textboxes where you start typing somes text and the website looks up the data in the database and returns a list of items starting with the text.

There is no default control for this in WPF as well. So, time to build one.



View [XAML] contain the following info/code:
     
    <ComboBox x:Name="cmName"  
                            ItemsPanel="{DynamicResource ItemsTemplate}"  
                            Padding="4 3"  
                            Width="170"  
                            IsEditable="True"  
                            IsTextSearchEnabled="False"  
                            Text="{Binding TextBinding}"  
                            IsDropDownOpen="{Binding IsDropDownOpen}"  
                            ItemsSource="{Binding SourceBinding}"  
                            DisplayMemberPath="Name"  
                            SelectedValue="{Binding Path=SelectedEmailThreadingFrom}"  
                            Grid.ColumnSpan="2"  
                            Margin="43,2,-8,-24"  
                            Grid.Row="6" 
                            />  
                            
View Model [CS] contain the following info/code:
 
      private List<ReturnType> _SourceBinding;

      public List<ReturnType> SourceBinding
      {
        get
        {
            return _SourceBinding;
        }
        set
        {
            _SourceBinding = value;
            RaisePropertyChanged("SourceBinding");
        }
     }

     private string _TextBinding; 
      
     public string TextBinding  
     {  
       get { return _TextBinding; }  
       set  
       {  
         _TextBinding = value;  
         Filter(value);  
         RaisePropertyChanged("TextBinding");  
       }  
     }  

     private bool _IsDropDownOpen;  

     public bool IsDropDownOpen  
     {  
       get { return _IsDropDownOpen; }  
       set  
       {  
         _IsDropDownOpen = value;  
         RaisePropertyChanged("IsDropDownOpen");  
       }  
     }  


Filter Method of View Model [CS] Page
 
     private void Filter(string value)  
     {  
       SourceBinding = (from m in OtherFillList  
                    where m.Name.ToLower().StartsWith(value.ToLower())  
                    select m).ToList();  
       if (SourceBinding != null && SourceBinding.Count > 0)  
       {  
         IsDropDownOpen = true;  
       }  
     }  

Tuesday, January 4, 2011

URL Rewrite Using ASP.net 3.5 or Over




The blog will explin how we can achieve url rewriting in ASP.net 3.5 or Over.

Step1 : Create a helper class title "SiteRouteHandler.cs".

 1: #region System
 2: using System;
 3: using System.Collections.Generic;
 4: using System.Linq;
 5: using System.Web;
 6: using System.Web.UI;
 7: using System.Web.Routing;
 8: using System.Web.Compilation;
 9: #endregion
10:  
11: namespace UrlRewrite
12: {
13:  
14:    /// <summary>
15:    /// Handler for routing
16:    /// </summary>
17:    public class SiteRouteHandler : IRouteHandler
18:    {
19:  
20:       #region Properties
21:  
22:       /// <summary>
23:       /// Page Virtual Path
24:       /// </summary>
25:       public string PageVirtualPath { get; set; }
26:  
27:       #endregion
28:  
29:       #region Implements IRouteHandler
30:  
31:       /// <summary>
32:       /// Gets the handler in return
33:       /// </summary>
34:       /// <param name="requestContext"></param>
35:       /// <returns></returns>
36:       public IHttpHandler GetHttpHandler(RequestContext requestContext)
37:       {
38:  
39:          Page page = BuildManager.CreateInstanceFromVirtualPath(PageVirtualPath,typeof(Page)) as Page;
40:          foreach (var item in requestContext.RouteData.Values)
41:          {
42:  
43:             HttpContext.Current.Items["qparam." + item.Key] = item.Value;
44:          }
45:  
46:          return page;
47:       }
48:  
49:       #endregion
50:    }
51:  
52: }

Step 2 : In global.asax.cs file declare the routes you want to give to
the pages with a particular pattern. Use the SiteHandler class for getting the params
mentioned in the route pattern. The "{ID}", "{AspxPage}" and "{PageNumber}" are
the dynamic values which can be used on our aspx page for manupulation. Than according
to the pattern "123" is {ID}, "This-is-a-blog" is {AspxPage} and 32 is {PageNumber}.
"~/Blog.aspx" is the actual page.

 1:  using System.Web.Routing;
 2:  protected void Application_Start(object sender, EventArgs e)
 3:  {
 4:   
 5:     //Clears all route
 6:     RouteTable.Routes.Clear();
 7:   
 8:     //Handles the route
 9:     RouteTable.Routes.Add("Blog", new Route("blog/{ID}/{AspxPage}.aspx/{PageNumber}", new
10:                                    SiteRouteHandler() { PageVirtualPath = "~/Blog.aspx" }));
11:  }
12:   

Step 3 : Now on Blog.aspx we can use params to retrieve the data.


 1:  /// <summary>
 2:  /// The blog id from the query string
 3:  /// </summary>
 4:  private int BlogID
 5:  {
 6:   
 7:     get
 8:   
 9:     {
10:   
11:        if (Context.Items["qparam.ID"] == null)
12:        {
13:   
14:           return 0;
15:        }
16:   
17:        return Convert.ToInt32(Context.Items["qparam.ID"]);
18:     }
19:   
20:  }
21:   
22:   
23:  /// <summary>
24:  /// The blog id from the query string
25:  /// </summary>
26:  private string AspxPage
27:  {
28:   
29:     get
30:   
31:     {
32:   
33:        if (Context.Items["qparam.AspxPage"] == null)
34:        {
35:   
36:           return string.Empty;
37:        }
38:   
39:        return Context.Items["qparam.AspxPage"].ToString();
40:     }
41:   
42:  }
43:   
44:   
45:  /// <summary>
46:  /// The Page Number
47:  /// </summary>
48:  private int PageNumber
49:  {
50:   
51:     get
52:   
53:     {
54:   
55:        if (Context.Items["qparam.PageNumber"] == null)
56:        {
57:   
58:           return 0;
59:        }
60:   
61:        return Convert.ToInt32(Context.Items["qparam.PageNumber"]);
62:     }
63:   
64:  }

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);
}
}