Showing posts with label WCF RIA Services. Show all posts
Showing posts with label WCF RIA Services. Show all posts

Wednesday, 27 February 2013

WCF RIA Validations

How RIA Services Implement Validations

RIA Services have a built in way to validate entity up to the Silverlight UI.The validation logic used is common in the client as well as the server side.

Whenever an entity is changed , the ChangeSet is validated immediately , if the ChangeSet contains validation error , the validation results are passed  and shown at the client in a ValidationErrorContainer. In this case the ChangeSet does not travel to the server , thus doesn't call any service.

If the ChangeSet is a valid one that is there are no validation errors , the service is called. There may be cases where some business rules need to be implemented. For example , In an employee management application , whether the employee is eligible for a long leave is a decision to be taken based on the attendance data of the employee and this information cannot be shared with the client.  So, we implement the LongLeave rule in the server side.

Based on the business rule either the entity is set as valid or invalid. In case an entity is set as invalid at the server side , here we can show the errors either in a message box or an validation error container.

Following diagram shows how the RIA Services work in an MVVM way:





Data Annotation Validation Attributes

The namespace used for validation is System.ComponentModel.DataAnnotations.The class used to validate entities is the ValidationAttribute class in the above namespace.Any class that derives from ValidationAttribute class is a validator.

In RIA Services both property level and object level validations can be done.Validation attributes can be placed on the properties of metadata class. These validation attributes will be used for server side validation by WCF RIA Services,and they will also be used client side because the client generated entities will have those attributes on their properties.

Following are the common property level validator:
a. RequiredAttribute
b.StringLengthAttribute 
c.RangeAttribute
d.RegularExpressionAttribute



Custom Validation Attributes


Cross property validation


ValidationContext:


Validations during Submit Operation


Async Validation using Invoke Methods


References







Tuesday, 17 July 2012

Domain Context : considerations, strategies and design

1. What is a domain context?

A domain context is a collection of entities and the operations possible on those entities which is available to the client. Which the application uses to communicate with the domain service.
Client can not interact directly with domain services . Instead, a domain context class is generated in the client project for every domain service in the server project.The domain context is generated in the client side as soon as you add a domain service at the server side and build the server side project.The name of the domain context is in accordance with the domain service , for example if the domain service is called EmployeeDomainService the domain context is named EmployeeDomainContext.

According to msdn:" A Domain Context is a stateful client side representation of domain service , provoding access to all the functionality of the service."

The domain context class inherits the DomainContext class 
System.ServiceModel.DomainServices.Client.DomainContext.

2. Looking inside a domain context?


The generated domain context has three overloaded constructors:
Constructor 1: Default constructor embeds the URI for communicating with the domain service over HTTP.
Constructor 2:Enables to specify alternate URI
Constructor 3 : This is used as a custom domain context , used for unit testing.

Domain context supports:
a. Querying
b. Submitting
c.Invoking domain operations.

The Classes used for the above three operations are :
a. LoadOperation 
b.SubmitOperation
c.InvokeOperation

The Methods used for the above three operations are :
a. Load : gets the data
b.SubmitChanges : saves the changes
c.RejectChanges : rolls back changes

EntitySet is generated in the client and contains the operations(get,insert, update, delete) that can be executed by the client.

As discussed above regarding name of the service and context , similarly the name of the operations at the server side and the client side vary.
For example the server side query is GetEmployees() and client side the corresponding method in domain context is GetEmployeesQuery().

All the operations from the domain context are asynchronous and to take any action after the operation a callback method should be provided.

An application may contain one or many number of domain service and domain context.

Following are the various scenarios generally seen :
a. Application has N number of view models but 1domain service and 1 domain context.(Shared domain context.)
b. Application has N number of view models , 1 domain service but N number of domain context , one for each view model.

Now among all these scenarios which is the best of for your application how do you decide?

3. How should I Decide?


 We generally create view models based on business functionality , so creating a separate domain context for each of these individual business functionality is advantageous from the point of view that RIA services does not provide partial save. If we have separate domain contexts for each of the views we can implement partial save very easily , because whenever an entity changes for a particular business object , submit changes is called only for and not for others.
In general business scenarios normal two business objects relate to each other by some or other means , let me take an example of  two view model Product and Category. If product and category are in the same view model , we need to do extra bit to make changes in product not to reflect in category. If separate domain contexts are used , this problem can be avoided.

Although the above two points hold good but the problem that this approach has is keeping each individual view models in sync.Synchronizing each of the individual view models each time after the submit operation is a performance issue.

This does not come out of box and has to be handled exclusively. This can be done by refreshing domain contexts only for the entities that have changed.

When there is only one domain context for all the view models the problem which becomes very prominent is  the problem of partial save and also the changes in one entity will get reflected immediately.

