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.

if (myVar == null)
    return myVar = null;

As an additional reason, the Resharper tooltip about the row number 2 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, and then, obviously, configure the IIS authentication for the site/virtual directory that host your service to enable Windows Authentication and disable Anonymous access.

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,  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.

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:

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:

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:
(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:

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:

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

 unapregieratraduebicchieridigin 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!

Internet Explorer 7 and 8 will download stylesheets twice if the http(s) protocol is missing

This is hard to believe, but is true:

Internet Explorer 7 & 8 will download stylesheets twice if the http(s) protocol is missing.

If you have a page with mixed protocol url request (i.e. a https page with tags “link” or “script” with http links), Internet Explorer displays a security warning.

This is a security warning which alerts the user that a web page requested by a security connection (https) contains web request using a non secure connection (http) as well. It’s not clear what is the answer that user must supply to this message to download both the secure and unsecure content. To make things more complicated, this answer is different between Internet Explorer version 7 and 8 (strange but true, too). In fact, in version 7 user had to click the “Yes” button (the default one), but in version 8 user would have to click “No” (it’s incredible, I know it, but it is so).

So, to avoid this confusion, it’s necessary avoiding mixed content on https requests, and this can be obtained using the short sintax for urls, that is a special sintax in which the protocol part of the url is missing.

Doing this browsers automatically use the same protocol as web page, and the problem seems solved, but Internet Explorer version 7 and 8, in this particular condition (missed protocol), download stylesheets twice, as you may easily notice using any software for capturing the http traffic, like HttpWatch

Hard to imagine, right ?

Snippets code #1 – Extension method to raise an event via reflection

This extension method, applied to the object class and then available for all classes, allows to raise any events via reflection, providing as parameters the event name (as a string) and the TEvenArgs generic parameter.

Example of use:

CustomerViewModel vm = new CustomerViewModel();
vm.Raise("PropertyChanged", new PropertyChangedEventArgs("Name"));

Source for code in this example

AddessAccessDeniedException in WCF 4.0

If you host a WCF service on a machine with UAC enabled, Vista or Win7 for example, you might run into a seemingly strange exception:

The reason is due to the fact that to host a WCF service you need to register its url, and this task requires administrator privileges, and this means as well that if you run Visual Studio as Administrator everything works fine, but what if you don’t have this possibility ? Or how to register an URL for it to work ?

If you follow the link mentioned in the error message you waste your time because the resulting link is too general for this specific error. I used this approach: I downloaded HttpNamespaceManager, a little and nice open source utility (not an official Microsoft tool), also provided with source code, that just does this, register an URL even assigning permissions to users.

After the URL registration your service will work fine.

Default endpoints in WCF 4.0

Starting from WCF 4.0 it’s possible to use a default endpoint in absence of explicit configuration. This means that you can avoid to configure an explicit endpont because of a default mapping between protocol schema and bindings described in the configuration file machine.config.

Here is the default content of that mapping:

For example, in the case of presence of “http” in the protocol, it will be used the default binding “basicHttpBinding” without the need to configure an endpoint explicitly.

Now, to test this new feature all you need is to create a simple service without an explicit endpoints configuration and then read hits configuration such as the following example:

This code in .Net Framework 4.0 will work fine, while .Net 3.5 would have required the endpoint configuration

Visual Studio 2010 compilation message error “The exec task needs a command to execute”

If it happens this strange and cryptic error in Visual Studio 2010 while compiling any project:

“The exec task needs a command to execute”

the reason is this: in any pre or post build event, there is a carriage return character to remove, because Visual Studio 2010 poorly digested the carriage return characters in ‘text editor pre-post build events.

How to call a controller action by jQuery

With jQuery you are able to invoke an action of a Asp .Net MVC application’s controller.
This is the code you need:

You can establish the request type (GET, SET and so), whether the request should be asynchronous or not (parameter async true or false), whether the request should be cached or not (parameter cache), a Javascript function to be called in case of success of the server request (parameter success) or in case of request fails (parameter error).
The parameter “data” of the function called in case of success contains the return value by the server call.

However there are many others useful parameters you can use. For a complete list go here. It’s also possible to make the same call but with a Json return value by the $.getJSON funtion.