Recently I was working on data access code using the Entity Framework 4.1 and Code First. I had a simple DbContext setup. Everytime I would add an object to one of the DbSets I created, I got this exception:
The provider did not return a ProviderManifestToken string.
The provider manifest token is part of the SSDL that tells the Entity Framework (and specifically the EF database provider) what version of the DB is being used. The problem is, since I was using code first, I didn't have an SSDL file.
Digging into the inner exception, I saw this message:
Could not determine storage version; a valid storage connection or a version hint is required.
Also not very helpful. Google wasn't much help either. It seems that these two errors (either in pairs or together) can be caused by things like permission errors and database configuration errors. None of them were the cause of this error in my case.
But after digging further, I finally realized that I had a typo in my connection string. I had DataSource= instead of Data Source=, i.e. no space. So, since this error seems to be another famously unhelpful error from Microsoft, I'll throw this suggestion out there to help you if you're running into the same issue.
Failures In Coding
Musings on ASP.NET MVC, WCF, Entity Framework, and other .NET related things.
Friday, December 2, 2011
Monday, November 14, 2011
Exceptions - More Expensive Than You Might Think
So, everybody knows that you shouldn't use exceptions in control logic right? Meaning, you shouldn't expect exceptions to be thrown and you shouldn't plan on reacting to them under normal code execution circumstances, right? Exceptions are, well, exceptional. They are the exception, not the norm.
Recently I wrote some code where I violated this rule in a manner that seemed innocent enough to me. I wrote an extension method for IDataReader that looked like this:
It's purpose was to check if a value exists in a data reader before trying to access it. I was looping through a data reader to populate an object, and I was doing a lot of converts (ToBoolean, ToDateTime, ToDecimal, etc), so I wanted to make sure the values existed. The column names matched property names on my object. I was looping through the properties of the object using reflection, and not all the properties were being populated from the database call that populated the data reader, so an exception was being thrown quite often in TryGetObject, because a lot of the data didn't exist.
I had written a web service method that called the database stored procedure I was using. Initially I noticed this was taking ~2.5 seconds to complete which I though was ridiculous. After looking through my code I saw that this was the only "wrong" thing I was doing, so I replaced it with a method that loops through all the columns of the data reader to check if one exists. This took my execution time down to ~150ms. That's a decrease of well over ten-fold.
So the moral of the story is: Exceptions are more expensive than you might think.
Recently I wrote some code where I violated this rule in a manner that seemed innocent enough to me. I wrote an extension method for IDataReader that looked like this:
It's purpose was to check if a value exists in a data reader before trying to access it. I was looping through a data reader to populate an object, and I was doing a lot of converts (ToBoolean, ToDateTime, ToDecimal, etc), so I wanted to make sure the values existed. The column names matched property names on my object. I was looping through the properties of the object using reflection, and not all the properties were being populated from the database call that populated the data reader, so an exception was being thrown quite often in TryGetObject, because a lot of the data didn't exist.
I had written a web service method that called the database stored procedure I was using. Initially I noticed this was taking ~2.5 seconds to complete which I though was ridiculous. After looking through my code I saw that this was the only "wrong" thing I was doing, so I replaced it with a method that loops through all the columns of the data reader to check if one exists. This took my execution time down to ~150ms. That's a decrease of well over ten-fold.
So the moral of the story is: Exceptions are more expensive than you might think.
Tuesday, November 1, 2011
How Uninstalling The .NET Framework Can Screw Up ODP.NET
Recently I started working on my first project that uses Oracle as the backend database. Since Microsoft has deprecated the Oracle client built into the .NET framework, I am using ODP.NET from Oracle. This client works well and follows the familiar patterns familiar to ADO.NET developers, i.e. Connections, Command objects, DataReaders, etc.
However, during development of the project I ran into a gotcha. I saw some other blog posts describing this same fix and resolution, but I figured one more on explanation on the internet couldn't hurt, right? More search results for the same problem :)
In the .NET Framework's machine.config file, DBProviderFactories for custom providers (i.e. non System.Data.Odbc, System.Data.OleDb, and System.Data.SqlClient providers) are listed in a <DBProviderFactories> element so the .NET Framework can instantiate connections them when you reference the provider in the provider attribute of the connection string. In the case of the Oracle ODP.NET client, the entry looks like this:
My gotcha happened when I uninstalled the .NET Framework to try and fix some sort of unrelated corruption issue. At the time I was unaware of this provider factory entry, so I was confused as to why ODP.NET would not work after I re-installed the framework. I could not create a connection. After a while, google finally told me that it is because the DBProviderFactory entry above was missing, since I re-installed the .NET framework and a fresh copy of the machine.config file was put on my machine.
A quick re-install of ODP.NET fixed everything. Fail on my part, I guess.
However, during development of the project I ran into a gotcha. I saw some other blog posts describing this same fix and resolution, but I figured one more on explanation on the internet couldn't hurt, right? More search results for the same problem :)
In the .NET Framework's machine.config file, DBProviderFactories for custom providers (i.e. non System.Data.Odbc, System.Data.OleDb, and System.Data.SqlClient providers) are listed in a <DBProviderFactories> element so the .NET Framework can instantiate connections them when you reference the provider in the provider attribute of the connection string. In the case of the Oracle ODP.NET client, the entry looks like this:
A quick re-install of ODP.NET fixed everything. Fail on my part, I guess.
Sunday, October 30, 2011
Calling WCF Service Methods With One Line Of Code
While WCF makes creating services (Web, TCP, etc) incredibly easy, it's client functionality, in my opinion, is not as easy to use. Most of this has to do with calling WCF service methods, and the method in which clients must be created.
To call a WCF service method, you typically do the following:
On the last line, we have to remember to close the connection. Remembering to do this is similar to remembering to de-allocate dynamic memory, or remembering to call IUnknown.Release() in the old world of COM. It's just not something modern developers want to worry about. The proxy generated by the Add Service Reference menu implements IDisposable so you could create the client in a using statement so the client is closed after the call. This could make cleanup easier, however there is a well known issue with using the using statement with WCF client proxies that is described here. Microsoft actually recommends you NOT use the using statement with a WCF client.
So, how can we make this process easier? By using generics, lambdas, and Expressions, we can create a client library that does all the cleanup for us, and allows us to call a WCF service method in one line of code. This post will show how to create an object that can be used to easily call any type of WFC service, such as Web services, TCP services, and the link. In a later post, I will show how to create a second object that can be used to specifically call RESTful web services.
To do this, we can create two interfaces:
It contains two methods. The first is used to create a
proxy to a web service defined by the interface TServiceInterface type.
The second, Close(), is used to close an open connection. Objects
implementing this interface are used to manage WFC Channel objects.
Here is the defiintion of IWCFServiceCaller<TServiceInterface>:
This interface contains a single method named CallServiceMethod, whose purpose it to call a method on the type TServiceInterface, via the supplied Expression object. Note the parameter is supplied as an Expression<> instead of a Func<> in order to facilitate creating an implementation of this interface that can be used to call a RESTful web service.
Let's look at the implementation of each. First, the class WCFServiceChannel, which implements IWCFServiceChannel. First, let's look at the constructor:
The parameters are all used to configure the WCF ChannelFactory object used internally by the GetWebServiceProxy() method. The first, bindingName, is the name of a binding configuration in the <system.ServiceModel> section of an app.config or web.config file. This configuration can be used to set properties of the binding such as SSL security, received message size, etc. Uri is, obviously, the uri of the WFC service. The third, bindingType, is the type of binding to create, i.e. basicHttpBinding, wsHttpBinding, etc. The last two parameters, userName and password, can be used to supply credentials to services that require them.
Next, here is the implementation of the GetWebServiceProxyMethod():
First, note that _channelFactory is a private member variable defined as follows. It is an instance of the ChannelFactory<T> object that is used to create the WFC Channel used for communication with the service.
Lines 73-84 check the _bindingType supplied in the constructor and create the appropriate binding, using the supplied _url and _bindingName from the configuration file. If supplied, the credentials are added to the _channelFactory, and then the channel is created and returned as an instance of TServiceInterface.
Now let's look at the implementation of IWCFServiceCaller. Here is the implementation of CallServiceMethod:
The implementation is pretty straight forward. Line 69 calls the _serviceChannel object (an instance of WCFServiceChannel supplied via a property on the WCFServiceCaller object) to get the client proxy. Line 72 compiles the supplied Expression object parameter and invokes the resulting function, supplying the client object as a parameter. The return type of the resulting function is the same as the return type of the method being called on the client proxy. An example will help to clarify this, but first note that in the finally block of try block, the _serviceChannel Close() method is called, ensuring that your channel is always closed for you and you don't have to worry about cleanup after a service call.
Finally, putting this all together, here is an example of how you call use the WCFServiceChannel and the WCFServiceCaller to call the GetProducts() method defined on our imaginary Northwind web service:
Lines 46-50 create the WCFServiceChannel and WCFServiceCaller. They are created within the same function as they are used, but since the WCFServiceCaller takes care of connection management for you by creating a new WCFServiceChannel on each call and ensuring the connection is closed, you could create and configure these two objects in a constructor or initialization function and share them throughout your class or application, something that you cannot easily do with a standard WCF client.
Lines 52-53 show how to use the WCFServiceCaller to call a method on a WCF service. The supplied lambda expression takes an instance of INorthwindService (as specified in the declaration of the serviceChannel and serviceCaller objects) and calls the GetProducts method. This lambda itself is then compiled and executed by the implementation of CallServiceMethod().
So, with a little work and creating a few classes, you can create a WCF service client that takes care of the initialization and cleanup for you, and allows you to call a WCF service method with only one line of code. In my next post, I'll show how you can create another implementation of IWCFServiceCaller specifically for calling RESTful web services.
To call a WCF service method, you typically do the following:
- Create the client proxy object.
- Call the service method.
- Close the connection.
On the last line, we have to remember to close the connection. Remembering to do this is similar to remembering to de-allocate dynamic memory, or remembering to call IUnknown.Release() in the old world of COM. It's just not something modern developers want to worry about. The proxy generated by the Add Service Reference menu implements IDisposable so you could create the client in a using statement so the client is closed after the call. This could make cleanup easier, however there is a well known issue with using the using statement with WCF client proxies that is described here. Microsoft actually recommends you NOT use the using statement with a WCF client.
So, how can we make this process easier? By using generics, lambdas, and Expressions, we can create a client library that does all the cleanup for us, and allows us to call a WCF service method in one line of code. This post will show how to create an object that can be used to easily call any type of WFC service, such as Web services, TCP services, and the link. In a later post, I will show how to create a second object that can be used to specifically call RESTful web services.
To do this, we can create two interfaces:
- IWCFServiceChannel<TServiceInterface>
- IWCFServiceCaller<TServiceInterface>
Here is the defiintion of IWCFServiceCaller<TServiceInterface>:
This interface contains a single method named CallServiceMethod, whose purpose it to call a method on the type TServiceInterface, via the supplied Expression object. Note the parameter is supplied as an Expression<> instead of a Func<> in order to facilitate creating an implementation of this interface that can be used to call a RESTful web service.
Let's look at the implementation of each. First, the class WCFServiceChannel, which implements IWCFServiceChannel. First, let's look at the constructor:
The parameters are all used to configure the WCF ChannelFactory object used internally by the GetWebServiceProxy() method. The first, bindingName, is the name of a binding configuration in the <system.ServiceModel> section of an app.config or web.config file. This configuration can be used to set properties of the binding such as SSL security, received message size, etc. Uri is, obviously, the uri of the WFC service. The third, bindingType, is the type of binding to create, i.e. basicHttpBinding, wsHttpBinding, etc. The last two parameters, userName and password, can be used to supply credentials to services that require them.
Next, here is the implementation of the GetWebServiceProxyMethod():
First, note that _channelFactory is a private member variable defined as follows. It is an instance of the ChannelFactory<T> object that is used to create the WFC Channel used for communication with the service.
Lines 73-84 check the _bindingType supplied in the constructor and create the appropriate binding, using the supplied _url and _bindingName from the configuration file. If supplied, the credentials are added to the _channelFactory, and then the channel is created and returned as an instance of TServiceInterface.
Now let's look at the implementation of IWCFServiceCaller. Here is the implementation of CallServiceMethod:
The implementation is pretty straight forward. Line 69 calls the _serviceChannel object (an instance of WCFServiceChannel supplied via a property on the WCFServiceCaller object) to get the client proxy. Line 72 compiles the supplied Expression object parameter and invokes the resulting function, supplying the client object as a parameter. The return type of the resulting function is the same as the return type of the method being called on the client proxy. An example will help to clarify this, but first note that in the finally block of try block, the _serviceChannel Close() method is called, ensuring that your channel is always closed for you and you don't have to worry about cleanup after a service call.
Finally, putting this all together, here is an example of how you call use the WCFServiceChannel and the WCFServiceCaller to call the GetProducts() method defined on our imaginary Northwind web service:
Lines 52-53 show how to use the WCFServiceCaller to call a method on a WCF service. The supplied lambda expression takes an instance of INorthwindService (as specified in the declaration of the serviceChannel and serviceCaller objects) and calls the GetProducts method. This lambda itself is then compiled and executed by the implementation of CallServiceMethod().
So, with a little work and creating a few classes, you can create a WCF service client that takes care of the initialization and cleanup for you, and allows you to call a WCF service method with only one line of code. In my next post, I'll show how you can create another implementation of IWCFServiceCaller specifically for calling RESTful web services.
Subscribe to:
Posts (Atom)