I suggest the best way is to go with  shared domain context idea but instead of having a single domain context for all view models may be based on the UI and functionality a little more than domain context may be used.

For example , in case of a application having category, product , sale , report modules may be only one domain context will be good enough.

In case of a school management app having Student , Employee , Course , Marks, Reports we can use two domain contexts one for Student , Course , Marks and other for Employee and Reports.


Monday, 16 July 2012

Security in WCF RIA- Service Best Practices

In this article we will see  some of the coding best practices done to ensure RIA services are secure. The best practices are referred from msdn.
I will be taking paging-caching , authentication and authorization and adding endpoints in subsequent articles.


When you expose a domain service by applying the EnableClientAccessAttribute attribute, the domain service is available to everyone on the network where it is exposed.
The Client application is accessed not only by your application but also any other application can access the domain service. This consideration is important not just for application with sensitive data hosted to public but also in case of an application hosted behind a firewall.
Here I have tried to list down a few things which we use in our project , reference is msdn.

Best Practices
Sl No                                         
1
ID                                      
D&O_1
Best Practice Definition
Only the required data should be exposed to the client
Explanation
If there are 5 columns of a table in the application and say, only 2 columns are needed by the client expose only the two columns required by the client to do the task.
You should also expose only those entities that should be consumed by the client and not all the entities.
Example
When a column should not be exposed decorate it with [Exclude] attribute.
Exclude specifies that an entity member will not exist in the code-generated client view of the entity, and that the value should never be sent to the client.


Or you can create a separate domain class, which contains only those entities that should be exposed to the client.

Sl No                                         
2
ID                                     
D&O_2
Best Practice Definition
Only the required operations should be exposed to the client
Explanation
Suppose for an entity Product, Products can be inserted and updated and cannot be deleted, we should not expose delete method to the client.
Example
You can either create multiple domain services one for the client and other with server exposing the appropriate methods and decorate the methods which are not used by client with [Ignore] attribute in the client’s domain service.

Sl No                                         
3
ID                                     
D&O_3
Best Practice Definition
Retrieve only the required operations and not everything in the database
Explanation
Pass required parameters to query operations so that the output data can be filtered as required.
Example
For a method GetReportForAnEmployee , create a separate LINQ query and pass EmployeeID as a parameter instead of using GetReport() and then doing some operations on all the data that is retrieved.



Sl No                                         
4
ID                                     
D&O_4
Best Practice Definition
Use separate query methods for each specific scenario.

Explanation
Pass required parameters to query operations so that the output data can be filtered as required.
Example
For example, if products are shown by category or supplier, you can provide two methods that accept category or supplier information, instead of a single method that returns all of the products.

Sl No                                         
5
ID                                     
D&O_5
Best Practice Definition
Use caching and paging intelligently.

Explanation
Paging helps to show the results when large number of records is retrieved present in the search result, while managing the server load.
Caching decreases load on middle layer.
Example



Sl No                                         
6
ID                                      
A&A_1
Best Practice Definition
Provide authentication and authorization for data and operations.

Explanation
Apply the RequiresAuthenticationAttribute attribute to a domain method to restrict access to the operation to only authenticated users.
the RequiresAuthenticationAttribute attribute is applied to an entire domain service class, all of the domain operations are restricted to only authenticated users.
The RequiresAuthenticationAttribute attribute prevents the method from being executed when the user is not authenticated.


Example
[RequiresAuthentication]
        public void InsertEmployee(Employee employee)
        {
            if ((employee.EntityState != EntityState.Detached))
            {
                this.ObjectContext.ObjectStateManager.ChangeObjectState(employee, EntityState.Added);
            }
            else
            {
                this.ObjectContext.Employees.AddObject(employee);
            }
        }


Sl No                                         
7
ID                                     
A&A_2
Best Practice Definition
Provide authentication and authorization for data and operations.

Explanation
RequiresRoleAttribute is applied to a domain method to restrict access to the operation to only authenticated users that belong to one of the specified roles.
When you apply the RequiresRoleAttribute to an entire domain service class, all of the domain operations are restricted to only authenticated users that belong to the specified roles.
The RequiresRoleAttribute prevents the method from being executed when the user does meet the authentication criteria.

Example
[RequiresRole("Administrator")]
        public void DeleteEmployee(Employee employee)
        {
            if ((employee.EntityState == EntityState.Detached))
            {
                this.ObjectContext.Employees.Attach(employee);
            }
            this.ObjectContext.Employees.DeleteObject(employee);
        }


Will explain 5, 8 and 9 in next few articles to come.

Sl No                                          
8
ID                                     
A&A_3
Best Practice Definition
Always verify data before using it.
Explanation
Data sent from client should not be trusted, verify the data for data type , regular expressions, nulls and empty, length etc in the domain service. You can also validate these using custom validators.

