Contents tagged with .NET
Sometimes it makes sense to send several queries at the same time to the database server. This prevents multiple roundtrips and normally can provide results faster. Knowing this, NHibernate offers two features: multiqueries and future queries. Future queries build upon multiqueries and because they use LINQ, which is probably the most common querying API in NHibernate, I will focus in this.
In order to use future queries, you queue them, by calling the ToFuture() or ToFutureValue() extension methods on any number of queries that you wish to retrieve together:
Only after you actually access its results are the queries sent:
And the generated SQL is:
Notice how the two queries are sent at the same time, separated by a semicolon.
It also works for single values, they can be combined with multi value queries:
The caveat is that this, like multiqueries, is right now only supported in SQL Server, Oracle and MySQL. In all the other cases the results will be retrieved immediately.
Another post on the Unity series, this time, adding interfaces to proxies. Previous posts here (Registration by Convention), here (Injecting Values), here (Extensions), here (Aspect-Oriented Programming), here (Dependency Injection) and here (Introduction).
Unity can be used to inject additional interfaces to proxies generated for some type. We can easily add these interfaces at registration time but then we need to implement a behavior that can intercept calls to these interfaces and act accordingly.
A typical example is implementing INotifyPropertyChanged. Let’s see how we can register a type with this additional interface, first, by XML:
And by code:
Now, let’s see the NotifyPropertyChangedBehavior class:
Finally, sample usage:
Still lots of things to talk about Unity, stay tuned for more!
Sometimes there is the need or desire to resort to Aspect-Oriented frameworks (AOP) in order to add some validations or cross-cutting concerns. In several situations, it is indeed necessary, but .NET already offers some hooks that we can use to achieve parts of this functionality. One of those is CodeAccessSecurityAttribute. In a nutshell, it allows the application of security checks whenever some code – method, property – is called. A somewhat well known example is PrincipalPermissionAttribute.
Let’s see an example of how we can restrict a method so that it can only be called on a specific day of the week:
The Intersect, Union and IsSubsetOf methods really don’t apply in this simple case, but the Demand method does: this is where the actual logic goes. The example should be pretty straightforward. One thing to keep in mind, though: classes inheriting from CodeAccessSecurityAttribute should expose a public constructor with a single SecurityAction parameter, otherwise, it won’t be called.
The attribute can be applied as:
But this technique can be used for things other than permission checks. Let’s see logging applied to a class:
Yes, I know… it really has no access to method parameters, and it really doesn’t anything really productive, it’s just an example, remember!
An example of its usage:
If you have other usages, please send them to me, I’ll make sure to refer where they came from!
This one is a real treat!
When we use NHibernate or any other O/RM, we normally use classes to represent the database objects (tables or views). In NHibernate, this is called Entity Mode POCO – Plain Old CLR Object. NHibernate, however, supports other Entity Mode: Map. This Entity Mode does not use “physical” classes, but instead, dictionaries (implementations of IDictionary)! This makes it great for mapping dynamic database objects without the need for real classes.
For creating a Map entity, we need to do a slight change in our usual mappings, here is a simple Parent-Child example:
You might not have noticed that I used entity-name instead of name in the <class> declaration, in <one-to-many> and <many-to-one>; this tells NHibernate that these classes will be mapped as Map, not POCO (the default). Alas, you cannot use mapping by code, because there is no physical class to map.
OK, so now we have a mapped Parent and Child. We insert them as this:
As for retrieving, also simple, just use the ISession methods that take an entityName parameter:
Each of these IDictionary instances will have an entry that has key “$type$” and contains the entity type name – in our case, either “Parent” or “Child” – as well as entries for each of the other mapped properties, associations and collections:
Entity Mode Map supports both HQL and Criteria querying APIs:
And it also supports executable HQL:
Cool, don’t you thing? Eat your heart out, Unnamed Framework!
In SharePoint, there are several web parts that allow us to have different contents depending on some conditions:
LoginView (ASP.NET): allows the definition of templates per authenticated or anonymous user;
SPSecurityTrimmedControl: displays contents based on the security permissions of the current user;
EditModePanel: for displaying contents in a web part page depending on its edit mode;
DataViewWebPart: allows the passing of parameters and the usage of XSL for rendering logic.
I imagine you are now rolling your eyes: DataViewWebPart? how come? Well, because it doesn’t need to point to a specific list or view (unlike XsltListViewWebPart), it is very useful for markup-based customizations that will only depend on parameters.
Let’s see an example:
You can use this technique for:
Including scripts and stylesheets;
Including server-side controls.
It’s just a matter of rolling out some XSL to the rescue!
You may be already familiar with the available parameters, but you can find the full list here: http://msdn.microsoft.com/en-us/library/office/ff630170(v=office.15).aspx.
Another SharePoint Designer-only solution that may come in handy! ;-)
Another not widely known feature of NHibernate: mixing client and server-side calls.
To illustrate this, imagine that you want to calculate the difference between a mapped DateTime property and the current time, DateTime.Now. The following query works in NHibernate, but not in other O/RM frameworks:
The generated SQL will only be:
But NHibernate will detect that the result needs to be combined with something from the client side and will return a TimeSpan. This mechanism is extensible – more on this in a future post.
In other O/RMs, which shall remain unnamed, you have to use LINQ to Objects after LINQ to Unnamed Framework:
Pretty cool, don’t you think?
Today I start a new series on lesser-known NHibernate features.
Besides the normal mapping of a class to a table (or view, for that matter), it is also possible to map a class to a query. Do note that this is not the same as having a class mapped to a table and using custom SQL for the INSERTs, UPDATEs, SELECTs or DELETEs, this is something different. This is called Subselect mapping - not to be confused with subselect fetching.
To demonstrate this, imagine we have a blogging model where a Blog has several Posts. We can map a readonly query between the two as (in HBM.XML):
In mapping by code, it would be:
It easy to understand that the class cannot be mutable: it makes no sense to change any of the properties, because they may not map directly to a table.
Querying is done in exactly the same way:
And the resulting SQL is:
Sometimes, when you are using a SPDataSource control to bind to some list control, you might need, inside of it, to fetch information from the item you are iterating over.
Imagine, for example, that you are displaying a list of sites. As usual with SharePoint, there are lots of options for doing this, but consider the SPDataSource approach, which doesn’t require any coding:
But now you want to display all lists of each subsite… What would you do then?
OK, we need to get, for each site listed, its id, and store it in some server-side control, such as HiddenField. Next, we add a nested SPDataSource, this time with DataSourceMode=ListOfLists, and add a WebID parameter:
If you are curious, the MSDN page SPDataSource.SelectParameters lists all predefined parameters that the SPDataSource will recognize automatically, and this page in Solutionizing .NET lists all fields returned by SPDataSource, in all of its modes. BTW, a great resource!
Sometimes we have an instance of some class that is not exactly the one we want. This can either be because it is not typed – is of type Object – or for some other reason. When that happens, we need to convert it.
There are several ways that the .NET allows for doing more or less automated conversions between types. I usually use the following function, which does this:
Matching type: if the destination type can be assigned from the source value type;
Destination type String: this is pretty obvious, just call ToString() on the source value;
Source type TypeConverter: if the source value provides a type converter and it can convert to the destination type, then use it;
Implicit and explicit conversion operators: if the source value has implicit or explicit conversion operators for the destination type, use them.
The code looks like this:
So, am I missing anything? Do let me know!
I had the pleasure to be the technical reviewer and I can recommend it to you! Hope you enjoy it!