NHibernate QueryOver is not a Linq provider (that is how to do join with QueryOver API)

Starting from NHibernate 3.0 a new API was build as a wrapper around the ICriteria object.

Obviously I’m talking about the powerful API called QueryOver. With this API you can build a wide range of query object, from the simplest to the more complicated one. But you need to remember that this API is not a Linq provider, and then you cannot apply those constructs typically applied in a Linq query. I explain with an example what I really mean.

Introduction: you have a data model with 2 table, Category and Customer, with a one-to-many relationship between them.

With Entity Framework and Linq To Entities it’s pretty simple to query data that belong to both entities, thanks to navigation properties and Linq provider, i.e. all customers that belong to a category with a specified Id, as shown in this example:

   1: var customersList = customers.Where(c => c.Category.Id == 1);

 

If you try to execute the same query with the same where conditions applied to a QueryOverObject, like this example:

   1: QueryOver<Customer> qu = QueryOver.Of<Customer>()

   2:           .Where(c => c.Category.Id == 1);

This code throws a NHibernateException saying that “could not resolve property: Category.Id of : MyNamespace.Customer”, suggesting to verify the mapping as property “Category.Id” could not be found”.

Obviously such a property doesn’t exist at all, it’s only the QueryOver API that concatenates the Navigation property and and its field named Id (in this example).

This means that: you cannot make a query with QueryOver API that refers to fields belonging to a navigation property in where clause….without explicitly defying a join between the object itself and its navigation property. An example will help to understand better.

   1: Category cat = null;

   2: QueryOver<Customer> query = QueryOver.Of<Customer>()

   3:                         .JoinAlias(x => x.Category, () => cat)

   4:                         .Where(x => cat.Id == 1);

I have defined a join with the JoinAlias method, which uses an alias (the Category object declared two rows before) to project the object under the navigation property. After that you can use this alias inside the others method (such as “Where” in this example) to refer to the navigation property field (cat.Id).

As you can see, the way you write the lambda expression inside a Linq provider’s where clause is quite different than the “”Where” condition of a QueryObject object.

Not even the logical operator “And” can be used in the same way. To apply this logical operator to the “where” filter you have to use the “And” method, as shown here:

   1: Category cat = null;

   2: QueryOver<Customer> query = QueryOver.Of<Customer>()

   3:                         .JoinAlias(x => x.Category, () => cat)

   4:                         .Where(x => cat.Id == 1)

   5:                         .And(x => cat.IsEnabled);

Pluralisation services in .Net Framework

Starting from .Net Framework version 4.0 developers have available a new service for converting a single word from singular to plural form, or from plural to singular form.

I’m talking about the class PluralizationService contained in namespace System.Data.Entity.Design.PluralizationServices in assembly System.Data.Entity.Design.

it’s very simple to use it:

string singular = "dress";
string plural = System.Data.Entity.Design.PluralizationServices
   .PluralizationService.CreateService(
      new System.Globalization.CultureInfo("en-US")
                        ).Pluralize(singular);
// returns "dresses"

or

string singular = "woman";
string plural = System.Data.Entity.Design.PluralizationServices
      .PluralizationService.CreateService(
            new System.Globalization.CultureInfo("en-US"))
               .Pluralize(singular);
// returns "women"

I don’t know how reliable a translation service inside a framework can be, but it’s use can be very useful.

Be careful because the only supported culture is “English” (so far). Then if you call the service with another culture, i.e. Italian (it-IT), you end up with a NotImplementedException, as shown here:

image

Dynamic build of generics types at runtime

How to create dynamically a type in .Net when it’s only known a string representation of that type, I think it’s an operation known to almost all .Net programmers, but what happened with types with type parameters (or generics) ?

In .Net is possible to create dynamically both generics with a known type, i.e. List<>, and generics with type in turn dynamically built.

Here’s an example:

a) Dynamic generated both type parameter and type