Example


Sl No                                         
9
ID                                     
EP_1
Best Practice Definition
Minimize the number of end points
Explanation
For RIA Service, binary endpoint is default. New endpoints should be added in the web.config only when needed.

Example



Sunday, 15 July 2012

Domain Services


We talked about domain service in the last article, now let us sit and understand what domain service is?

Domain services are Windows Communication Foundation (WCF) services that encapsulate the business logic of an application. A domain service exposes a set of related operations in the form of a service layer.
 When you define a domain service, you specify the data operations that are permitted through the domain service.

Domain service is defined at the server side, using the domain service the entities in a domain context at the client side talk to the database.

When designing a domain service, you should think of the domain service as a set of related tasks that you expect users to perform in your application. Typically, such tasks involve a small group of closely-related entities. For example, in a school management application, you might expose entities for students, grades and courses in a domain service. You might, then, place entities for staffs, class, house and payments in a separate domain service.

The DomainService class is the base class for all classes that serve as domain services.

There are two ways to create domain service class for your application:
1.       Create a blank domain service for creating custom domain services
2.       Create the domain service from ADO.NET.

To create a domain service that binds to a custom data object, you create a class that derives directly from DomainService.

But if you have a domain service either binds an ADO.NET Entity model or that exposes a LINK to a SQL database, there are special abstract classes the derive from DomainService that you use instead.

A domain service class must be marked with the EnableClientAccessAttribute attribute to make the service available to the client project. 


TheEnableClientAccessAttribute attribute is automatically applied to a domain service when you select the Enable client access check box in the Add New Domain Service Class dialog box.
When the EnableClientAccessAttribute attribute is applied to a domain service, RIA Services generates the corresponding classes for the client project.

As a Windows Communication Foundation (WCF) service, the domain service builds upon WCF concepts.

The domain service features that use WCF concepts:
·         Standard usage of WCF services
·         Existing WCF programming models constructs, such as operation contracts, operation behaviors, and service behaviors
·         Standard WCF customization capabilities, such as binding configuration, behavior configuration, and management infrastructure

The domain service or WCF Domain service is created at the server side.
The domain context gets created automatically at the client side.
When you build the server solution a service contract is created.

The domain context communicates with the RIA Services domain service by using the WCF ChannelFactory to create a channel and passing to it a service contract that was generated from the domain service.

By default, only the binary endpoint is enabled for domain services. 
To use the binary endpoint no additional configuration is needed. If you want to use another endpoint (such as OData, JSON, SOAP, or a custom host) you must register an endpoint factory in the Web.config file as shown below:

The System.ServiceModel.DomainServices.Hosting namespace contains the endpoints that are supported in RIA Services.

A domain service generally contains methods that perform data operations that you have exposed.

When domain services are created automatically these methods are pre-added.
In case it’s a custom domain service, we need to add the methods by ourselves.
You can add methods that perform the following operations:

·         Query
·         Update
·         Insert
·         Delete




You can also add more complicated operations such as:

·         Invoke: to implement operations that need to be executed without tracking or deferred execution.
This method is used only with non-entity data, and used only when query, update, insert, or delete operations cannot be used instead.
·         Named Update: to implement custom operations that do not fall into simple modification operations.

When you expose a domain service, an EntitySet object is generated in the domain context with properties that indicate which operations (insert, update, or delete) are permitted from the client. You execute data modifications by modifying the entity collection and then calling the SubmitChanges method.

To Load data you should use queries instead of invoking operations because Invoke operations provide an out-of-band mechanism for returning non-entity data and executing operations with side-effects. 

Query methods returns one of the following:

a.        a single Entity object,
b.        An IQueryable<Entity> object,
c.         An IEnumerable<Entity> object. 

The RIA Services framework generates entities in the client project for only those entities that are returned from query methods in a DomainService.

Following are the common things you should now before calling a query method:

a.       You cannot overload methods that are domain operations. 
b.       You must specify a unique name for each method that can be called from the client project.
c.        All methods that represent domain service operations must be public.
d.       The methods must use serializable types for parameters and return types.
e.       You can prevent a method from being exposed by adding the IgnoreAttribute attribute to the method.
f.         A query method must return a single instance of an entity, or an IEnumerable<T> or IQueryable<T> where T is a valid entity type.
g.       You cannot have two methods GetBooks() and GetBook(int id) because overloading is not allowed, instead you can have GetBooks() and GetBookById(int id)
h.       When you want to write your application logic in the methods, either create a partial class or create separate methods containing your application logic which can be called from the method operations.Partial classes will give you security concerns, so use the application logic in a separate method decorated with [Ignore] attribute.



References: