DCSIMG
April 2010 - Posts - Gil Fink's Blog

Gil Fink's Blog

Fink about IT

News

Microsoft MVP

My Facebook Profile My Twitter Profile My Linkedin Profile

Locations of visitors to this page

Creative Commons License

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.
© Copyright 2013 Gil Fink

Hebrew Articles

Index Pages

My OSS Projects

English Articles

April 2010 - Posts

Add Service Reference – How to Avoid Generating Already Existing Classes

Add Service Reference – How to Avoid Generating Already Existing Classes

Today I was asked Add Service Reference – How to Avoid Generating Already Existing Objects
how to avoid
generating an
already existing 
client class when
we use the Add Service Reference menu item in Visual Studio.

The Problem

In the e-mail I got the question was regarding the use of ValidationResults
(from the Validation Application Block) as a return type for a WCF Service.
When they try to Add Service Reference to the service it is generating
a new ValidationResults class for the use in the client side.

How to Avoid This Problem?

You need to reference the assembly that holds the ValidationResults
in the client’s project. Since by default the Add Service Reference
reuses the types in all the referenced assemblies this will disable 
the  generation of ValidationResults class.
If you want to disable this feature or to be able to specify the
referenced assemblies you can first open the Add Service Reference
menu and then click the Advanced button:
Add Service Reference
In the Service Reference Settings view you can check or uncheck
the Reuse types in referenced assemblies checkbox or specify the
only referenced assemblies to search with the Reuse types in specified
referenced assemblies radio button:
Service Reference Setting

Summary

In order to avoid generation of classes in the proxy that is generated
by WCF’s Add Service Reference we need to add reference to the
dll which include those classes in the client assembly. Another way to
do that is to use the svcutil.exe with the parameter /reference:<file path>
were file path is the location of the dll which you want to reuse its
classes. I hope it will help you.

Enterprise Library 5 Fluent Configuration API

Enterprise Library 5 Fluent Configuration API

One of the newEnterprise Library 5 Fluent Configuration API
Enterprise Library 5
improvements is a new
fluent configuration API.
In this post I’ll explain the
subject and then show
how to use the fluent
configuration
API with the
Data Access Application Block.

Fluent Configuration API

There are times that we would like to configure our application
at runtime without using a configuration file such as
web.config or app.config. In order to achieve that we can use the
new fluent configuration API that was shipped with
Enterprise Library 5. The API can be used to configure the core,
instrumentation and all of the application blocks not including
the Validation and Policy Injection application blocks. Also, if you
already have an Enterprise Library configuration in your config file you
will be able to merge the configuration you created in runtime to it or
update it.

Using the Fluent Configuration API

In order to use the fluent configuration API you need to create a
ConfigurationSourceBuilder which is the main class to build a runtime
configuration. Each feature in Enterprise Library, such as the
application blocks for example, provide extension methods for this class
which enable us to use the API in the same manner. The use of the
extension methods is very intuitive and easy. The
ConfigurationSourceBuilder class is located in the
Microsoft.Practices.EnterpriseLibrary.Common.Configuration dll and you
need to reference it. In order to use the fluent configuration 
extension methods for every application block you need to add a reference
to that application block’s dll also.

DAAB fluent configuration API example

Lets look at a DAAB fluent configuration API example:

public void ConfigureDAAB()
{
  var configBuilder = new ConfigurationSourceBuilder();
 
  configBuilder.ConfigureData()
         .ForDatabaseNamed("School")
           .ThatIs
           .ASqlDatabase()
           .WithConnectionString(ConnectionString)
           .AsDefault();
 
  var configSource = new DictionaryConfigurationSource();
  configBuilder.UpdateConfigurationWithReplace(configSource);
  EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(configSource);
}

What you see here is that I created a ConfigurationSourceBuilder instance.
Then I used the fluent configuration API to configure it. I instructed the
data configuration to be a SQL Server provider (using the ASqlDatabase
method), gave it a connection string and set it to be my default database.
Then I created a DictionaryConfigurationSource which hold my DAAB
configuration when I use the UpdateConfigurationWithReplace method
in order to update the configurations or if exists to replace it.
In the end I set the EnterpriseLibraryContainer to be configured from
that source.

