How to fix: "Could not find a base address that matches scheme http for the endpoint with binding WebHttpBinding" Errors

by jmorris 24. June 2010 14:30

After deploying a project from development environment running off of the VS development Web server Cassini to a production box using IIS, I noticed that all of my WCF service were all failing with the same HTTP 500 error:

The problem is that IIS needs to determine which base address in the bindings to host the service. However, WCF services only allows one service hosted under a site to be bound to one base address for a scheme. In situations where you have multiple services being hosted under a single site, the binding must specify a base address to use filter requests to t he specific service.

To resolve the issue, simple provide the base address in the baseAddressPrefixFilters section of the web.config:

By adding the prefix above, only requests with the specified base address above will be passed through. All others will be blocked and a HTTP 500 error returned to the client:

"System.InvalidOperationException: Could not find a base address that matches scheme http for the endpoint with binding WebHttpBinding. Registered base address schemes are []"

Tags: , , , ,

WCF

Using Datatables.net JQuery Plug-in with WCF Services

by jmorris 17. May 2010 13:42

There are several JQuery plug-ins that provide the basic functionality of an html grid: paging, sorting, etc. In essence these plug-ins provide a consolidated display of the data and typically means of which to interact with the data (update, insert, delete, etc). I recently had the opportunity to work with the DataTables.net grid and have been very impressed.

The following post describes the steps I used to make the DataTables grid work in an ASP.NET Webforms environment using a WCF Service as an endpoint. I’ll also go over some of the pitfalls I ran into which required a bit of ‘tweaking’ to get things working smoothly. One cool thing was that for every roadblock, a workaround was quickly discovered. This is huge when investing any time or resources on any third party plug-in or control.

First up, if you are not aware of what the DataTables is, it’s a JQuery Plug-in that written by Allan Jardine. According to the DataTables website:

“DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, which will add advanced interaction controls to any HTML table. “

It offers a plethora of features including pagination, filtering, sorting, auto loading of data via Ajax, Fully theme-able by CSS, etc. The documentation on the DataTables website is thorough and the quality excellent. There are also forums…good stuff. Additionally DataTables is licensed dually under the GPL v2 License and the BSD license for those who inquire…

Here is an example of Datatables with built in JQuery UI theme support:

 
The WCF Service
Datatables allows you to either have client-side paging, sorting and searching, which is the default, or you can do it on the server. Doing it on the client is the simplest and easiest way to get up and running with Datatables, however you will quickly find that it leads to larger page sizes and longer initial load times as all of the data must be piped from the server before Datatables is ready.  Performing the actions on the server makes for much a much snappier and scalable UI, but it adds complexity.

In order to use a WCF service with DataTables, you have to both honor the signature that DataTables expects and the data must be returned in a format that DataTables expects. Fortunately this is relatively easy to do; you simple need to a) map the HTTP variables from the GET request and b) generate a JSON string matches a specific format.

The HTTP variables that DataTables will post are as follows:



Note that the websiteId and categoryId are custom variables and that for each column specified, additional variables will be posted for the following fields with a consecutive numerical postfix: bSearchable_0, bSearchable_1, bSearchable_2, etc.

For my example the following WCF service method was used:



Note that I only specified a subset of the parameters in the WCF method that Datatables posts with its GET request:
 

Too be honest, I do not know why Datatables sends so many (looks like one variable per option per column for most), but from the WCF service method perspective they are optional. Also, note that Datatables uses some form of Hungarian notation to qualify the variables type. While a bit confusing at first, it did help a bit when debugging. The variables that we did specify in the WCF service method signature will be used for sorting, filtering, paging, etc.

Datatables expects to receive a JSON object with a two dimensional array called “aData” from this service. Here is an example of the server output that Datatables will receive:
 


Where “d” is the wrapper type appended by WCF and from the Datatables website:

 

Basically, note that the service must correctly compute and return the “iTotalRecords”, “iTotalDisplayRecords” and the data in “aaData”. Also, the length of each data returned must match the DataTables jQuery definition provided on the web page where the data will be displayed.

Here is the complete code listing for the internals of the WCF service method:


 

Note that depending your architecture, this code may look considerable different. However the steps are same:

  1. Query the datastore based upon the passed in parameters
    1. Calculated paging values
    2. Column to search by
    3. Column to sort by
  2. Create a JSON return result matching the JSON structure defined above.

Another thing to note here is that Datatables does not send column names; it sends the ordinal of the column with respect to the table. In order to sort by a column or filter by a column, you need to resolve the ordinal to a column name of your datastore:

 

The GetSortFieldFormOrder(int order) returns a string column name based upon the ordinal of the column so that the datastore (in this case via a sproc call) can sort the data by the correct column.

The Convert(object record) method makes an array from the values of properties of an object: each becomes an “aaData” record that is returned and used by Datatables on the client.

