Sep 18, 2007

Calling Webmethods Asyncronously

If you are using any web reference in your Windows Forms application or Web Site there might have been numerous occasions when you make a call to any of the web methods exposed by the web service.
Time taken by the web method to return is dependent on the network traffic and the method implementation.
We cannot block the main thread to wait for the web method to return.
This eats up the application responsiveness. It is advised to call the web methods asynchronously.
For every web method in ASP.NET 2.0 Web Service there is a corresponding Asynchronous method.

Web Service

For the Webmethod Helloworld() we have an Async method HelloWorldAsycn().
An Event HelloWorldCompleted and Event argument
Before making call to the async webmethod we need to attach a eventhandler corresponding to the completion of the method. In our case it is HelloWorldCompletedEventHandler.
This is how the client application will make the call, and the service will callback the event handler once the method execution is completed


Sep 1, 2007

Data as Web Service

Using new advanced features of SQL Server 2005 we can expose stored procedures, user defined functions and even T-SQL statements as web services, providing access to the database.This gives new dimensions to a SOA because any HTTP SOAP (web) client be can access the database without any extra middleware.

We can send SOAP/HTTP requests to SQL Server to execute:

· Transact-SQL batch statements, with or without parameters.

· Stored procedures extended stored procedures, and scalar-valued
user-defined functions.

SQL Server 2005 relies on 'HTTP.SYS' Kernel listener (driver) of Windows Server 2003 to expose its data objects as HTTP End points. It doesn't rely on IIS to expose these services. This simplifies application development and deployment, and requires fewer
infrastructure components.

Once the HTTP listener in Windows Server 2003 is configured in such a way that its able to send requests to SQL Server, The database administrator (DBA) can create and define the endpoints and associate the stored procedures and scalar-valued functions to an endpoint as Web methods.

Creating HTTP Endpoints
Setting up SQL Server as a Web Service that can listen natively for HTTP SOAP requests requires creating an HTTP endpoint and defining the methods that the endpoint exposes.
We use the new CREATE ENDPOINT statement to create HTTP endpoints.
Each HTTP endpoint ties the results of a SQL Server stored procedure directly to a Web Service, providing support through the Web Services Description Language (WSDL) and Simple Object Access Protocol (SOAP) protocols for retrieving the data supplied by the stored procedure.

The HTTP Endpoint also is a means of creating interfaces via HTTP or TCP for SOAP, TSQL, Service Broker, and even database mirroring. Although all these other functions are very fascinating, the discussion here mainly concerns only on the SQL Server 2005 ability to create Web services—Web services that can return row set data, scalar
values, messages, and even errors, all of which are serialized into XML automatically.

While creating an HTTP endpoint, it must be created with a unique URL that it uses this URL to listen for incoming HTTP requests. For example, if we create an endpoint with the URL "http://ServerName.Domain/Store" SOAP requests that are sent to http://ServerName.Domain/Store" will be picked up by HTTP.SYS. HTTP.sys will then route the SOAP requests to the SQL Server instance that hosts the endpoint associated with the URL. From there, the requests will be handed off to the SOAP processing layer within SQL Server.

In this section how we can create the HTTP endpoint. To start with, we will have to create a stored procedure that returns some data or use an existing stored procedure. As an example, we will use a simple stored procedure dbo.getCustomerDetails that returns the contents of two fields from the Sales.Customers table in the Sales sample database
that ship with SQL Server 2005:

CREATE PROC dbo.getCustomerDetails


Once the stored procedure is ready, the next step will be to create
the HTTP endpoint. The SQL Statement snippet below is used to create
an HTTP endpoint "GetCutomer" and running this SQL statement is what
makes the data from the stored procedure available to SOAP clients:
PATH = '/Store',
SITE = 'ServerName.Domain'
--SQL Server Name and Domain
WEBMETHOD 'CustomerList'
(NAME= Sales.dbo.getCustomerDetails),
DATABASE = 'Sales',