Summary

Enterprise Library 5 comes with a new fluent configuration API which
enable us to configure our EnterpriseLibraryContainer in runtime.
That API is very intuitive and easy to learn. I showed a straight forward
example of how to configure the default database for the Data Access
Application Block

I hope it will help you.

Enterprise Library 5 Released

Enterprise Library 5 Released

The new release of Enterprise Library 5 Released
Enterprise Library 5 is
available in Codeplex
site.
This new release brings a 
massive change in the
architecture and the core of
Enterprise Library such as
refactoring all the Application Blocks to work with Unity and 
dropping the old ObjectBuilder library. Also we got a new look
and feel for the configuration tool which is now implemented in
WPF:
Entlib Configuration Tool  
We get more improvements to the application blocks themselves
such as data accessors in Data Access Application Block or
optimizations in the Logging Application Block. There is a new
programmatic configuration support via fluent interface
which make writing configuration in code more intuitive.

You can download Enterprise Library 5 from here

Book Review – C# in Depth – What You Need to Master C# 2 and 3

Book Review – C# in Depth – What You Need to Master C# 2 and 3

In the last weeks  C# in Depth
I read the book
C# in Depth –
What You Need
to Master C# 2
and 3
” that was
written by
Jon Skeet.
You might ask
yourself why I
bothered reading
a book about
C# 2 and 3.
The answer is
very simple. 
Knowing some
material isn’t
enough and
reading leads to wide and
deeper knowledge. One of the first things that I recommend people
who ask me how can I learn and gain programming knowledge
is reading good technical books. That leads me right back to the book.
C# in Depth is a great book to read. I really enjoyed the writer’s
writing and the book itself. Sometimes when I read technical books
I get bored and this book succeeded to fascinate me so I kept on
reading.

What You are Going to Gain from The Book?

