Monday, March 9, 2009
Valuable custom LINQ provider tutorials
1. Old, good LINQ to LDAP by Bart De Smet
2. Surprisingly complete tutorial by Matt Warren where a LINQ-to-SQL-like custom provider is explained very thoroughly.
Do not also miss the LINQ's Dynamic Query helper and the MetaLINQ to discover other interesting variations on LINQ.
Friday, March 6, 2009
DevExpress XPO - incomplete Linq support
In general, XPO is great. I like it because of two features:
- the ability to automatically update the database schema when connecting from the new version of the object model
- the default "mark-as-deleted" way of removing objects
There's however one scar on its beautiful face - incomplete Linq support.
No matter how fancy the Linq-To-Whatever implementation is - without Skip and Take it can never be fully adopted in enterprise systems. And XPO's implementation of Linq lacks the support of the Skip operation.
I am afraid that this is because XPO's implementation of paging is flawed by design: if you forget about Linq for a second, the only way to paginate is to use the XPPageSelector over your collection.
1: /* initial collection*/
2: XPCollection<TheType> ds = new XPCollection<TheType>(TheSession);
3: 4: /* paging */
5: XPPageSelector ps = new XPPageSelector(ds);
6: 7: ps.PageSize = PageSize; 8: ps.CurrentPage = PageNumber; 9: 10: return ds;
If you run the above code and in the same time you trace queries which are executed, you'll learn that:
- first, the whole collection of objects' identifiers is retrieved from the data source
- the page selector selects the identifier subset which refers to the page you select
- then, another query retrieves all the columns but only from the selected page of items
1: /* first query sent by xpo to retrieve all the data */
2: select N0."OID" from
3: "dbo"."X_RejestrDostepu" N0 4: where N0."GCRecord" is null order by N0."Data" asc
5: 6: /* xpo engine selects identifiers of objects in selected page */
7: 8: /* another query - 9: selected page is retrieved by manually providing identifiers
10: */11: exec sp_executesql N'select
12: N0."GCRecord",N0."OID", .... ,N0."OptimisticLockField" 13: from "dbo"."X_RejestrDostepu" N0 14: where (N0."GCRecord" is null and N0."OID" 15: in (@p0,@p1,@p2,@p3,@p4,@p5,@p6,@p7,@p8,@p9))',16: N'@p0 int,@p1 int,@p2 int,@p3 int,@p4 int,@p5 int,@p6
17: int,@p7 int,@p8 int,@p9 int',@p0=31,@p1=32,@p2=33,@p3=34,@p4=35,@p5=36,@p6=37,@p7=38,@p8=39,@p9=40And if you realize that there are in fact two queries required to retrieve selected page of data, then you imagine how ineffective (difficult?) this could be when implementing Linq's Skip this way!
It's then no surprise that the only answer to the "when the Skip operator will be supported?" is "sorry, Skip is not supported":
http://community.devexpress.com/forums/p/72977/248858.aspx
Edit: if you find this post in early 2010 or later please consider it outdated. Both skip and take are now correcly handled by XPO's Linq provider. I've blogged about it.
C# Puzzle No.13 (advanced)
Using LinqToSQL is fun and speeds up a lot of things. However, there are issues with LinqToSQL which confuse people. Ultimately, some of these people tend to think that LinqToSQL is useless because things that should be obvious are not such obvious. Over a year ago I wrote a short blog entry on one of such basic issues.
Another such "not-so-obvious" thing is the issue of "ordering". One of the common requirements is to be able to order by the name of the property and not by the property itself. For example, if you use ObjectDataSource, then you know that the sorting parameter is passed to the object responsible for data retrieving by name of the parameter.
Let's take a look at two LinqToSQL ordering attempts:
1: ConcreteDataContext ctx = new ConcreteDataContext();
2: 3: /* this is easy */
4: var list = from elem in ctx.TheTable
5: orderby elem.Property 6: select elem; 7: 8: /* this will compile
9: however it does not work
10: */
11: string PropertyName = "Property";
12: var list = from elem in ctx.TheTable
13: orderby PropertyName 14: select elem;In the example code above, the first linq clause is obvious - the ordering uses the property "Property" in a direct way. However, in in the second clause we use the name of the property.
You are to answer two following questions:
1. Why the second clause does not produce correct results, although it compiles correctly?
2. How is it possible then to build generic linq expressions which sort objects by names of their properties.
By generic I mean that following solution is not acceptable:
1: switch ( PropertyName )
2: {3: case "Property":
4: 5: return from elem in ctx.TheTable
6: orderby elem.Property 7: select elem; 8: 9: case "AnotherProperty":
10: 11: return from elem in ctx.TheTable
12: orderby elem.AnotherProperty 13: select elem; 14: 15: ... 16: 17: }Wednesday, February 18, 2009
Beware when you upgrade ...
When Windows Media Player 11 came out, I've upgraded from WMP 10 immediately. To me, a new version always means new functions, enhanced compatibility, stability and security.
I got no problems with WMP 11 until I've bought two great soundtracks by Jeremy Soule from DirectSong. These soundtracks are protected by the DRM - you are required to obtain a valid license from the soundtrack provider to be able to play it with the Windows Media Player.
To be able to backup your downloads, DirectSong says that:
Our current licensing is set up to allow unlimited Soundtrack CDs to be burned per machine download.
Great, this does not work in WMP 11 - you learn from the WMP that the license does not allow you to burn, synchronize or even play the music (which does not stop the music from actually playing!).
After few nervous hours spent trying to find out what's the problem, I've learned from someone's blog that you have to downgrade to WMP 10 to get this to work.
I don't remeber beeing so disappointed by a new version of the Microsoft's software for a long time. A new version which breaks the backward compatibility is not something which I could accept.
Friday, February 6, 2009
Inject application-specific code into ASP.NET module
We often write ASP.NET modules to customize ASP.NET processing pipeline - extend security, etc.
1: public class ExampleModule : IHttpModule
2: {3: #region IHttpModule Members
4: 5: public void Dispose() { }
6: 7: public void Init( HttpApplication context )
8: {9: context.BeginRequest += new EventHandler( context_BeginRequest );
10: } 11: 12: void context_BeginRequest( object sender, EventArgs e )
13: {14: // extend the processing pipeline by providing
15: // custom code for particular events, in this case
16: // the BeginRequest event
17: } 18: }However, as modules are static, in a sense that a module is active or inactive in processing pipeline, applications which "host" modules are dynamic, in a sense that different applications work under different conditions.
The issue we've faced recently was to inject a custom, application specific code into module:
1: void context_BeginRequest( object sender, EventArgs e )
2: {3: // how to call an application-defined code
4: // but do it so that the module is not
5: // rewritten everytime application changes
6: 7: // ?
8: }The solution we've came up with was rather simple: we've used a custom provider to provide application-specific code.
1: <system.web>
2: <specificProvider defaultProvider="ApplicationSpecificProvider">
3: <providers>
4: <add name="ApplicationSpecificProvider" type="Namespace.ApplicationSpecificProvider" />
5: </providers>
6: </specificProvider>
This way we can configure different providers on the application level but still be able to write generic module code:
1: void context_BeginRequest( object sender, EventArgs e )
2: { 3: HttpApplication app = (HttpApplication)sender; 4: 5: SpecificProvider.DoSpecificOperation( app ); 6: }Thursday, January 29, 2009
C# Puzzle No.12 (intermediate)
Consider following class which stores the information about external urls.
1: class LinkInfo
2: {3: public int Ord { get; set; }
4: public string Url { get; set; }
5: }In your application you somehow retrieve the list of such items:
1: List<LinkInfo> l = new List<LinkInfo>()
2: { 3: new LinkInfo() { Ord = 1, Url = "" },
4: new LinkInfo() { Ord = 2, Url = "test1" },
5: new LinkInfo() { Ord = 3, Url = "test1" },
6: new LinkInfo() { Ord = 4, Url = "test2" },
7: new LinkInfo() { Ord = 5, Url = "" }
8: };Your goal is to use Linq to filter this list in a special way:
- if the Url is empty - the item is always returned
- if the Url is nonempty - only one item with such Url is returned
In the above case the Linq expression should return:
1: { 2: new LinkInfo() { Ord = 1, Url = "" },
3: new LinkInfo() { Ord = 2, Url = "test1" },
4: new LinkInfo() { Ord = 4, Url = "test2" },
5: new LinkInfo() { Ord = 5, Url = "" }
6: };or
1: { 2: new LinkInfo() { Ord = 1, Url = "" },
3: new LinkInfo() { Ord = 3, Url = "test1" },
4: new LinkInfo() { Ord = 4, Url = "test2" },
5: new LinkInfo() { Ord = 5, Url = "" }
6: }
How effective is your solution? Can you not only think of just a solution but of an effective one?
Thursday, January 22, 2009
NTE_BAD_DATA (0x80090005) on CryptImportKey
The CryptImportKey docs says that NTE_BAD_DATA can occur when importing a key when
Either the algorithm that works with the public key to be imported is not supported by this CSP, or an attempt was made to import a session key that was encrypted with something other than one of your public keys.
This has been exactly the case in my scenario. I generate RSA public/private key pair using .NET and RSACryptoServiceProvider:
1: RSACryptoServiceProvider rsa = new RSACryptoServiceProvider( 2048 );
2: 3: File.WriteAllBytes( @"capipublic.key", rsa.ExportCspBlob( false ) );
4: File.WriteAllBytes( @"capiprivate.key", rsa.ExportCspBlob( true ) );
and then try to use these keys to encrypt/decrypt data in C++ using CryptoAPI.
It seems that the default MS_DEF_PROV provider is uncapable of importing a 2048-bit key and it just returns with NTE_BAD_DATA.
However, initializing the crypto context (CryptAcquiteContext) with more powerful CSP is enough, in this case the the MS_STRONG_PROV.
More on Crypto Service Providers here.