Dec 15 2021

Move quickly your team to Asp.NET Core 6!

Asp.NET Core online interactive course Start quickly with Asp.NET Core 6, with an interactive online course on the Educative platform

Takeaway Skills

ASP.NET Core
MVC Pattern
Razor and Razor tag-helpers
Localization and globalization
Option framework
Dependency injection and hosted services
Authentication and Authorization

Start Now!

Course Contents

  1. Razor Template Language

  2. Tag Helpers

  3. Controllers and ViewModels

  4. Validation and Metadata

  5. Dependency Injection

  6. Configuration and Options Framework

  7. Localization and Globalization

  8. Factoring out UI Logic

  9. Authentication and Authorization

  10. Publishing Your Web Application

Try it|

Tags: , , ,

Dec 11 2010

Silverlight…without Ria Services

Data Validation 3: Silverlight, INotifyDataErrors, Ria Services and The Validation Toolkit for WPF & Silverlight

Something More about Ria Services

Ria Services offer an easy solution to the main problems of a typical Business Silverlight application, specifically:

  1. Data Validation. As discussed in a previous post, Ria Services offer support for a data validation based on Data Annotations defined on the server side classes.
  2. Communication with the server and remote validation. Several configuration details of the web service definitions are automatically handled by Ria Services. Moreover, as discussed previously, if the definition of some custom validation attribute is not available on the client side, validation is performed remotely on the server (please refer to the above post for more information).
  3. Ria services automatically set up Asp.net Authentication, Authorization and User Profile Web Services for the Silverlight client.

Unluckily, it is not always possible to use Ria Services, because the Web Services created by Ria Services are specific for Silverlight. Therefore, if one needs a interoperable general purpose service layer that is compatible with various technologies Ria services can not be used.

In such a case the only acceptable option should be the configuration of a Silverlight specific endpoint in a general purpose Web Services. However, often I see developers that do a partial duplication of code implementing a parallel Ria Services Layer specific for the Silverlight clients just to take advantage of the opportunities  offered by Ria Services.

In this post I will show a simple alternative way to obtain the same advantages offered by Ria Services with general purpose Web Services.

Let start with the support for Data Annotations.We can proceed as follows ( I assume  knowledge of the Data Annotations issues discussed in my previous posts here and here.) :

  1. When we define the meta classes of our business classes we  furnish a complete implementation of those classes with the right property types. Moreover, in order to make them serializable we decorate them with the [DataContract] attribute and their properties with the [DataMember ] attribute, since we want they be compatible with Silverlight that has no implementation of the [Serializable] attribute.
  2. We use the above meta classes as View Models or as part of the View Models, both in the server and in Silverlight projects. I advice just linking the same code to both the Silverlight  and  the server projects.
  3. We define our Web Services according to general design constraints, and not only according to Silverlight needs.
  4. We generate the Silverlight proxy, with the option to use already existing classes. This way, we use the original View Models we have linked to the Silverlight project instead of View Models provided automatically by Visual studio during proxy generation.
  5. Once in Silverlight, we wrap the View Model with the Validation Toolkit for Wpf & Silverlight wrapper, in order to furnish it support for both Data Annotations and INotifyPropertyChanged.

With the above procedure we have View Models with Data Validation support without duplicating code, and with the same effort required by the definition of a Ria Domain Service.

The Validation Toolkit for Wpf & Silverlight offers also all tools needed to perform the Remote Validation. On the server we pack all validation errors into an IEnumerable<ValidationErrorInfo> and then we throw a fault Exception: FaultException<IEnumerable<ValidationErrorInfo>> containing the above IEnumerable.

The exception is passed to the client if we decorate the Wcf interface definition with the FaultContract<IEnumerable<ValidationErrorInfo>>] attribute.This is enough for all clients but Silverlight to receive the validation errors. In fact Silverlight is a browser plug-in and as all browser plug-ins it can receive the details of a response only if the status code of the response is either 200(OK) or 404(Not Found), and the status code associated with a fault error normally is not one of them. To overcome this problem we apply the SilverlightFaultBehavior defined in the BindToolkit.Behaviors namespace of the Validation Toolkit for Wpf & Silverlight to the endpoint specific for Silverlight. This endpoint behavior change the status code of the Wcf error response from whatever it is into a 200 status code, thus allowing Silverlight to receive the FaultException.

Once the FaultException is available to the silverlight client,we need just to call the AddValidationFaultExceptionContent(IEnumerable<ValidationErrorInfo> errors) method of the top level wrapper, to send all error messages in their adequate places in the User Interface.