A lot. The book is a deep dive into the past (C# 2) and to the present
(C# 3). It includes all the language enhancements and features and
shows how they developed during time. I really liked the discussion
about delegates which is well defined in the book.

What is Included in The Book?

The book includes the following parts:

  • Preparing for the journey – this chapter covers all the overview
    about C# and it develop from C# 1.
  • Solving the issues of C# 1 -  this part include all the new (currently
    they are now old) features of C# 2 including Generics, Nullable types,
    delegates (which were introduced in C# 1 but were very improved in
    C# 2), iterators using yield and more.
  • C# 3 – revolutionizing how we code – this part discuss the new
    features of C# 3 including initializers, anonymous types, lambda
    expressions and expression trees, extension methods, LINQ and more.

Summary

"C# in Depth” is a very recommended book.
I give it 5 stars out of five.
If you look for a very interesting book about C# evolution and more this
is your book.

SQL For .Net Developers First Session

SQL For .Net Developers First Session

SQL For .Net Developers First Session

 

Microsoft is conducting a SQL For .Net Developers series of sessions.
I got the honor to deliver the first session about
Entity Framework 4.0 & LINQ.
The session will take place on the 5.5.2010 at Microsoft office in Raanana
starting at 17:00 till 19:00.
For further details (in Hebrew) and registration you can use this link
See you there!

Building ASP.NET Validator using Data Annotations

Building ASP.NET Validator using Data Annotations

In this post I’m Building ASP.NET Validator using Data Annotations
going to describe
an implementation
of ASP.NET validator
that uses the new
System.ComponentModel.DataAnnotations 
assembly that comes in .NET 4.

The Validator

In order to create the validator you need to inherit from
the BaseValidator abstract class and implement its EvaluateIsValid
method.
I’ve created an ASP.NET Server Control project and added a control
class that do the exact thing.You need to reference the 
System.ComponentModel.DataAnnotations assembly in order for
it to work. Here is how it’s implemented:

namespace Validators
{
  [ToolboxData("<{0}:DataAnnotationValidator runat=server></{0}:DataAnnotationValidator>")]
  public class DataAnnotationValidator : BaseValidator
  {
    #region Properties
 
    /// <summary>
    /// The type of the source to check
    /// </summary>
    public string SourceTypeName { get; set; }
 
    /// <summary>
    /// The property that is annotated
    /// </summary>
    public string PropertyName { get; set; }
 
    #endregion
 
    #region Methods
 
    protected override bool EvaluateIsValid()
    {
      // get the type that we are going to validate
      Type source = GetValidatedType();
 
      // get the property to validate
      PropertyInfo property = GetValidatedProperty(source);
 
      // get the control validation value
      string value = GetControlValidationValue(ControlToValidate);
 
      foreach (var attribute in property.GetCustomAttributes(typeof(ValidationAttribute), true).OfType<ValidationAttribute>())
      {
        if (!attribute.IsValid(value))
        {
          ErrorMessage = attribute.ErrorMessage;
          return false;
        }
      }
      return true;
    }
   
    private Type GetValidatedType()
    {
      if (string.IsNullOrEmpty(SourceTypeName))
      {
        throw new InvalidOperationException("Null SourceTypeName can't be validated");
      }
      
      Type validatedType = Type.GetType(SourceTypeName);
      if (validatedType == null)
      {
        throw new InvalidOperationException(
            string.Format("{0}:{1}", "Invalid SourceTypeName", SourceTypeName));
      }
 
      return validatedType;
    }
 
    private PropertyInfo GetValidatedProperty(Type source)
    {
      PropertyInfo property = source.GetProperty(PropertyName, 
        BindingFlags.Public | BindingFlags.Instance);
 
      if (property == null)
      {
        throw new InvalidOperationException(
          string.Format("{0}:{1}", "Validated Property Does Not Exists", PropertyName));
      }
      return property;
    }
 
    #endregion
  }
}

 

As you can see I use two main properties in the validator
which help me to get the relevant source type name and
property to validate.

Testing The Validator

In order to test the validator I have created a Web Application
project and put inside of it a simple Person class which
uses Data Annotations for validation:

namespace ASPNETDataAnnotation
{
  public class Person
  {
    [Required(ErrorMessage="ID is requiered")]
    public string ID { get; set; }
 
    [StringLength(20, ErrorMessage = "First name is too long!")]
    public string FirstName { get; set; }
 
    [StringLength(20, ErrorMessage="Last name is too long!")]
    public string LastName { get; set; }
 
    [RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*",
      ErrorMessage="Must be a valid e-mail address")]
    public string Email { get; set; }
  }
}

Also I’ve created a web form that uses the validator:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="ASPNETDataAnnotation.WebForm1" %>
 
<%@ Register Assembly="Validators" Namespace="Validators" TagPrefix="cc1" %>
<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <div>
            <asp:Label ID="lblID" Text="ID: " runat="server" />
            <asp:TextBox ID="txtID" runat="server" />
            <cc1:DataAnnotationValidator ID="valID" runat="server" ControlToValidate="txtID"
                PropertyName="ID" SourceTypeName="ASPNETDataAnnotation.Person, ASPNETDataAnnotation" />
        </div>
        <div>
            <asp:Label ID="lblFirstName" Text="First Name: " runat="server" />
            <asp:TextBox ID="txtFirstName" runat="server" />
            <cc1:DataAnnotationValidator ID="valFirstName" runat="server" ControlToValidate="txtFirstName"
                PropertyName="FirstName" SourceTypeName="ASPNETDataAnnotation.Person, ASPNETDataAnnotation" />
        </div>
        <div>
            <asp:Label ID="lblLastName" Text="Last Name: " runat="server" />
            <asp:TextBox ID="txtLastName" runat="server" />
            <cc1:DataAnnotationValidator ID="valLastName" runat="server" ControlToValidate="txtLastName"
                PropertyName="LastName" SourceTypeName="ASPNETDataAnnotation.Person, ASPNETDataAnnotation" />
        </div>
        <div>
            <asp:Label ID="lblEmail" Text="E-Mail: " runat="server" />
            <asp:TextBox ID="txtEmail" runat="server" />
            <cc1:DataAnnotationValidator ID="valEmail" runat="server" ControlToValidate="txtEmail"
                PropertyName="Email" SourceTypeName="ASPNETDataAnnotation.Person, ASPNETDataAnnotation" />
        </div>
        <div>
            <asp:Button ID="btnValidate" Text="Validate" runat="server" />
        </div>
    </div>
    </form>
</body>
</html>

 

Running the web form and clicking on the button while we
have bad data will generate validation error as expected:
WebForm Validation Results

Summary

In the post I showed one way to create an ASP.NET data annotation
validator. In other frameworks like ASP.NET MVC or WCF RIA Services
you have such validators implemented.

Posted: Apr 08 2010, 07:48 AM by Gil Fink | with 6 comment(s) |
תגים:,

Open Data Protocol – Open Protocol For Working with Data Article

Open Data Protocol – Open Protocol For Working with Data Article

I wrote an Hebrew articleOpen Data Protocol – Open Protocol For Working with Data Article
about the OData protocol.
I explain there what is
the OData protocol, why
you should think about
using it and make a brief
overview. You can download
it from here.
If you like please provide feedback.

Enjoy!

OData Visualizer Extension

OData Visualizer Extension

Yesterday I wrote OData Visualizer Extension
about VS2010
extension manager.
One of the great
extensions that you
can download and
use is the OData Visualizer.
The OData Visualizer helps
us to get a visual graph of the OData Protocol’s types, properties,
associations, and other aspects of the EDM which you get
from an OData metadata endpoint.

Installing OData Visualizer

Installing the OData Visualizer is very easy. Go to your Extension
Manager and search for OData Visualizer in the online gallery.
Once you find it just install it and then restart VS2010 in order to
it to be available. It is also available in the Visual Studio Gallery
from here.

Setting the Environment

In order to use the OData Visualizer you need to have an OData
metadata endpoint which is referenced in a project. In the example
I use the following WCF Data Service which was created on top of
a school EDM:

public class SchoolDataService : DataService<SchoolEntities>
{    
  public static void InitializeService(DataServiceConfiguration config)
  {
    config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);      
    config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
  }
}