The CREATE ENDPOINT statement has several key components. The STATE argument is set to STARTED, which indicates that the endpoint listener is running. Other options included STOPPED and DISABLED for handling service endpoints. The rest of the code sits in the AS HTTP clause or the FOR SOAP clause. AS HTTP sets HTTP as the transport for the endpoint and includes the following settings:

PATH—Specifies the URL for the service endpoint, and in this example defaults to the server name and the path specified, e.g. "http://ServerName.Domain/Store

AUTHENTICATION—Specifies the type of authentication to be used for the service endpoint. A variety of authentication mechanisms are supported, including BASIC, INTEGRATED (uses Windows security), NTLM, and KERBEROS.

PORTS—Specifies what port type to use. CLEAR or SSL are the supported options, with CLEAR accepting only HTTP requests and SSL requiring HTTPS.

SITE—Specifies the name of the host computer for the endpoint. The FOR SOAP clause supports the following arguments:
WEBMETHOD—Specifies the Web method used to send requests via the HTTP SOAP endpoint. we can declare multiple Web methods per endpoint.

BATCHES—specify whether not the endpoint supports ad-hoc SQL requests.This is disabled by default.

WSDL—specifies whether the endpoint supports WSDL. For custom WSDL implementations, we can provide a stored procedure name that returns a custom WSDL implementation.

DATABASE—specifies the name of the database where the requested operation is executed in context.

NAMESPACE—specifies a namespace for the endpoint.After creating the endpoint, we can submit an HTTP request to the server to ensure that the endpoint is responding. A simple test is to navigate to "http://ServerName.Domain/Store?wsdl (substitute server
and endpoint name), which, if the endpoint is responding, will return the WSDL for our exposed service.

Consuming Web Services(End Point)

Consuming the Native Web Service that is created using the SQL Server 2005, Is exactly same as we consume any web services created using .Net and C#. That's the advantage of Web Services and SOAP. We'll create a windows or a web application in Visual studio .Net and we will need to add the Web reference to the web service created using the HTTP Endpoint. We can browse the web service created in the above sample code using the http://servername.domain/Store?wsdl where the Server would be our computer name or IP.

Once the Web reference is created we can use this web service as a normal web service. Here we need to note that the WebMethod returns the object array because the SQL Server can not only send the result sets, but also the messages, Errors, and other types. Its our responsibility that we validate what we have received is what we expected and safely cast the object to the required type to work with it.

SQLReference.GetCutomer proxy = new SQLReference.GetCutomer ();

//SQLReference is the name given to the Web Service Reference

proxy.UseDefaultCredentials = true;

object results = proxy.CutomerList();


Aug 12, 2007

Microsoft Connected Services Framework

The Microsoft CSF is an integrated, server-based software product which enables service oriented architecture (SOA) to empower the creation and management of services across networks and devices.
An interoperable, manageable, and scalable infrastructure of services can be integrated with the existing technologies. It enables an SOA to create new Web Services, update the existing one and aggregate services into a single distributed application.
CSF helps to create, deploy and update applications that composed of web services. The basic built-in blocks of CSF performs identity or profile management or service discovery functionality and does not require taking care of those in services.

Key Functions and Components
Connected Services Framework consists of components (see Figure below) that provide environments for service creation, deployment, and execution of voice, data, and multimedia services, as well as system management. In addition, Connected Services Framework provides a platform for content service solutions to integrate, manage, and provision content from third-party content providers

Service Creation Environment
The components within this environment provide an integrated development environment and software development kits (SDKs) for software developers to use when creating new services. In addition, developers can be authenticated on Connected Services Framework within an operator’s environment and have access to a catalog of exposed Web services for internal functionality, as well as to external partners. Web services can be combined to create new aggregated or composite services by using Visual Studio development system. For example, a developer who wants to create a video conferencing service can browse the service catalog to discover exposed services that enable video conferencing, as well as services that can interface to media streaming and billing activities.

Service Deployment Environment
The components within this environment provide tools and mechanisms that help operators manage the deployment of new services, both within a provider’s core network and in third-party service provider and content delivery networks. Operators can automate service deployment to reduce complexity and minimize downtime, and to manage deployed services information in terms of version number, operating system, system configuration, hardware configuration, and so on.
The main components of Connected Services Framework are:

Session Component:
The Session is the central collaboration unit of CSF, and enables Web service collaboration between heterogeneous Web services that were developed without access to the other service's implementation details.
Session enables service collaboration through a session context among the services in CSF. Providing a centralized context for service collaboration enables services to be developed independently, decreasing coupling and increasing modularity. Session makes no assumptions about the services participating in a collaboration cycle, so independent development of participating services is enabled.
Session creates and manages the collaboration context through which the loosely coupled services can exchange messages. It mediates this exchange of messages by providing an environment for message routing, identity mediation, policy enforcement, security enforcement, and metering and monitoring.

Role of Session Component in CSF:
The main tasks involved in managing a session are defining a manifest, creating a session, searching for sessions, and terminating a session. Before creating a session, we should define a manifest by specifying the initial participants and any custom routing information that is required.
The important role of Session component in CSF is that all the messages are sent by using CSF pass through the Session Web service, which routes these messages to the appropriate destinations.
Identity Manager:
The identity Manager manages users, organizations, customers, and roles for CSF. It provides authentication and role-based authorization services for CSF. It also provides administrative policies, such as those for passwords and audits for a CSF deployment. The Identity Manager manages mappings between CSF users and value-added services participants to provide the Single Sign-On service to CSF, so that Requesting Authorities to CSF are only required to present valid CSF user credentials, rather than credentials for all of the VAS participants that are involved in the request. The Identity Manager uses Microsoft Enterprise Single Sign-On (ESSO) to provide an encrypted store for secondary credentials that a user or a service may have to present to an application to be authenticated and authorized by that application. The Identity Manager can be used to register applications and to create user maps, which hold the mappings between these applications and the secondary credentials that a user must present to sign-on to the application. Identity Manager also provides calls that you can use to get information about registered applications and to manage the user maps that are stored in ESSO. The Identity Manager MMC Snap-in can be used to create and manage applications and user maps in Identity Manager.

Service Catalog:
Microsoft Connected Services Framework (CSF) Service Catalog component is a Universal Description, Discovery, and Integration (UDDI) registry which stores the properties of all XML Web services that can participate in your CSF distributed application. The Service Catalog is built on Microsoft Enterprise UDDI Services, a component of Windows Server 2003.The Service Catalog provides access to the UDDI repository that holds the URIs of Web services that can be used in business scenario. The Service Catalog component stores the uniform resource identifier locations of all value-added services that are part of the distributed application, and provides a Web service that you can query to return URIs for specified services. You can obtain the URI for a service by specifying the name of the service, the binding key of the service in the service catalog, or the UUID of the service. The Service catalog exposes a Web service interface that enables you to use UDDI to discover the services that are offered for a particular request.

One of the initial steps you must perform to create your CSF application is to populate the Service Catalog. You should use the UDDI Publish command line tool. While you can also populate the Service Catalog by using the user interface provided by UDDI Services, the UDDI Publish tool dramatically reduces the possibility of introducing errors to a t-Model and the services that you register in the Service Catalog. The UDDI Publish tool automatically puts the correct identifiers into the t-Model and registers the Web service with that t-model. You do this by first creating a Provider entry in the Service Catalog, which defines the organization that offers the Web service over your internal network or across the Internet. You can also add contact information for the Provider. Next, you register the Web service itself and the binding for each endpoint within the service.