Just an architecture note here: in my opinion there is too much “busy” work going on here at the service level. Ideally this will be refactored into your entities so that the behavior is encapsulated outside of your data “delivery”.

The Client Code
The client JQuery code for Datatables can be very simple or rather complex depending upon the formatting and features your situation requires. Below you will see the code that I used and I will explain the major initialization required for using Datatables with a WCF service.

 

Lines 4-6 I get a reference to the DOM element I will load into using a typical JQuery selector. Let me explain the relevant settings:

A.    I am using the Datatables built in support for JQuery UI Themes
B.    I am setting the “bServerSide” flag to true so that Datatables will use AJAX to get the data source
C.    The URL of the AJAX method to call for loading data
D.    Since I want to set some custom variables to post to my service method and I want to override the default HTTP POST method that Datatables uses for invoking the AJAX method, I am overriding the “fnServerData” callback with a custom implementation.
E.    Datatables uses POST be default, I overridden the AJAX method to use a GET
F.    The results from the server are then passed into the fnCallBack callback and Datatables can now render the results.

The target for the selector is a div element on an ASP.NET UserControl:

 

   kick it on DotNetKicks.com

Tags: , , ,

Implementing the Command Pattern

by jmorris 19. August 2009 22:38

Command Pattern Background

One of the most ubiquitous software patterns in existence is the Command Pattern:  “Encapsulate a request as an object, thereby allowing for the parameterization of clients with different requests, queue or log requests, and support undoable operations” – GOF. It is generally used in situations where the all of the information necessary for a future call can be ‘built up” sequentially and finally executed at a point in time in the future – i.e. each action is state-full.

A common scenario is an object used to build up a database request taking in several different parameters such as the database name and location, the stored procedure name, any data that needs to be passed to the stored procedure and possibly a transaction object. Once the command has been constructed and all required parts are defined, it is executed, which delegates an action to call the stored procedure on the database and return a result set or perform some operation on an object, with the provided parameters. In the C# world, we are talking about System.Data.DbCommand and its concrete classes such as System.Data.SqlClient.SqlCommand or any other database specific implementation of DbCommand (Oracle, MySql, etc.).

Here is the basic UML diagram of the Command Pattern:

The Command Pattern typically utilizes the following actors:
  1. Client – creates the command object providing the relevant information (parameters) needed to fulfill its obligations
  2. Invoker – initiates the action on the command so that it’s obligations are fulfilled, making the decision of which of the commands actions should be called
  3. Receiver – performs the command object’s obligations, whatever they might be – i.e. makes database call or some other action

The Command Pattern Implemented

The scenario is this: a service exists which takes as input a series of inputs (a query) and returns as output, the results of those inputs as an xml stream of attributes and values. Caching at the service level and several operations are also supported: filtering, sorting, paging, etc.

Each request varies by parameters and is encapsulated as a query object defined by the client. This query object is simply a data structure that contains the fields accepted optionally be the service. The query object is executed by a command object created by the client, who delegates control to the receiver encapsulated by it’s invoking one of its action methods.

The following diagram illustrates the implementation:

 

 

The Command implementation is very simple. It contains an ICommandReceiver reference and IQueryRequest reference which stores a reference to the current query being executed. The command delegates control to the receiver, which performs its work and returns back an IQueryResponse object containing the results of the query.

 

The ContentReceiver class implements ICommandReceiver interface and simply makes the call to the remote service via a WCF client. This happens to be a very simplistic implementation in that much of the heavy lifting (i.e. caching, query generation, etc.) occurs in the service. In this case, we are simply translating a client query into a SOAP request to access the services resources.


The client uses an IQueryRequest object to build up a set of parameters which are consumed by the service endpoint via the command object. The results are returned to the client with an IQueryResponse object. How the results are used is dependent upon the client.




Finally, a simple unit test illustrating the usage:

Tags: , , , , ,

WCF and Large Message Bodies

by jmorris 22. June 2009 16:39

I have been running into some situations WCF barfs on calls where the message body is very large:

"The maximum string content length quota (8192) has been exceeded while reading XML data. This quota may be increased by changing the MaxStringContentLength property on the XmlDictionaryReaderQuotas object used when creating the XML reader. Line 3, position 9381."

Took a little poking around to see what exactly was going wrong here, but a couple of posts got me going in the right direction. In fact, this is a real excellent exception message in that it tells me exactly what I need to do to resolve the issue: increase the MaxStringContentLength property on the XmlDictionaryReadersQuotas object that the BasicHttpBinding class is using. 

According to MSDN the MaxStringContentLength property:

 "Gets or sets the maximum size for a message that can be received on a channel configured with this binding."

The purpose of this restriction being the possiblity of DoS attacks on a publicaly exposed service caused by arbitrarily large messages. Since I am using TransferMode.Buffered, the message size is bound by the size of the MaxReceivedMessageSize by default.

This is the end result:

Tags: , , ,

Jeff Morris

Tag cloud

Month List

Page List