I have created a console application and created a service 
reference to the service I showed above.

Using the OData Visualizer

In the Solution Explorer click the right mouse button on the created
service reference and choose the View in Diagram menu item:
View in Diagram

This will result in the following OData Protocol Model Browser:
OData Protocol Model Browser

After opening the OData Protocol Model Browser you can
start visualizing your model. Use the Conceptual Model Content to
add all the aspects you want to visualize. For example, after I click
on add all for Entity Types this is the graph I get:
Entities Graph

You can also see in the right menu that I have a model browser that
helps to navigate the model and see all its aspects. You can also
export the model into a XPS file if you like.

Summary

When using OData Protocol if you want to see a visual representation
of the model you can do it using the OData Visualizer. As I showed
in the post it is very easy to install it and to use it as a VS2010
extension. I found that tool very useful and I recommend you to
download it too.

VS2010 Extension Manager

VS2010 Extension Manager

One of the great vs2010 logo
features in VS2010
is the extension
manager. In last
DevAcademy4
conference I talked
about it a little in my
session and showed 
an extension that I use.
Lets see what is it all about.

Using The Extension Manager

The extension manager in VS2010 is a manager that help to
manage and discover extensions to VS2010. In order to use it
we only need to go to the Tools menu and choose to use the
Extension Manager menu item. The following figure shows how to
start the extension manager:
Open Extension Manager 

After opening the manager we get to the following menu:
VS2010 Extension Manager

As you can see you can see all the installed extensions, to disable them or
uninstall them. Also You can discover extensions that exists in the online
extensions gallery:
Online Gallery

The last thing you can do is to look for extensions updates if they exists:
Extensions Update
As you can see there are no available updates for the extensions I use.

Summary

Using the extension manager is very simple and intuitive. It enables
great way to extend VS2010 as we wish or need. Of course if you like, you
can create your own extension but this is a story for another post.