In most scenarios, the Service Catalog component is used to get a list of Web service URIs from a list of Universal Unique Identifiers that are mapped to those Web services. We should always store the physical URI of a specific Web service in the Service Catalog, and your application should read that URI from the Service Catalog before it calls the Web service. By designing your application in this way, if you change the URI for the Web service, you only change it in the Service Catalog and not in multiple locations.
You can discover Service Catalog through all common Web service discovery mechanisms, including UDDI, WS-Discovery, WS-Inspection and DISCO.
When you create a CSF application you must also design a CSF client. This client can query the Service Catalog for Web service properties so that it can build a Session Manifest. Such a query obtains URIs for the Web services and any other properties for that service, such as any security policies defined for the Web service, and authorization or authentication requirements. This information is typically used by the CSF client to create the Participant Manifest sections of the Session Manifest that the client uses to create a session for the incoming request. The following figure illustrates the relationship between a CSF client, the Service Catalog, and the Session core component.

Profile Manager:
Information about subscribers, networks, and services are managed in profiles. In Connected Services Framework, profile management is provided by Microsoft SQL Server and Active Directory on Windows Server 2003.Using profiles for each user enables operators to offer personalized services to customers. User profile management provides the foundation for effective customer targeting of information services, which leads to higher customer satisfaction and increased revenue for operators. Within the scope of Connected Services Framework, user profile management enables operators to analyze service usage activities of subscribers based on access history; this enables them to generate abstract usage patterns and supply such valuable insights to value-added services for fine-tuning their personalization engines.

This component is based on Resource Description Framework (RDF) and Simple Protocol and RDF Query Language (SPARQL) standards. In addition, this component provides capability to propagate events based on the profile changes to interested services that are registered for event notifications using the WS-Eventing standard.

Standard Business Events:
CSF enables collaboration between loosely-coupled Web services. However, enterprises often possess core business systems that are heterogeneous, tightly-coupled, and that are either rudimentarily Web service-enabled or are not Web service-enabled at all. A Standard Business Event (SBE) is a custom Web service that enables collaboration between your enterprise-wide business systems and external Web services to help you compose a service application that provides a specific area of business functionality. Conceptually, the SBE sits between your enterprise business systems and CSF and facilitates communication, a process, or both, with other Web services through a CSF session.
An SBE can provide:

· A bridge between enterprise systems that do not implement Web services and Web services that use the CSF platform.

· Specialized functionality that enables collaboration between enterprise systems and external services; for example, by transforming heterogeneous messages that are delivered by multiple external systems into schemas that can be understood by one or more enterprise systems.

Microsoft offers two Standard Business Event (SBE) products to help you integrate your enterprise-wide business systems with Web services that are provided by external systems.
  • The Order Handling Standard Business Event(OHSBE) enables order management systems to create, provision, and fill orders for resources that are provided by external Web services.
  • The Billing Standard Business Event(BSBE) enables your back-end billing systems to collect billing usage information from Web services, and to exchange advice of service messages between your general ledger application and a Web service

Well Enabled Services:
A Well-enabled Service (WES) is a Web service that provides a resource-centered view of a product. It provides four views of resources, which enables you to isolate and implement the functionality that is required to expose a product as a series of services. A WES enables you to do the following tasks:
· Provision resources
· Monitor the health of resources
· Discover resources
· Track usage of resources that are implemented by the product

For example, you can use Microsoft Exchange and a WES to provide access to Exchange mailboxes, implement provisioning services (such as creating or deleting mailboxes,) monitor the state of the Exchange server to maintain a specified quality of service, and track the amount of mailbox space occupied by users. A WES can help you to make the product available as a service. In a commercial environment, monitoring of the health and usage of resources can be the basis for billing customers.

By using a WES you can enable a product to participate in a CSF application alongside other services. The following figure illustrates a scenario where a number of consumers of the WES access the WES through a CSF application.

