Blog on development in general, and specifically on .NET
If you want to validate the maximum number of characters that a string property can take, you might be lured into using MaxLengthAttribute. However, this won’t give you what you want: what this attribute does is, when a model is being generated, it provides the maximum length of the string field in the database, but does not perform any kind of pre-insert or pre-update validation. For that, you need to use StringLengthAttribute. This one is indeed a validation attribute, inheriting from ValidationAttribute, and will be called when EF is about to persist your entity, or when ASP.NET MVC validates a model as a consequence of a post. You can specify both the minimum (MinimumLength) as well as the maximum length (MaximumLength).
So, this time I decided to use Entity Developer to generate a database from an Entity Framework Code First model:
I was then asked if I wanted to synchronize my model with a database later on, which seems like a good idea:
Next, I am asked about the target server, interesting, all databases for which I have an ADO.NET provider installed are present:
A naming configuration screen for classes and properties is shown, similar to its NHibernate counterpart, with the curious exception of the option to remove invalid characters:
Next, some namespace and Entity Framework version options:
I chose Entity Framework 6 and then I got to chose the template:
Because I started with model first (or code first), I am presented with an empty diagram. Weird, I got a validation message about not being able to find the Entity Framework 6 assembly, but it didn’t seem to affect the entities’ generation:
While generating the model, we can add spatial types as properties (if the target database server supports them), which is nice:
It is also possible to specify stored procedures for the DELETE, INSERT and UPDATE operations, but only if one stored procedure exists in the model.
So, to add it up, everything worked as expected, the functionality is similar to that when using an NHibernate model.
Coming next, advanced usages of Entity Developer.
NHibernate offers two interfaces that can be used to validate an entity before it is saved or updated or to cancel its saving, updating and deleting: IValidatable and ILifecycle. They are an alternative to events, and don’t need anything else to work other than be implemented by some entity.
Here’s what a possible implementation of IValidatable looks like:
As you can see, you can cancel the current operation - save or update - by throwing an exception.
As for ILifecycle, it not only allows us to specifically cancel a save, update and also delete operation, but also to be notified as soon as the entity is loaded:
You even have access to the current session.
This is a classic feature of NHibernate, but some people don’t like it because it “pollutes” our POCO entities with NHibernate-specific features, which makes our entities less reusable, and forces us to reference the NHibernate DLL. It may, however, come in handy sometimes as a "poor-man's" event system.
I created a new model item of type NHibernate and chose the option to generate from the database:
Mind you, you need to have the database providers installed for the databases you want to access, Entity Developer does not include them.I was then presented with a list of database objects:
After I selected a few, Entity Developer shows the class and properties naming rules dialog:
Next, some more options, pretty complete. Very useful is the option to detect many-to-many associations and table per type inheritances. These will be the default settings, but we can override them on a class by class basis:
Interesting, the next dialog gives an opportunity to split entities among different diagrams according to the database object’s schema:
Finally, we get to choose the template that will be used to generate the classes (the only included one is for HBM.XML) and set some of its properties, like, generate a single file or one file per entity, implement standard methods such as Equals or GetHashCode, standard interfaces like NHibernate’s IValidatable, ICloneable and INotifyPropertyChanged, add data contract serialization attributes for WCF and add support for a validation framework (NHibernate Validator, Data Annotations or Enterprise Library Validation Application Block):
There are several templates available, in both C# and Visual Basic, which we can browse and select (others can be added manually):
The code is immediately generated, unless there are validation errors in the model, like, a table without primary key:
In the Model window, selecting a class or a property of a class, we can set its properties, I think all of NHibernate’s features are there, collection types, cascading options, id generators, etc, plus validation settings, which will be translated to the validation framework of choice.
The HBM.XML files are set as embedded resources, which is also nice, and the Web.config file is updated with the connection string to the selected database. Weird, the dialect was set to MsSql2005Dialect, which doesn’t make much sense since I was connecting to SQL Server 2014. It is possible to select another dialect through the user interface, but dialects and drivers appear as text boxes, not much of a help.
All in all, it’s pretty impressive, it seems that all NHibernate features are present – did I mention that it is even possible to configure filters? – making Entity Developer a very interesting product. Another strong point is the T4 template system, which, with some effort, allows us to generate code mappings or whatever we want. The only problem I see is that no template for NHibernate's built-in mapping by code is supplied, although one exists for Fluent NHibernate.
Next, Entity Framework.
I recently started to use Entity Developer, by Devart, to generate entities from my databases. It is a commercial product, mind you, and I am in no way affiliated with them, I just happen to like it, so I am going to talk a bit about it.
A very strong point is that it supports out of the box NHibernate, Entity Framework and the now half-forgotten LINQ to SQL, which makes it stand out from other products. This is not going to be a thorough review, but I will post more as soon as I explore things in more depth.
Look and Feel
In general, the UI has a classic Windows appearance, with multiple floating windows, and there are a couple of skins available, but I didn’t pay much attention to it.
There’s a Database Explorer window which allows us to browse our databases and to see what’s in there (tables, views, functions and stored procedures), plus we can drag objects from it into the Diagram window, which will add this objects to the model.
The Diagram window allows automatic layout of the objects in it, having each in different colors, adding notes (nice!) and new model items (classes, inheritances, associations, enumerations. A diagram can be “stamped” with the author’s details (name, company, version, date, etc), which is good if we are to print it or generate a bitmap from it (supported natively). It can be zoomed and there’s a Diagram Overview window that shows the full model at once, so that we can easily spot objects outside of the visible area.
There may be several diagrams for an entity model, the core of an Entity Developer project, and this model has it’s own window, on which we can explore it and see all the mapped database objects and corresponding model items, including inheritances, associations, components (complex/value types), etc. We also have there the list of templates available for the current project type.
There’s the possibility to generate a SQL script from the model, but in NHibernate projects, only databases SQL Server, SQL Server Compact Edition, Oracle, MySQL and PostgreSQL, this requires that the proper .NET providers are present. For Entity Framework projects, I could only find the option to generate the script for SQL Server, and, of course, LINQ to SQL only supports SQL Server as well. There’s an option for updating the model from the database as well, in case we chose to generate it from the database.
It is of course possible to validate the model, and the Error List window will present all outcomes of this validation, which can either be errors or warnings. A nice thing: double clicking on a notification, we jump directly to the model item that caused it. It would be interesting as well to have the option to quick fix the problem, but I reckon it’s not always possible or easy to do in an automated fashion.
When it comes to actually generating the code, there are an endless number of options, from capitalization of properties, lazy loading of associations, inclusion of foreign keys, etc. These settings are of course dependent on the project (NHibernate, Entity Framework or LINQ to SQL), because not all libraries have the same features. The generation is based on T4 templates, which is nice, because they are a standard in .NET. Only one template for each API is include, but it is very easy to write our own, by copying from an existing one and modifying it to our liking. I have yet to find a T4 debugger, Entity Developer, unsurprisingly, does not offer one.
OK, so far I have talked in general about Entity Developer, in my next posts, I will talk about NHibernate and Entity Framework specifics and also about advanced functionality.
You should that SharePoint usually offers lots of ways to do more or less the same thing, and, of course, filtering a list view is no exception! In this post I am going to talk a bit about the ways that you can do this.
Built-in URL Filtering
SharePoint’s list view controls (XsltListViewWebPart, ListViewWebPart, etc) recognize a number of parameters from the query string that can be used to filter and sort automatically a list view, without requiring any additional effort.
Filter by single value:
FilterField must be an internal field’s name and FilterValue is case insensitive.
Filter by single value and an operator:
The list of possible operators (FilterOp) is:
- Eq: equal (default);
- Neq: not equal;
- Gt: greater than;
- Lt: less than;
- Geq: greater or equal to;
- Leq: less or equal to;
- BeginsWith: the start of a string;
- Contains: part of a string.
You can add up to 10 FilterField/FilterValue/FilterOp entries, the items must match all conditions (AND operator). If you wish to filter on an additional field of a lookup field, use this syntax:
Filter by one of multiple exact values:
FilterName is also the internal name of the field and the values in FilterMultiValue are treated as case-insensitive. Separate then by ;.
Filter by one of multiple partial values:
The * character acts as a wildcard, matching anything before or after. Placing a term between * is the same as using FilterField/FilterValue with the Contains operator in FilterOp.
Filter by a taxonomy field:
If you want to filter by a managed metadata field, you can either search by the display name using FilterField and FilterValue, or you can use the ids of the terms. A little known fact is that all usages of managed metadata values – values of fields of managed metadata type – are stored in the TaxonomyHiddenList hidden list. If you want to filter by an id of a term, you need to use the following syntax (search by one of two values with FilterOp=In, values separated by commas):
Or by a single value (no need for FilterOp):
The FilterLookupId=1 is only there to tell SharePoint that it needs to search not by value (FilterValue) passed in the query string, but by term pointed by it. You can find the ids for FilterValue in the TaxonomyHiddenList list.
Possible values for SortDir are pretty obvious:
- Asc: ascending (default);
- Desc: descending.
You can only sort by a single field.
Filtering a XSLT Web Part by a Query String Parameter
Notice that in case the param value is not present in the query string, the second condition in the Or disjunction will apply, which will try to match an empty string inside of the Author (Created By) field, which will always be true. Be careful, however, that while this works most of the time, if you specify a value for param that is indeed part of the creator of the field, it will be matched. As of now, I don’t have an 100% foolproof solution for this, if you know of any, do let me know!
Filtering by a Form Field
This is a variation of the previous technique, where we use a Location of Form in a ParameterBinding. In this case, however, filtering will only be applied when the page is post back. Add the following HTML to your page:
And change the previous ParameterBinding to use the param input:
The Search button will cause a postback, thus applying the filter, and the Clear button will navigate to the current page, using the GET verb, thus clearing the filter.
If instead of HTML we want to use a server side control, we certainly can:
1: <ParameterBinding Name="param" Location="Control(param,Text)"/>
Filtering by a Web Part Connection
Filter web parts:
Another option is to filter by a web part that implements any of the filtering interfaces, used for supplying a value to another web part.
SharePoint Enterprise contains a collection of filtering web parts. These cover a number of scenarios:
- Filtering from a query string parameter;
- Filtering from a text box;
- Filtering from a date picker;
- Filtering from a choice of values;
- Filtering from a SharePoint list;
- Filtering from a Business Connectivity Service;
- Filtering from a SQL Server Analysis Services cube;
- Filtering from current user properties (id, profile property);
- Filtering from a field in the current page ().
For the sake of simplicity, let’s pick filtering from the query string. In a web part page’s edit mode, add the Query String (URL) Filter web part to a web part zone:
Next, add a connection from a list view web part in your page:
Again, you are free to do it in markup:
Do replace the ConsumerID and ProviderID by the actual IDs of your web parts, where ProviderID is the ID of the QueryStringFilterWebPart and ConsumerID is the ID of the list view web part and also the ConsumerFieldNames for the list field you want to filter on and ProviderFieldNames for the value you used in FilterName.
Filter by a custom web part:
All you need is to implement interface IWebPartField. Here’s a sample implementation of a web part that filters by a query string value, think of it as a poor man’s Query String Filter web part:
After you deploy this web part and add it to a page, you will be able to create a connection to a list view web part so as to enable its filtering.
Filtering an External List
An external list is filterable by a finder operation, which is an operation of type Read List that you configure on the external content type. You can use SharePoint Designer to create views on the external list on top of an existing Read List operation. In the view’s page, the finder method – the name of the operation, not its display name – is specified as a Method entry in the CAML for the View element in the XSLT list view web part, for example:
Of course, you can also specify parameters to a finder method (a filter):
Filtering by XSLT
The last technique is done on the “client-side”, through XSLT. This offers possibly the worst performance, since all records are retrieved before they are filtered, but the greatest flexibility, because you can apply conditional rules that would be very difficult, if not impossible, using the previous techniques. XSLT filtering can be applied on top of web part connections, external lists, etc.
So, in your XSLT list view web part, inside xsl:stylesheet, add something like:
This goes through all the returned records and outputs a message depending on the value of the PercentComplete field. Because it is a number field, we must use the syntax PercentComplete. (a dot in the end).
As you can see, a lot of functionality is available without having to resort to programming, SharePoint is very good at it. XSLT offers the greatest flexibility, because you can use conditional logic to express your exact intents. Whenever possible, however, try to filter records at CAML level, because less data will be returned.
Sometimes there is the need to show text inside HTML tags. For instance, in one occasion, I wanted to show just a portion of the contents in a Wiki field, but just the text. xsl:value-of will return the contents inside HTML tags:
This will return “This is some HTML contents”.
If in the other hand you want to show the HTML contents as is, use xsl:copy-of instead:
Which will return “This
is some HTML contents” (line break because of the DIV element).
However, if your variable is HTML encoded (> are >, < are <, etc), it’s a whole different matter. For that, you need to use a recursive template:
Will return “This is some HTML contents” as well. The logic is this:
- First, show anything before the first < (<), if it exists;
- Check if the parameter contains a <, and if so, call the template recursively passing as a parameter the text after > (>), which is supposed to exist;
- Otherwise, just output the parameter.
There are several posts out there on using SignalR to signal changes in a database, but because I really didn’t quite like any of them, I decided to write my own.
The possibility to detect changes in a database comes from the SqlDependency class. Other implementations exist, such as SqlCacheDependency and SqlNotificationRequest, but with these we don’t really receive a notification event. The process is a bit tricky, lots of people out there have problems. These classes only work with SQL Server non-Express, but there are equivalents for other databases, such as OracleDependency for Oracle.
Because I like to make things generic and reusable, I decided to encapsulate things in my class. Unfortunately, since SqlDependency does not have an ADO.NET base class, we have to use it directly.
So, my purpose is to:
Have a generic class that, given a database connection and SQL string that illustrates the changes I would like to detect, starts monitoring them, and raises an event whenever it sees changes;
I also want a SignalR hub that I can call from the outside – in this case, the changes event – and broadcasts a message about these changes.
First things first, here is the ChangeNotifier class:
It all starts with the Start method, which receives the name of a connection string stored in Web.config, and the SQL to use for detecting changes. When they occur, it raises the Change event. Action stops when the Stop or Dispose methods are called – do note that this class implements the Dispose Pattern, but in a particular way, because it is not meant to be subclassed. Whenever the OnChange event is raised, we need to set it up again, that’s how SqlDependency works. Because I don’t want to expose directly .NET classes, I created my own event classes and enumerations:
A connection named MyConnection should exist in Web.config, as well as a table SomeTable with a column SomeColumn. Do change those for your own.
Next, a SignalR notification hub:
What it does is merely broadcast to connected parties an OnChange message. We can get a reference to it by calling GetHubContext:
The call to $.connection should match you hub class, but using camel casing. The callback function onChange is the same as you call in ChangeNotificationHub and in the OnChange event handler.
And that’s basically it!
Some common gotchas:
Does not work with SQL Server Express;
There’s a specific order by which the connection and SqlDependency.Start must be called, if you stick to my code, it should work;
Your application pool identity needs to have permissions to connect to the notification queue, see them here;
Won’t work with any SQL query, a number of restrictions apply; see here;
SqlDependency is very sensitive, and you can easily run into problems if you try different things.
I just updated my Excel I mentioned before with lots of hopefully useful SharePoint references:
- Fields (enumeration, display name, internal name, id, type, CLR type, resource, group, description, etc);
- Content types (enumeration, id, parent, group, description, etc);
- List templates (enumeration, id, name, internal name, base type, category, description, etc);
- Site templates (enumeration, name, code, id, description, etc);
- List fields: fields of lists;
- Document library fields: fields of document libraries;
- SPDataSource fields: fields returned by SPDataSource.
Get it here and give me your feedback.