The binary distribution of the Validation Toolkit for Wpf & Silverlight contains a Silverlight example that shows both how to use the wrapper and how to handle remote validation.

Finally, the set up of  Asp.net Authentication, Authorization and User Profile Web Services for the Silverlight client is easy because Asp.net has standard implementations for these Web Service.

For the authentication service we just need to add to our web project an .svc file containing just:

<%@ ServiceHost 
  Language="C#"
  Service="System.Web.ApplicationServices.AuthenticationService" 
  Factory="System.Web.ApplicationServices.ApplicationServicesHostFactory" %>

No code behind or explicit implementation needs to be furnished since the Asp.net class  System.Web.ApplicationServices.AuthenticationService offers a standard implementation of the Authentication Service. However, we need to configure a Membership provider on our Web Site.

In the configuration file we must enable the Authentication Service:

<system.web.extensions>
  <scripting>
    <webServices>
      <authenticationService enabled="true" 
         requireSSL = "true"/>
    </webServices>
  </scripting>
</system.web.extensions>

and we must configure it to use basicHttpBinding(for Silverlight compatibility) and Https:

<services>
    <service name="System.Web.ApplicationServices.AuthenticationService"
        behaviorConfiguration="AuthenticationServiceTypeBehaviors">
      <endpoint contract=
        "System.Web.ApplicationServices.AuthenticationService"
        binding="basicHttpBinding"
        bindingConfiguration="userHttps" 
        bindingNamespace="http://asp.net/ApplicationServices/v200"/>
      </service>
  </services>
  <bindings>
        <basicHttpBinding>
            <binding name="userHttps">
                <security mode="Transport" />
            </binding>
        </basicHttpBinding>
  </bindings>

A detailed reference is here.

Analogously, for the Authorization service we have:

<%@ ServiceHost 
  Language="C#"
  Service="System.Web.ApplicationServices.RoleService" 
  Factory="System.Web.ApplicationServices.ApplicationServicesHostFactory" %>
<system.web.extensions>
  <scripting>
    <webServices>
      <roleService enabled="true"/>
    </webServices>
  </scripting>
</system.web.extensions>
<services>
    <service name="System.Web.ApplicationServices.RoleService"
        behaviorConfiguration="ApplicationServiceTypeBehaviors">
      <endpoint contract=
        "System.Web.ApplicationServices.RoleService"
        binding="basicHttpBinding"
        bindingConfiguration="userHttps" 
        bindingNamespace="http://asp.net/ApplicationServices/v200"/>
    </service>
  </services>
  <bindings>
<basicHttpBinding>
<binding name="userHttps">
<security mode="Transport" />
</binding>
</basicHttpBinding>

a Detailed reference is here.

While for the User Profile we have:

<%@ ServiceHost Language="C#"
Service="System.Web.ApplicationServices.ProfileService" 
Factory="System.Web.ApplicationServices.ApplicationServicesHostFactory" %>
<system.web.extensions>
  <scripting>
    <webServices>
      <profileService enabled="true"
        readAccessProperties="Birthday, FavoriteColor"
        writeAccessProperties="Birthday, FavoriteColor" >
    </webServices>
  </scripting>
</system.web.extensions>

As you can see, while enabling the profile service we need to specify read and write permissions for each property.

The service configuration is quite standard:

<services>
    <service name="System.Web.ApplicationServices.ProfileService"
      behaviorConfiguration="MyServiceTypeBehaviors">
      <endpoint contract=
        "System.Web.ApplicationServices.ProfileService"
        binding="basicHttpBinding" 
        bindingNamespace="http://asp.net/ApplicationServices/v200"/>
    </service>

A detailed Reference is here.

Well. As you can see, the set up of a Silverlight application with all features described in points 1), 2), and 3) is quite easy and can be carried out quickly also without the use of Ria Services. Therefore, there is no need to force the use of Ria Services also when a different solutions should be more adequate.

That’s all for now!. But…..

                                                                                  Stay Tuned !

                                                                                  Francesco

For more information or consulences feel free to contact me

Tags: , , , , , , , ,

Oct 21 2010

…Something More about Ria Services

Data Validation 3: Silverlight, INotifyDataErrors, Ria Services and The Validation Toolkit for WPF & Silverlight

Silverlight…without Ria Services

In my previous post about data validation I spoke quite enough about Ria Services. I spoke about its kind of validation and how it is achieved, and also how to share classes among a Silverlight project and its hosting web site project (it is enough to put the share.cs or share.vb extension to a file on the server).