The Billing Web service queries the WES through the Usage interface to obtain information to bill customers of the service. The Marketing Web service uses the Health interface to provide advertisements to customers based on the state of the resource. For example, if the Value Added Service (VAS) is a mail server and the resource enters a degraded state because a user account exceeds the allocated storage limit, the marketing Web service can provide information to the user about how to upgrade the account to an increased the storage limit. The VAS is invisible to other Web services because all interaction occurs through the WES interfaces. Other Web services can access any of the interfaces that are exposed by the WES within the security restrictions that are implemented by the WES.

Utilities (Web Services):

Besides these core components, CSF provides various helper services for event notification, reporting,tracking and tracing.

The Profile Integrator subscribes to the profile updates events that the Profile Manager generates and propagates the changes to the services to which the user has subscribed. Connected Services Framework (CSF) Profile Integrator works with the Profile Manager to propagate user profile changes to all of the value-added services (VASs) for which the user is provisioned. Whenever you update an existing user profile in the Profile Manager, it automatically sends an event to notify the Profile Integrator about the change. While the event is fired for multipe VASs at a time, the Profile Integrator processes updates to each VAS individually, one at a time.

Service Logic or Service Orchestration:
The Service Logic component is a Web service that provides the business logic to drive a composite service application. The core CSF services (Session, Identity Manager, Profile Manager, and Service Catalog) provide a collaboration context through which Web services can be aggregated by providing a framework for message delivery, identity mediation/synchronization, authentication, and service discovery within a composite service application. The Service Logic component provides the rules and sequencing steps that define the interaction of Web services in a composite service application. This service logic orchestration could be implemented by using Microsoft BizTalk® Server, a Web Service,or other workflow engines.

The Notification Participant logs the messages that are routed by Session in a message queue so that the messages can be consumed by applications at a later time. Messages consumed by the Notification Participant can contain many types of data, such as billing data records. As a utility service or VAS, the Notification Participant is not one of the CSF core components, but it serves the important function of permitting messages to be sent outside CSF from any Session.

Summing up:
We can easily combine collections of Web services to create composite services and applications. CSF provides all the common services for a SOA to collaborate Web services to easily communicate with one another, identity management, profile management, and service discovery capabilities. CSF is built on top of Microsoft Web Services Enhancements (WSE) 3.0.CSF enables you to use the .NET Framework to develop secure, interopable Web services that are based on open industry specifications.

Aug 10, 2007

Service Oriented Architecture

Service Oriented Architecture (SOA) is an imminent version of the Component Based Architecture. It is an Interface Based Object Oriented Design.It can also be viewed as a Distributed System that communicates across the Internet.SOA is based on the use of distributed objects and components and is the next evolutionary step in computing environments. SOA does not have a standardized, reference model yet; however, implementations share the main concepts of services, service descriptions, advertising and discovery, the specification of an associated data model, and the use of a service contract.

Although SOA and Web services are two separate but related entities, it is more important to realise the clear distinction between them. Web services, in the form of SOAP-based interapplication connections, has been highlighted, while SOA — a body of application architecture and design concepts — has largely been viewed as a side effect of Web services.

An SOA, at its heart, is a collection of services. A service is a software component
that is well-defined, both from the standpoint of software and business function, and doesn't depend on the context or state of any application that calls it.

Loosely Coupled Services : A service in an SOA comprises of the interface contract which is platform-independent. These services can be dynamically located and invoked. They are self-contained i.e., the state of a service does not depend upon the state of other services. A client from anywhere, functioning on any operating system can dynamically invoke these services (depending on their requirement). Dynamic discovery involves a lookup of services in the Universal Description Discovery Integration(UDDI) directory where service providers publish the services they provide.

Dynamic Discovery : The directory of services(UDDI) forms an intermediary for service providers and consumers. They organize services and categorize them as per their functionality. A directory service in SOA has the following advantages:
a)Decouples consumers from providers.
b)Scalability of services is highly enhanced. Services can be added incrementally.
c)Serves as a lookup for service consumers.
d)Allows consumers to dynamically locate service providers instead of hard-coding a single provider.