Type collectionType = Type.GetType("
         System.Collections.Generic.List`1, mscorlib");
if (collectionType == null)
    throw new InvalidOperationException("Invalid type");
 
Type genericType = Type.GetType("MyNamespace.MyType, MyAssembly"));
Type listWithGeneric = collectionType.MakeGenericType(genericType);    
var myList = Activator.CreateInstance(listWithGeneric) as IList;

b) Dynamic generated type parameter with a known type (System.Collection.Generic.List in this case):

Type genericType = Type.GetType("MyNamespace.MyType, MyAssembly");
Type listWithGeneric = typeof(List<>).MakeGenericType(genericType);
var myList = Activator.CreateInstance(listWithGeneric) as IList;
Technorati Tags: ,,

[ASP .NET] How to access Request data when HttpContext.Current.Request is unavailable

What happened if you need to access the HttpRequest object whitin the event Application_Start of an ASP .NET Web Application ?

Response: you end up with an exception like this:

image

Someone might observe that such event is not a valid place for a task like that, but sometimes things are simply different from those that appear at first sight.

So, if you want to get for example the virtual path or the physical path of a web application before the HttpRequest object is constructed  this is a valid solution:

   1:  HttpRuntime.AppDomainAppVirtualPath;
   2:  HttpRuntime.AppDomainAppPath;

Simply use HttpRuntime instead of HttpContext.Current.Request!

Technorati Tags: ,

How to enable Visual Studio Intellisense for NHibernate configuration files

If you are an NHibernate’s user and you want to benefit of the Intellisense support during the editing of its configuration files in Visual Studio 2010 environment, just copy these 2 files: nhibernate-configuration.xsd and nhibernate-mapping.xsd,  from the NHibernate zip into the following folder:

C:\Program Files (x86)\Microsoft Visual Studio 10.0\Xml\Schemas

where C:\Program Files (x86)\Microsoft Visual Studio 10.0 is your Visual Studio 2010 installation folder.

You’ll end up with the Intellisense support, like this:

image

Technorati Tags: ,

Javascript code block formatting

For those who develop applications using C# or Javascript, but I think Java too, (I’m not a Java developer and then I don’t know if what I’m going to say is true for them as well) ,  there are two kind of writing styles for indentation and code’s blocks formatting .

These styles, known as K&R (Kernighan & Ritchie) style and Allman style, concern the way the opening curly brace is opened, when defining a block of code.

The former places the brace in the same line as the preceding line of code, as you can see in this example:

   1:  return  {
   2:              name: "Joe"
   3:  };

the latter places the curly brace in its own line, as shown here:

 

   1:  return 
   2:          {
   3:              name: "Joe"
   4:          };

So, the question is:

Can I use both of these styles or not when writing code ?

The answer is: yes, except for Javascript code.

In Javascript you must always use the K&R style if you want to avoid some subtle bugs that may be very difficult to identify.

For example, if you used the code in Allman style showed below

the return value would be “undefined” and not an object as expected, because the browser insert a semicolon after the word “return”.

If the code below had written in K&R (Kernighan & Ritchie) style:

as shown in first example, the return value would have been an object as expected.

Tag di Technorati: ,

Raven2Go posts editor portable application

Raven2Go
Raven2Go is a valid alternative to blog posts editor much more famous like Word or Windows Live Writer, and it can even be installed as a portable application in a USB pen drive, feature very useful for people who often move from one pc to another.

Main features are:

  • Tabbed true WYSIWYG Editing
  • Manage multiple media storage services
  • Improved content management
  • Manage multiple blogs offline
  • WordPress 2.2+ Page & Tag support

Download

Powered by Zoundry Raven

HeidiSQL – Free portable client for Sql server and MySql

image  

Free portable client for Sql server and MySql.

This is the software I always needed!

Features:

Entity Framework for Oracle is dependent by an environment variable

Those who using Entity Framework Provider for Oracle have certainly already run into this issue, i.e., the proper functioning of this provider depends on an environment variable! It’s a bit strange, but it’s the truth.

If you forget (or if you simply don’t know) to setup an environment variable named “TNS_ADMIN” which contains the full path used by Oracle software to search for the “tnsnames” file, which in turn is used for reading the necessary parameters to establish a connection to the database server, attempting to open a connection will fail.

After setup the environment variable you have to reboot Visual Studio, if already opened, in order to apply the change.

After applying the environment variable if you try to create a new Oracle connection using the Visual Studio wizard, if all is working fine you will see the list of the tnsnames file entries in the data source dropdown list instead of a blank list.

Also, this environment variable needs only to Entity Framework for Oracle, as other software, like Toad for example, doesn’t need it to search for tnsnames files.

You can obtain the same result by adding a registry key, but it’s certainly easier to create an environment variable than modifying the registry.

Hope this helps.

Coding Horror #2

Some time ago I started writing a series of blog post (only one for precision) about some “absurd” code I meet in my daily work.

I called this series “Coding horror”, and, so far I have written only one post, this one.

This is the second one.

About the code below, I thing that every comment is unnecessary because it speaks for itself.

   1: if (myVar == null)

   2: {

   3:     return myVar = null;

   4: }

As an additional reason, the Resharper tooltip about the row number 3 is:

““Destination has the same value before assignment”.

It could not be much clearer than that.

Technorati Tags:

WCF 4.0 and its defaults

The default endpoint and default binding provided by WCF 4.0 are obviously great features that can save developing and testing time, but sometimes this conventional configuration don’t help in case you have some trouble with certain setting that doesn’t work.

The setting I mean in this case concern the Windows Authentication over HTTP.

To enable this setting you have only to configure the basic http bindings with a specified security mode, like that:

WcfService1 - Microsoft Visual Studio (Administrator)_2012-06-06_15-08-13

and then, obviously, configure the IIS authentication for the site/virtual directory that host your service to enable Windows Authentication and disable Anonymous access, like in this example:

HelpDesk-DEV - IT-S-HDDEV01 - Remote Desktop Connection_2012-06-06_14-47-53

If you make this two simple change, you end up with an ASP .Net error page which says this:

“Security settings for this service require Anonymous Authentication, but it is not enabled for the IIS application that hosts this service”,

that is to say that the Windows Authentication isn’t working and the service requires Anonymous Authentication that is not enabled and then here’s the error.

Why although the configuration is it not working? Because you have not specified a binding for your service, and then the default binding comes into play, and the default binding requires Anonymous Authentication, which is not enabled.

The next logical step is to provide a specific binding configuration, like this:

WcfService1 - Microsoft Visual Studio (Administrator)_2012-06-06_15-28-21

which maps the binding named “BasicHttpEndpointBinding” defined early with your service.

But when you run the service the error is always the same. What’s wrong with this configuration ?

The problem here is the service name you provided. This name must match with the service name written inside the .svc file of your service. If this name doesn’t match, the explicit binding configuration doesn’t match with those provides by your service as well, and then you fall into the default binding behavior again.

Otherwise, if the service name matches everything works fine.

Moral of the story: “Pay always attention to the default values of any configuration”!

Web services Contract First development

WSCF.blue is a great tool for developing web services in a Contract First mode.

Develop in such a way means that you start from a WSDL contract that describes everything is concerned with a web service, and only after that you can write code which  that contract is based on.

Working with a WSDL can be a very error-prone task because a WSDL is a XML file. The WSCF.blue tool is able (among other things) building the server code you need from that file.

But this tool is also useful in some particular scenario where you have to change the web service code that “answers” to a particular call. I will explain it better.

Imagine you have a old application using a old web service developed by a third part, and you don’t have the source code of that service. What if you have to rewrite the web service for changed requirements without affecting the application which use it by simply changing the service’s url in configuration files ?. in other words, it needs to create another web service’s implementation without changing the WSDL in any way. In this case WSCF.blue can greatly save your time recreating the server code starting from the WSDL input, and with this server code you can write the new implementation. At this point you can just change the url of the service in application which was using the old implementation.

As unit test, it is possible to add a proxy reference to the old implementation of the service. After that you can create a new instance of the service by the proxy, change the url property and invoke methods and obviously the new service’s implementation at the new url will respond.

How to debug Log4Net

If you use Log4Net as log engine for your applications (in my opinion is the best choice), this simple row in application configuration file can save you by a waste of time and probably by a headache too.

<add key="log4net.Internal.Debug" value="true"/>

When Log4Net doesn’t log anything due to a configuration error it never throw an exception, and this is the expected (and correct) behavior of a log system which should never block an application due to its internal error. Unfortunately when something went wrong it is quite difficult discover the reason if you don’t have a break in your code.

With that configuration instruction Log4Net “logs” its initialization process in output windows and in Trace system.

If you add a trace listener you can also save this output in a file.

Here’s an example:

<system.diagnostics>

  <trace autoflush="true">

    <listeners>

      <add 

        name="MyTraceListener" 

        type="System.Diagnostics.TextWriterTraceListener" 

        initializeData="C:\log\log4netInitialization.txt" />

    </listeners>

  </trace>

</system.diagnostics>

This is very useful in production environment where Visual Studio is not installed and then an output window is not available.

Technorati Tags: ,

Entity Framework #3–my scattered notes

When using Entity Framework 4.x Code First you can put your validation code in Data Annotations or inside the DbContext class (this is my preferred mode).

It’s possible to override the virtual method ValidateEntity exposed by the DbContext class and then define your own validation logic in one place.

This method is called once for each distinct entity being modified in your context, and it provides an opportunity for developers to stop the entity update process when some properties are in invalid state.

Here’s an example:

protected override DbEntityValidationResult ValidateEntity(

    DbEntityEntry entityEntry, 

    IDictionary<object, object> items)

{

   var errors = new DbEntityValidationResult(entityEntry, 

                                new List<DbValidationError>());

   if (entityEntry.Entity is Customer)

   {

       Customer customer = (Customer) entityEntry.Entity;

       if (string.IsNullOrEmpty(customer.Lastname))

       {

           var error = new DbValidationError("Lastname", 

                        "Lastname cannot be null or empty");

           errors.ValidationErrors.Add(error);

       }

   }

 

   if (errors.ValidationErrors.Count > 0)

       return errors;

 

   return base.ValidateEntity(entityEntry, items);

}

This code will be invoked only if the “ValidateOnSaveEnabled” property of the class DbContextConfiguration is set to true.

Entity Framework #2–my scattered notes Part 2

This is my second post about my Entity Framework Code First usage experience. You can find my first post here.

The Entity Framework Power Tool is a must-have tool for those who use EF in Code First mode, especially with fluent API. With this tool you can reverse-engineering an existing data source and then generate both domain classes (POCO) and the mapping configuration files. The latter are generated by creating a class which inherits from EntityConfiguration<T>, where T is your domain entity type. The tools is able to understand all the existing relations in the database and to transform them in the correct relation mapping in code.

Entity Framework #2–my scattered notes Part 1

Here are a few scattered notes on the use of Entity Framework 4.2 Code First:

  • The core EF Api is contained in the System.Data.Entity.dll assembly
  • The DbContext Object is a lightweight version of the ObjectContext object, the former provides more functionality than the first. If you need to get an ObjectContext instance starting from a DbContext instance you can use the IObjectContextAdapter interface for casting, as shown in the following example:
   1: (myDbContext as IObjectContextAdapter).ObjectContext;

  • The DbSet class is just a wrapper around the ObjectSet class
  • A Complex Type has some limitations, the main are: a) it can expose only properties with primitive types b) it cannot be exposed as a multi-instance (collection)
  • The EntityTypeConfiguration<T> class has an interesting method called WillCascadeOnDelete(bool), whose name makes the idea of the action it takes. Invoking this method with true parameter allows dependent data to be automatically deleted when main data is deleted, but you must pay attention to some aspects: a) it doesn’t work with optional relations but only with required relations b) The dependent data must be explicitly loaded into the context by invoking the “Include” extension method. If you don’t, there are no dependent data in memory and therefore no data will be deleted on database
  • Table splitting requirements: a) entities must have a 1 to 1 relation b) entities must share a common key
  • How a particular class is part of the EF context ? a) Because the context as a property DbSet<T> which reference that class b) Because the class is referenced by another class already tracked by the context c) Because you just inserted a configuration for that class and added to the model builder
  • EF supports three mapping inheritance typologies a) TPH (table per hierarchy) => a base type and all its inherited types are mapped to a single database table with a discriminator column b) TPT (table per type) => There are distinct tables for base type and all its derived types. The tables for derived types contain only the additional fields exposed, while the common fields are mapped to the base type’s table c) TPC (table per concrete type), very similar to TPT. The only difference is that all derived type’s fields are stored in separate tables and not only the common ones. For guidance on which typology to choose depending on various scenarios, you can see this link
  • EF Code First is based on conventions. Conventions are assumptions that can save developers from a lot of work when you define the mapping between domain classes and tables. For example, a convention states that the Id property of a class is also the primary key for that class. Conventions can be singly removed by code, as shown here:
   1: modelBuilder.Conventions.Remove<IdKeyDiscoveryConvention>();

Entity Framework #1 –How to get the original type of an entity when dynamic proxy is enabled

If your Entity Framework context is proxy-enabled, the runtime will create a proxy instance of your entities, i.e. a dynamically generated class which inherits from your entity class and overrides its virtual properties by inserting specific code useful for example for tracking changes and lazy loading.

The proxy instance has a dynamically generated name by the runtime that looks like this:

{System.Data.Entity.DynamicProxies User_00394CF1F92740F13E3EDBE858B6D599DFAF87AA5A089245977F61A32C75AA22}

(User is the original entity class name which the proxy class inherited from).

Starting from the proxy type, if you need to know the original type you have to use the static method GetObjectType of ObjectContext type, as shown in this example:

   1: var userType = ObjectContext.GetObjectType(user.GetType());

Through the FullName property of the type returned by this method you can get the full name of the original type (User in this example)

[OT] A very particular book

UnaPreghieraTra2BicchieridiGin

This is not the usual technical post that I generally write. Instead it is a post dedicated to my dear friend Nicola Gaeta, who has written a book about his passion (which is also my passion), the music. The book is called

Una preghiera tra due bicchieri di gin, il jazz italiano si racconta

published by Caratteri Mobili.

It’s a very good book and very particular, it has not the classic narrative style but is a passionate collection of interviews conducted by Nicola to the greatest exponents of the Italian jazz about ambitious and very interesting topics, to which is not easy to answer. The question that has remained impressed to me is

‘What is jazz?’ Friend, if you have to ask it, you’ll never know it (Louis Armstrong)”

It’s an instinctive book written by a music passionate that plays anything in everyday work (like me too), it’s the book of a dear friend of mine who reminds me the happy times when I was back in high school (many years ago), and very often I avoid studying to listen to his not-to-missing musical broadcasts on a local radio.

Enjoy your passion, Nicola.

UgiAlt.Net sessions

This is the list of UgiAlt.Net sessions to be held next on next Saturday, Jan. 21 in Milan, I chose to attend

  • TDD everywhere
  • WinRT e il futuro dello sviluppo per Windows
  • I Love Async!
  • SignalR. Code, not toothpaste. Using SignalR for realtime client/server communication
  • oData può rappresentare il futuro del DataLayer?

See you there!