Discussing with people I discovered that there are a lot of  false beliefs about Ria services. For instance, a lot of developers think they can use Ria services only in conjunction with Entity Framework classes. This is simply false. Ria services allow you to define a context similar to the one of the EF entities also with general classes provided by the programmers: just follows the wizard that let you define your services…and will see it give you also this option.

If your classes are interconnected, you can benefit of Linq to Objects for your queries in a way completely analogous to EF objects.

With Ria services you can benefit of some pre-defined endpoints that have been adequately configured to fit well the needs of Silverlight users: you have a binary endpoint for intranet applications (its default), a soap endpoint for Internet applications and also a JSon endpoint. Moreover, you have also the option to expose OData (there is a check box in the wizard for the service definition). Instructions on how to define the endpoints in the configuration file are reported here. The bad news are that you cannot configure the features of the endpoints like in normal WCF services using the configuration file, but if you need features that are not contained in the standard configuration of the standard endpoints you have to define new endpoints in code.

Requiring a secure session is quite easy and can be done just by putting this attribute on the class that defines the service: [EnableClientAccess(RequiresSecureEndpoint = true)].Secure messages protocols are not supported by Silverlight. Don’t forget to give an https Url to a secured soap endpoint!

Requiring authentication and Role based authorizations are both easily achieved with attributes as explained here: http://msdn.microsoft.com/it-it/library/ee707361(en-us,VS.91).aspx. The above link explain also how to login and how to handle login errors.

Another, important thing that is worth to mention about Ria services concerns the return value of the Query methods of the service. According to the official documentation Query methods may return an IEnumerable<T>, an IQueryable<T> or a single object. However, what is not reported in the documentation is that only by returning an IQueryable one can  have an efficient filtering of data based on criteria passed by the Silverlight client to the server. For instance, suppose the Silverlight client needs to filter the customers returned by a Query method .GetCustomersQuery() defined on the server according to a user provided name. One can achieve this with the instruction:

 domainContext.Load(domainContext.GetCustomersQuery().Where(c => c.Name == "John").OrderBy(c => c.Age))

One could thing that all data returned by the server are then filtered by the Silverlight client. NO: behind the scene the Silverlight client build an IQueryable<T> and pass it to the server.Now, if also the server side method GetCustomerQuery() returns an IQueryable<T> the two queries are combined and either passed to the the Database or to Linq to Object to get the needed results efficiently! Therefore,  if you need to perform filtering based on client side defined criteria, please, always return an IQueryable<T>!

I thanks Gius that helped me clarifying well this point by speaking directly with a member of the WCF data services team.

Before concluding this short review post about Ria Services I would like to mention two more alternatives well suited for Silverlight clients: WCF Data Services, and WCF Rest Services. The WCF Rest Service Application template is not available in Visual Studio 2010 but it can be downloaded directly from Visual Studio 2010 by searching it in the Extension Manager(tool menu).

WCF Data Services are very similar to Ria services, The way you use it from Silverlight is quite the same. The main difference is that they don’t have any simple mechanism to share code with Silverlight and to handle validation. Moreover, you have to generate the proxy in Silverlight with Visual Studio and your context need to be specified by code(you need just to substitute a generic with an actual class…), and not with a simple wizard. The context may involve either EF entities or normal classes as in the case of Ria Services. This means some more job to be done but more flexibility because all things that Ria Services do in a standard way can now be customized! The only big loss is validation, but you can use my Validation Toolkit for WPF & Silverlight that is more flexible than the standard mechanism of Ria Services. However, it is important to mention that WCF Data Services just have one type of endpoint! The Rest endpoint! With a Rest endpoint queries are specified by adequately writing an URL, and the results are returned in the OData format that is a generalization of the Atom feed format. This means, you can send query not only with Silverlight but also with a simple browser! This is a very useful help in debugging the application. Obviously if you work with Silverlight all this details are hidden to you that just may use data contexts and IQueryables like with Ria Services.

WCF rest services use the same Rest protocol as the WCF Data Services but they are not connected to EF or classes, they are generic WCF services based on the Rest protocol. Parameters for the services are specified by the structure of the Url with the help of Routing tables defined in the Global.asax in a similar way to MVC Web applications. They are an interesting option to be considered for complex services that do more sophisticated computations than simply retrieving data from a Database.

Next post of this series will be again on validation, but on the server side…

 

                                                                                  Stay Tuned !

                                                                                  Francesco

For more information or consulences feel free to contact me

Tags: , ,