Web Services: Web Services play a major role in SOA because these services are built on top of platform independent protocols. These protocols include HTTP, XML, UDDI, WSDL and SOAP. Services in an SOA can be dynamically discovered and invoked. This is accomplished through these protocols. XML makes it very easy to have a platform-independent interface contract. HTTP enhances interoperability.

Messages: The interface contract of services defines the behavior of the service and the messages they receive and send from service consumers and service providers respectively. And since these interface contracts are platform and language independent, the method of defining these messages should also be compatible with all platforms, operating systems and languages. XML provides all of these features by being non-restrictive towards platforms and languages.

Picture shown below reflects the Protocol Stack of current SOA building blocks.

A SOA building block can represent one or many of these roles

Service provider
The service provider creates a service and possibly publishes its interface and
access information to the service registry or broker. Each provider must
decide which services to expose, how to make trade-offs between security
and easy availability, how to price the services, or, if they are free, how to
exploit them for other value. The provider also has to decide what category
the service should be listed in for a given broker service and what sort of
trading partner agreements are required to use the service.

Service broker
The service broker, also known as service registry, is responsible for making
the service interface and implementation access information available to any
potential service requestor. The implementer of the broker decides about the
scope of the broker. Public brokers are available through the Internet, while
private brokers are only accessible to a limited audience, for example, users
of a company intranet. Furthermore, the amount of the offered information
has to be decided. Some brokers specialize in many listings. Others offer high
levels of trust in the listed services. Some cover a broad landscape of services
and others focus within an industry. There are also brokers that catalog other
brokers. Depending on the business model, brokers can attempt to maximize
look-up requests, number of listings or accuracy of the listings.

Service consumer
The service consumer or requestor client locates entries in the broker registry
using various find operations and then binds to the service provider in order
to invoke one of its services.

Aug 1, 2007

XSD Schema Validation

The other day I was writing a .NET application which would read all the configuration details from an xml file.The application was not going to initialize properly unless the data in the config file were well formed.So I was wondering whether there was a way to validate an xml against some defined XSD schema.
Thankfully there is.
This is how I did it.

//Open the file with xml reader
XmlTextReader reader = new XmlTextReader(configFilePath);//Some local path

// Read the Schema
XmlReader schemaReader = new XmlTextReader(schemaPath);//path of the XSD file
XmlSchema schema = XmlSchema.Read(schemaReader , null);

// Create a validating Reader for the text reader
XmlValidatingReader validatingReader = new XmlValidatingReader(reader );
validatingReader.ValidationType = ValidationType.Schema;
validatingReader.Schemas.Add(schema);// Add the Schema to validatingReader
validatingReader.ValidationEventHandler += new ValidationEventHandler(this.ValidationEventHandle); //Event Handler for Validation Error
while (validatingReader.Read()) { } // Read but do nothing


If the xml file is a valid one then the validatingReader won't fire any events.

(a better approach...)
Even I managed to figure out a way to validate an XML file with a given Schema, I was wondering why we would need two readers to read/validate just one file. Then I figured out that XmlValidatingReader has now become obsolete.And instead, this task could be performed using just one Reader. We just need to put all the validation setting while creating the Reader itself.

// Read the XSD file and build schema object out of it
XmlReader schemaReader = new XmlTextReader(@"Schema.xsd");
XmlSchema schema = XmlSchema.Read(schemaReader, null);

//Create XmlReaderSettings object with validation settings
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;

//Assign the ValidationEvent Handler
settings.ValidationEventHandler += new ValidationEventHandler(this.ValidationEventHandle);

//Now create the reader with Validation Setting
XmlReader myXmlReader = XmlReader.Create(filePath,settings);

// Read XML data
while (myXmlReader.Read()) { }


If the XML file fails to validate against the given schema, the validation event will be fired.

For Reference :

Top Ad 728x90