<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>maxtoroq.dev</title>
	<atom:link href="http://maxtoroq.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://maxtoroq.wordpress.com</link>
	<description>simple code</description>
	<lastBuildDate>Sat, 24 Oct 2009 02:24:25 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<cloud domain='maxtoroq.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://www.gravatar.com/blavatar/46a543b9d20fb67d4bb8321b56fb1244?s=96&#038;d=http://s.wordpress.com/i/buttonw-com.png</url>
		<title>maxtoroq.dev</title>
		<link>http://maxtoroq.wordpress.com</link>
	</image>
			<item>
		<title>C# 3.0: Mixing object &amp; collection initializers</title>
		<link>http://maxtoroq.wordpress.com/2009/08/03/c-3-0-mixing-object-collection-initializers/</link>
		<comments>http://maxtoroq.wordpress.com/2009/08/03/c-3-0-mixing-object-collection-initializers/#comments</comments>
		<pubDate>Tue, 04 Aug 2009 00:17:47 +0000</pubDate>
		<dc:creator>maxtoroq</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://maxtoroq.wordpress.com/?p=124</guid>
		<description><![CDATA[Of all the examples and tutorials I&#8217;ve seen describing collection initializers I never saw something like this:
CodeTypeDeclaration codeType = new CodeTypeDeclaration {
   Name = GeneratedTypeName,
   IsClass = true,
   BaseTypes = { typeof(SchematronValidator) },
   Members = { cctor, schemaUriField, executableField, schemaUri, executable }
};
Note that the BaseTypes and Members [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maxtoroq.wordpress.com&blog=905434&post=124&subd=maxtoroq&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Of all the examples and tutorials I&#8217;ve seen describing collection initializers I never saw something like this:</p>
<pre style="background-color:#dadada;font-size:100%;">CodeTypeDeclaration codeType = new CodeTypeDeclaration {
   Name = GeneratedTypeName,
   IsClass = true,
   BaseTypes = { typeof(SchematronValidator) },
   Members = { cctor, schemaUriField, executableField, schemaUri, executable }
};</pre>
<p>Note that the <code>BaseTypes</code> and <code>Members</code> properties don&#8217;t have a setter, therefore I&#8217;m not instantiating collections, only intializing.</p>
<p>This makes C# the most declarative of the imperative languages I know. It&#8217;s so cool I want to rewrite all my code!</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/maxtoroq.wordpress.com/124/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/maxtoroq.wordpress.com/124/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/maxtoroq.wordpress.com/124/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/maxtoroq.wordpress.com/124/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/maxtoroq.wordpress.com/124/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/maxtoroq.wordpress.com/124/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/maxtoroq.wordpress.com/124/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/maxtoroq.wordpress.com/124/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/maxtoroq.wordpress.com/124/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/maxtoroq.wordpress.com/124/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maxtoroq.wordpress.com&blog=905434&post=124&subd=maxtoroq&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://maxtoroq.wordpress.com/2009/08/03/c-3-0-mixing-object-collection-initializers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1056a38ecd323c658a8c9e93bb41b18d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">maxtoroq</media:title>
		</media:content>
	</item>
		<item>
		<title>SqlBuilder 2.0 &#8211; Tutorial</title>
		<link>http://maxtoroq.wordpress.com/2009/02/18/sqlbuilder-20/</link>
		<comments>http://maxtoroq.wordpress.com/2009/02/18/sqlbuilder-20/#comments</comments>
		<pubDate>Thu, 19 Feb 2009 03:13:41 +0000</pubDate>
		<dc:creator>maxtoroq</dc:creator>
				<category><![CDATA[ado.net]]></category>
		<category><![CDATA[dbextensions]]></category>
		<category><![CDATA[dynamic sql]]></category>

		<guid isPermaLink="false">http://maxtoroq.wordpress.com/?p=85</guid>
		<description><![CDATA[Overview
SqlBuilder is a class designed to make dynamic SQL tasks easier. The top design goals are:

The query should look like SQL, and all SQL queries should be possible.
SqlBuilder is about building SQL, not getting or mapping data, so it should not be bound to any particular data access implementation.

Let&#8217;s take a look at the first [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maxtoroq.wordpress.com&blog=905434&post=85&subd=maxtoroq&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><h3>Overview</h3>
<p>SqlBuilder is a class designed to make dynamic SQL tasks easier. The top design goals are:</p>
<ol>
<li>The query should look like SQL, and all SQL queries should be possible.</li>
<li>SqlBuilder is about building SQL, not getting or mapping data, so it should not be bound to any particular data access implementation.</li>
</ol>
<p>Let&#8217;s take a look at the first example:</p>
<pre style="background-color:#dadada;font-size:100%;">var query = new SqlBuilder()
   .SELECT("*")
   .FROM("Products")
   .WHERE("Name LIKE {0}", "A%")</pre>
<p>What makes SqlBuilder very easy to learn/use is that all methods have the same signature:</p>
<pre style="background-color:#dadada;font-size:100%;">SqlBuilder SELECT(string, params object[]);
SqlBuilder FROM(string, params object[]);
SqlBuilder WHERE(string, params object[]);
...</pre>
<p>The first parameter is a composite format string, as used on <code>String.Format</code>, and the second parameter is an array of the parameter values you want to use in your command. So, if we call <code>ToString</code> on the first example this is what we get:</p>
<pre style="background-color:#dadada;font-size:100%;">SELECT *
FROM products
WHERE name LIKE {0}</pre>
<p>Pretty much the same. The parameter placeholder is still there, and the &#8216;A%&#8217; value is kept in the <code>SqlBuilder.ParameterValues</code> collection. To turn this into a command we need a <code>System.Data.Common.DbProviderFactory</code> instance:</p>
<pre style="background-color:#dadada;font-size:100%;">var command = query.ToCommand(SqlClientFactory.Instance);
Console.WriteLine(command.ToTraceString());</pre>
<p>The output:</p>
<pre style="background-color:#dadada;font-size:100%;">SELECT *
FROM Products
WHERE Name LIKE @p0
-- @p0: Input String (Size = 2) [A%]</pre>
<p>The parameter placeholder is now replaced with a parameter name, and the parameter value is included in the command. To understand how this command is created you can read <a href="http://maxtoroq.wordpress.com/2007/10/29/implementing-a-stringformat-like-createcommandstring-params-object-extension-method/">my post about it</a>.</p>
<h3>Keeping track of the last clause</h3>
<p>SqlBuilder keeps track of the last clause to determine when to use separators like commas (&#8216;, &#8216;), logical operators (&#8216; AND &#8216;), etc, when building the clause body. This allows you to call the same method more than once:</p>
<pre style="background-color:#dadada;font-size:100%;">// SQL.SELECT is just a shortcut to new SqlBuilder().SELECT
var query = SQL
   .SELECT("ID")
   .SELECT("Name")
   .FROM("Products")
   .WHERE("Name LIKE {0}", "A%")
   .WHERE("CategoryID = {0}", 2); 

Console.WriteLine(query);</pre>
<p>The output:</p>
<pre style="background-color:#dadada;font-size:100%;">SELECT ID, Name
FROM Products
WHERE Name LIKE {0} AND CategoryID = {1}</pre>
<p>This is how you can dynamically construct the clause body. The &#8217;separator&#8217; feature is not for all clauses, for example, calling JOIN two times will append JOIN on both calls. Also notice we used a zero index for both parameter placeholders, but the output shows zero and one indexes. The format string must always use method-call-relative placeholders, SqlBuilder takes care of translating those to instance-relative.</p>
<h3>Dynamic SQL</h3>
<p>So far we&#8217;ve only used SqlBuilder to dynamically construct queries that are static, meaning the resulting SQL will always be the same. Let&#8217;s look at a real dynamic query example:</p>
<pre style="background-color:#dadada;font-size:100%;">void DynamicSql(int? categoryId, int? supplierId) { 

   var query = SQL
      .SELECT("ID, Name")
      .FROM("Products")
      .WHERE_If(categoryId.HasValue, "CategoryID = {0}", categoryId)
      .WHERE_If(supplierId.HasValue, "SupplierID = {0}", supplierId)
      .ORDER_BY("Name DESC"); 

   Console.WriteLine(query);
}</pre>
<p>Let&#8217;s call this several times with different arguments:</p>
<pre style="background-color:#dadada;font-size:100%;">DynamicSql(2, null);
DynamicSql(null, 3);
DynamicSql(2, 3);
DynamicSql(null, null);</pre>
<p>The output:</p>
<pre style="background-color:#dadada;font-size:100%;">SELECT ID, Name
FROM Products
WHERE CategoryID = {0}
ORDER BY Name DESC 

SELECT ID, Name
FROM Products
WHERE SupplierID = {0}
ORDER BY Name DESC 

SELECT ID, Name
FROM Products
WHERE CategoryID = {0} AND SupplierID = {1}
ORDER BY Name DESC 

SELECT ID, Name
FROM Products
ORDER BY Name DESC</pre>
<p><code>WHERE_If</code> is an extension method that takes an extra boolean parameter which indicates if <code>WHERE</code> should be called or not. Although you can implement the same logic explicitly writing an <em>if</em> statement, the advantage of this method is that you keep the query as a single method-call chain, improving the readability of the code.</p>
<h3>Sub-queries</h3>
<p>Parameter placeholders are always used for command parameters, except when you pass another SqlBuilder instance, case in which the supplied builder&#8217;s text is injected at the placeholder. This is how SqlBuilder support sub-queries:</p>
<pre style="background-color:#dadada;font-size:100%;">var query = SQL
   .SELECT("c.CategoryName, t0.TotalProducts")
   .FROM("Categories c")
   .JOIN("({0}) t0 ON c.CategoryID = t0.CategoryID", SQL
      .SELECT("CategoryID, COUNT(*) AS TotalProducts")
      .FROM("Products")
      .GROUP_BY("CategoryID"))
   .ORDER_BY("t0.TotalProducts DESC");

Console.WriteLine(query);</pre>
<p>The output:</p>
<pre style="background-color:#dadada;font-size:100%;">SELECT c.CategoryName, t0.TotalProducts
FROM Categories c
JOIN (
        SELECT CategoryID, COUNT(*) AS TotalProducts
        FROM Products
        GROUP BY CategoryID) t0 ON c.CategoryID = t0.CategoryID
ORDER BY t0.TotalProducts DESC</pre>
<p>If the sub-query contains any parameter values these are copied to the outer query. SqlBuilder doesn&#8217;t keep any reference to sub-queries, all instances are completely independent and composability is achieved by copying state from one instance to the other.</p>
<h3>Arrays</h3>
<p>Not many SQL dialects support array types, but a very common requirement is to use an array of values as the right expression of the IN operator:</p>
<pre style="background-color:#dadada;font-size:100%;">int[] ids = { 1, 2, 3 };

var query = SQL
   .SELECT("*")
   .FROM("Products")
   .WHERE("CategoryID IN ({0})", ids);

Console.WriteLine(query);</pre>
<p>The output:</p>
<pre style="background-color:#dadada;font-size:100%;">SELECT *
FROM Products
WHERE CategoryID IN ({0}, {1}, {2})</pre>
<h3>Extending an existing query</h3>
<p>If there&#8217;s a large portion of the query that is static, there&#8217;s no need to convert everything to method calls, just pass it to the constructor and extend it from there:</p>
<pre style="background-color:#dadada;font-size:100%;">var query = SQL.New(@"
    SELECT ProductID, ProductName
    FROM Products")
   .WHERE("CategoryID = {0}", 1);

Console.WriteLine(query);</pre>
<p>The output:</p>
<pre style="background-color:#dadada;font-size:100%;">             SELECT ProductID, ProductName
             FROM Products
WHERE CategoryID = {0}</pre>
<p>In this case I favored source code readability over SQL readability.</p>
<h3>Inserts, Updates, Deletes</h3>
<p>There&#8217;s really no limit to the kind of statements SqlBuilder can handle:</p>
<pre style="background-color:#dadada;font-size:100%;">var insert = SQL
   .INSERT_INTO("Products(ProductName, UnitPrice, CategoryID)")
   .VALUES("Chai", 15.56, 5);

var update = SQL
   .UPDATE("Products")
   .SET("Discontinued", true)
   .WHERE("ProductID = {0}", 1)
   .LIMIT(1);

var delete = SQL
   .DELETE_FROM("Products")
   .WHERE("ProductID = {0}", 1)
   .LIMIT(1);

Console.WriteLine(insert);
Console.WriteLine(update);
Console.WriteLine(delete);</pre>
<p>The output:</p>
<pre style="background-color:#dadada;font-size:100%;">INSERT INTO Products(ProductName, UnitPrice, CategoryID)
VALUES ({0}, {1}, {2})

UPDATE Products
SET Discontinued = {0}
WHERE ProductID = {1}
LIMIT {2}

DELETE FROM Products
WHERE ProductID = {0}
LIMIT {1}</pre>
<p>You can see here some methods that do not take the format string, like <code>SET</code>, <code>VALUES</code> and <code>LIMIT</code>. Since the format of these clauses is well known, all you need to pass in are parameters.</p>
<h3>Extensibility</h3>
<p>To understand how SqlBuilder can be extended let&#8217;s take a look at how some of the built-in clauses are implemented:</p>
<pre style="background-color:#dadada;font-size:100%;">public SqlBuilder SELECT(string format, params object[] args) {
   return AppendClause("SELECT", format, args);
}

public SqlBuilder FROM(string format, params object[] args) {
   return AppendClause("FROM", format, args);
}

public SqlBuilder JOIN(string format, params object[] args) {
   return AppendClause(new SqlClauseInfo("JOIN", null), format, args);
}

public SqlBuilder SET(string columnName, TValue value) {
   return AppendClause("SET", columnName + " = {0}", value);
}</pre>
<p>As you can see implementing a clause can be as easy as writing one line of code, it all depends on the parameters you define and how much you need to analyze them to produce a format string. Alternatively, you can access the underlying <code>StringBuilder</code> directly to append text, through the <code>Buffer</code> property.</p>
<p>Here&#8217;s how the <code>WHERE_If</code> extension method is implemented (<em>right now I don&#8217;t have a longer/more complex example, when I do I&#8217;ll post it here</em>):</p>
<pre style="background-color:#dadada;font-size:100%;">public static SqlBuilder WHERE_If(this SqlBuilder sqlBuilder, bool condition, string format, params object[] args) {
   return (condition) ? sqlBuilder.WHERE(format, args) : sqlBuilder;
}</pre>
<h3>Mapping to objects with LINQ to SQL</h3>
<p>As stated in the design goals, getting and mapping data is beyond the scope of SqlBuilder, so to get data we need a data access component. Since SqlBuilder was inspired by LINQ to SQL&#8217;s ExecuteQuery/ExecuteCommand methods, integrating with this ORM is very easy:</p>
<pre style="background-color:#dadada;font-size:100%;">public IEnumerable&lt;Product&gt; GetProducts(int? categoryId) {

   var query = SQL
      .SELECT("ProductID, ProductName, UnitPrice")
      .FROM("Products")
      .WHERE_If(categoryId.HasValue, "CategoryID = {0}", categoryId)
      .ORDER_BY("ProductName");

   // instantiate your DataContext
   DataContext context = null;

   return context.ExecuteQuery&lt;Product&gt;(query.ToString(), query.ParameterValues.ToArray());
}</pre>
<p>LINQ to SQL parses the query and maps columns to properties based on the column aliases used.</p>
<h3>Mapping to objects with DbExtensions</h3>
<p>SqlBuilder is part of the DbExtensions library, which includes a basic CRUD API:</p>
<pre style="background-color:#dadada;font-size:100%;">public IEnumerable&lt;Product&gt; GetProducts() {

   // Instantiate your DAO
   DataAccessObject dao = null;

   var query = new SqlBuilder { QueryMembers = dao.CreateQueryMembers() }
      .SELECT(typeof(Product), "p")
      .SELECT(typeof(Category), "c")
      .SELECT(typeof(Supplier), "s")
      .FROM("Products p")
      .LEFT_JOIN("Categories c ON p.CategoryID = c.CategoryID")
      .LEFT_JOIN("Suppliers s ON p.SupplierID = s.SupplierID")
      .WHERE("p.ProductID &lt; {0}", 7);

   return dao.Map&lt;Product&gt;(query).ToList();
}</pre>
<p>DbExtensions takes a different approach to mapping. First, it defines an extension method <code>SqlBuilder.SELECT(Type, String)</code> that takes the type of a mapped object, which appends the names of the columns based on the mapping, and adds the <code>System.Reflection.MemberInfo</code> instances for each mapped member to the <code>SqlBuilder.QueryMembers</code> collection. This way, the SqlBuilder instance not only contains the query to be executed, but also the members to which the result should map to. With this, DbExtensions is able to take a query and return mapped objects. It also detects that <code>Category</code> and <code>Supplier</code> types are related to <code>Product</code> with a Many-to-one association, and loads the <code>Product.Category</code> and <code>Product.Supplier</code> properties for each returned <code>Product</code>.</p>
<h3>Conclusions</h3>
<p>SqlBuilder helps your build dynamic SQL in an ADO.NET provider/RDBMS/ORM independent way. Generic query APIs like LINQ work great for simple queries, but it&#8217;s statically-typed nature tends to become a disadvantage for complex scenarios, and it&#8217;s very difficult to extend. Many ORM products have their own query APIs, but using them means marrying to a particular product and more APIs to learn. Complex queries require complete control of the executing SQL. SqlBuilder gives you that control, freeing you from dealing with low-level objects like <code>DbCommand</code> and <code>DbParameter</code>.</p>
<h3>More information</h3>
<p><a href="http://www.ohloh.net/p/dbex">http://www.ohloh.net/p/dbex</a></p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/maxtoroq.wordpress.com/85/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/maxtoroq.wordpress.com/85/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/maxtoroq.wordpress.com/85/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/maxtoroq.wordpress.com/85/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/maxtoroq.wordpress.com/85/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/maxtoroq.wordpress.com/85/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/maxtoroq.wordpress.com/85/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/maxtoroq.wordpress.com/85/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/maxtoroq.wordpress.com/85/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/maxtoroq.wordpress.com/85/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maxtoroq.wordpress.com&blog=905434&post=85&subd=maxtoroq&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://maxtoroq.wordpress.com/2009/02/18/sqlbuilder-20/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1056a38ecd323c658a8c9e93bb41b18d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">maxtoroq</media:title>
		</media:content>
	</item>
		<item>
		<title>Hello Berkeley DB XML on .NET</title>
		<link>http://maxtoroq.wordpress.com/2008/12/25/hello-berkeley-db-xml-on-net/</link>
		<comments>http://maxtoroq.wordpress.com/2008/12/25/hello-berkeley-db-xml-on-net/#comments</comments>
		<pubDate>Thu, 25 Dec 2008 06:39:06 +0000</pubDate>
		<dc:creator>maxtoroq</dc:creator>
				<category><![CDATA[xml]]></category>
		<category><![CDATA[bdb xml]]></category>
		<category><![CDATA[ikvm.net]]></category>
		<category><![CDATA[xquery]]></category>

		<guid isPermaLink="false">http://maxtoroq.wordpress.com/?p=69</guid>
		<description><![CDATA[UPDATE 2009-05-26: On ASP.NET you might get an &#8216;Unable to load ikvm-native&#8217; error message. There are several ways to fix this: a) Add the ikvm-native.dll location to the PATH; b) Copy ikvm-native.dll to %windir%\system32; c) Add a &#8216;ikvm:java.library.path&#8217; appSetting on web.config and set it&#8217;s value to the ikvm-native.dll location.
If you&#8217;re not familiar with Berkeley DB [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maxtoroq.wordpress.com&blog=905434&post=69&subd=maxtoroq&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p style="background-color:lightyellow;border:dotted 1px gray;padding:.5em;"><strong>UPDATE 2009-05-26:</strong> On ASP.NET you might get an &#8216;Unable to load ikvm-native&#8217; error message. There are several ways to fix this: a) Add the ikvm-native.dll location to the PATH; b) Copy ikvm-native.dll to %windir%\system32; c) Add a &#8216;ikvm:java.library.path&#8217; appSetting on web.config and set it&#8217;s value to the ikvm-native.dll location.</p>
<p>If you&#8217;re not familiar with <a href="http://www.oracle.com/database/berkeley-db/xml">Berkeley DB XML</a> (BDB XML), it is an open source <strong>embeddable </strong>XML database engine that provides support for XQuery access.</p>
<p>The official BDB XML distribution provides the library in the C++, Java, Perl, Python, PHP, and Tcl languages. Sadly, no .NET version.</p>
<p>I tried to look for a third-party .NET library and found this one from Parthenon Computing:<br />
<a href="http://www.parthcomp.com/dbxml_dotnet.html">http://www.parthcomp.com/dbxml_dotnet.html</a></p>
<p>The problem with this product is that it doesn&#8217;t seem up-to-date with .NET 2.0 and the most recent versions of BDB XML. Also it&#8217;s free only for non-commercial use.</p>
<p>Since I couldn&#8217;t find any other .NET libraries I started to think what I could do with the existing ones, and it occurred to me I could cross-compile the Java version using <a href="http://ikvm.net">IKVM.NET</a>. Because I use IKVM all the time with <a href="http://saxon.sf.net/">Saxon XSLT/XQuery</a> I trust and have a good opinion of this product.</p>
<p>Running the IKVM compiler is very simple. For this task you have to grab db.jar and dbxml.jar (available from the official BDB XML distribution) and execute this command:</p>
<pre style="background-color:#dadada;font-size:100%;">ikvmc -out:dbxml_net.dll db.jar dbxml.jar</pre>
<p>And that&#8217;s it! You have your .NET API, officially maintained and up-to-date with the latest BDB XML release. The API will have the Java look-and-feel, camelCase for members, no properties, etc. If you can live with that then there&#8217;s no problem. Please note that I haven&#8217;t tested much this library, but I suspect it shouldn&#8217;t have problems, I encourage you to try it and let me know your experience.</p>
<p>Here&#8217;s my hello-world program, it queries a container I had previously created using the dbxml command line shell:</p>
<pre style="background-color:#dadada;font-size:100%;">using System;
using com.sleepycat.db;
using com.sleepycat.dbxml;

namespace BerkeleyDB_XML1 {
   class Program {

      static void Main() {
         Console.WriteLine("Running {0}...", com.sleepycat.db.Environment.getVersionString());

         XmlManager mgr = new XmlManager();
         XmlContainer cont = mgr.openContainer(@"c:/temp/bdb-hello/hello.dbxml");

         int count = cont.getNumDocuments();

         Console.WriteLine("Number of available documents: {0}", count);

         XmlQueryContext qctx = mgr.createQueryContext(XmlQueryContext.Eager);

         XmlResults results = mgr.query(
@"for $h in collection('dbxml:c:/temp/bdb-hello/hello.dbxml')/hello
return $h", qctx);

         while (results.hasNext())
            Console.WriteLine(results.next().asString());

         cont.close();
         mgr.close();
      }
   }
}</pre>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/maxtoroq.wordpress.com/69/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/maxtoroq.wordpress.com/69/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/maxtoroq.wordpress.com/69/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/maxtoroq.wordpress.com/69/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/maxtoroq.wordpress.com/69/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/maxtoroq.wordpress.com/69/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/maxtoroq.wordpress.com/69/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/maxtoroq.wordpress.com/69/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/maxtoroq.wordpress.com/69/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/maxtoroq.wordpress.com/69/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maxtoroq.wordpress.com&blog=905434&post=69&subd=maxtoroq&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://maxtoroq.wordpress.com/2008/12/25/hello-berkeley-db-xml-on-net/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1056a38ecd323c658a8c9e93bb41b18d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">maxtoroq</media:title>
		</media:content>
	</item>
		<item>
		<title>Linq to MySQL, based on Matt Warren&#8217;s provider</title>
		<link>http://maxtoroq.wordpress.com/2008/10/19/linq-to-mysql-based-on-matt-warrens-provider/</link>
		<comments>http://maxtoroq.wordpress.com/2008/10/19/linq-to-mysql-based-on-matt-warrens-provider/#comments</comments>
		<pubDate>Sun, 19 Oct 2008 22:16:39 +0000</pubDate>
		<dc:creator>maxtoroq</dc:creator>
				<category><![CDATA[ado.net]]></category>
		<category><![CDATA[linq]]></category>
		<category><![CDATA[mysql]]></category>

		<guid isPermaLink="false">http://maxtoroq.wordpress.com/?p=55</guid>
		<description><![CDATA[On each release Matt Warren&#8217;s IQueryable provider is getting more and more interesting. On this post I&#8217;ll show you how easy is to plug-in your custom QueryFormatter to start querying MySQL databases.
Step 1: Download Matt Warren&#8217;s provider
The code on this post is based on release 11. Although I cannot ensure it will work with newer [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maxtoroq.wordpress.com&blog=905434&post=55&subd=maxtoroq&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>On each release Matt Warren&#8217;s IQueryable provider is getting more and more interesting. On this post I&#8217;ll show you how easy is to plug-in your custom QueryFormatter to start querying MySQL databases.</p>
<h3>Step 1: Download Matt Warren&#8217;s provider</h3>
<p>The code on this post is based on <a href="http://blogs.msdn.com/mattwar/archive/2008/07/14/linq-building-an-iqueryable-provider-part-xi.aspx" target="_blank">release 11</a>. Although I cannot ensure it will work with newer releases it is always recommended that you download the latest.</p>
<h3>Step 2: Create a custom QueryFormatter class</h3>
<p>The following code is a custom QueryFormatter for MySQL.</p>
<pre style="overflow:scroll;color:black;font-family:'Lucida Console',Consolas,'Courier New',Courier,Monospace;background-color:#ffffff;line-height:normal;font-size:9pt;width:100%;"><span style="color:#0000ff;">using</span> System;
<span style="color:#0000ff;">using</span> System.Collections.Generic;
<span style="color:#0000ff;">using</span> System.Linq;
<span style="color:#0000ff;">using</span> System.Linq.Expressions;
<span style="color:#0000ff;">using</span> System.Text;

<span style="color:#0000ff;">namespace</span> Sample {

   <span style="color:#0000ff;">internal</span> <span style="color:#0000ff;">class</span> <span style="color:#2b91af;">MySqlQueryFormatter</span> : <span style="color:#2b91af;">QueryFormatter</span> {

      <span style="color:#0000ff;">protected</span> <span style="color:#0000ff;">override</span> <span style="color:#2b91af;">Expression</span> VisitNamedValue(<span style="color:#2b91af;">NamedValueExpression</span> <span style="color:#0000ff;">value</span>) {
         sb.Append(<span style="color:#800000;">"?"</span> + <span style="color:#0000ff;">value</span>.Name);
         <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">value</span>;
      }

      <span style="color:#0000ff;">protected</span> <span style="color:#0000ff;">override</span> <span style="color:#2b91af;">Expression</span> VisitSelect(<span style="color:#2b91af;">SelectExpression</span> <span style="color:#0000ff;">select</span>) {
         sb.Append(<span style="color:#800000;">"SELECT "</span>);
         <span style="color:#0000ff;">if</span> (<span style="color:#0000ff;">select</span>.IsDistinct) {
            sb.Append(<span style="color:#800000;">"DISTINCT "</span>);
         }

         <span style="color:#0000ff;">if</span> (<span style="color:#0000ff;">select</span>.Columns.Count &gt; 0) {
            <span style="color:#0000ff;">for</span> (<span style="color:#0000ff;">int</span> i = 0, n = <span style="color:#0000ff;">select</span>.Columns.Count; i &lt; n; i++) {
               <span style="color:#2b91af;">ColumnDeclaration</span> column = <span style="color:#0000ff;">select</span>.Columns[i];
               <span style="color:#0000ff;">if</span> (i &gt; 0) {
                  sb.Append(<span style="color:#800000;">", "</span>);
               }
               <span style="color:#2b91af;">ColumnExpression</span> c = <span style="color:#0000ff;">this</span>.VisitValue(column.<span style="color:#2b91af;">Expression</span>) <span style="color:#0000ff;">as</span> <span style="color:#2b91af;">ColumnExpression</span>;
               <span style="color:#0000ff;">if</span> (!<span style="color:#0000ff;">string</span>.IsNullOrEmpty(column.Name) &amp;&amp; (c == <span style="color:#0000ff;">null</span> || c.Name != column.Name)) {
                  sb.Append(<span style="color:#800000;">" AS "</span>);
                  sb.Append(column.Name);
               }
            }
         } <span style="color:#0000ff;">else</span> {
            sb.Append(<span style="color:#800000;">"NULL "</span>);
            <span style="color:#0000ff;">if</span> (<span style="color:#0000ff;">this</span>.isNested) {
               sb.Append(<span style="color:#800000;">"AS tmp "</span>);
            }
         }
         <span style="color:#0000ff;">if</span> (<span style="color:#0000ff;">select</span>.From != <span style="color:#0000ff;">null</span>) {
            <span style="color:#0000ff;">this</span>.AppendNewLine(<span style="color:#2b91af;">Indentation</span>.Same);
            sb.Append(<span style="color:#800000;">"FROM "</span>);
            <span style="color:#0000ff;">this</span>.VisitSource(<span style="color:#0000ff;">select</span>.From);
         }
         <span style="color:#0000ff;">if</span> (<span style="color:#0000ff;">select</span>.Where != <span style="color:#0000ff;">null</span>) {
            <span style="color:#0000ff;">this</span>.AppendNewLine(<span style="color:#2b91af;">Indentation</span>.Same);
            sb.Append(<span style="color:#800000;">"WHERE "</span>);
            <span style="color:#0000ff;">this</span>.VisitPredicate(<span style="color:#0000ff;">select</span>.Where);
         }
         <span style="color:#0000ff;">if</span> (<span style="color:#0000ff;">select</span>.GroupBy != <span style="color:#0000ff;">null</span> &amp;&amp; <span style="color:#0000ff;">select</span>.GroupBy.Count &gt; 0) {
            <span style="color:#0000ff;">this</span>.AppendNewLine(<span style="color:#2b91af;">Indentation</span>.Same);
            sb.Append(<span style="color:#800000;">"GROUP BY "</span>);
            <span style="color:#0000ff;">for</span> (<span style="color:#0000ff;">int</span> i = 0, n = <span style="color:#0000ff;">select</span>.GroupBy.Count; i &lt; n; i++) {
               <span style="color:#0000ff;">if</span> (i &gt; 0) {
                  sb.Append(<span style="color:#800000;">", "</span>);
               }
               <span style="color:#0000ff;">this</span>.VisitValue(<span style="color:#0000ff;">select</span>.GroupBy[i]);
            }
         }
         <span style="color:#0000ff;">if</span> (<span style="color:#0000ff;">select</span>.OrderBy != <span style="color:#0000ff;">null</span> &amp;&amp; <span style="color:#0000ff;">select</span>.OrderBy.Count &gt; 0) {
            <span style="color:#0000ff;">this</span>.AppendNewLine(<span style="color:#2b91af;">Indentation</span>.Same);
            sb.Append(<span style="color:#800000;">"ORDER BY "</span>);
            <span style="color:#0000ff;">for</span> (<span style="color:#0000ff;">int</span> i = 0, n = <span style="color:#0000ff;">select</span>.OrderBy.Count; i &lt; n; i++) {
               <span style="color:#2b91af;">OrderExpression</span> exp = <span style="color:#0000ff;">select</span>.OrderBy[i];
               <span style="color:#0000ff;">if</span> (i &gt; 0) {
                  sb.Append(<span style="color:#800000;">", "</span>);
               }
               <span style="color:#0000ff;">this</span>.VisitValue(exp.<span style="color:#2b91af;">Expression</span>);
               <span style="color:#0000ff;">if</span> (exp.OrderType != OrderType.Ascending) {
                  sb.Append(<span style="color:#800000;">" DESC"</span>);
               }
            }
         }
         <span style="color:#0000ff;">if</span> (<span style="color:#0000ff;">select</span>.Take != <span style="color:#0000ff;">null</span>) {
            <span style="color:#0000ff;">this</span>.AppendNewLine(<span style="color:#2b91af;">Indentation</span>.Same);
            sb.Append(<span style="color:#800000;">"LIMIT "</span>);
            <span style="color:#0000ff;">this</span>.Visit(<span style="color:#0000ff;">select</span>.Take);
            sb.Append(<span style="color:#800000;">" "</span>);
         }
         <span style="color:#0000ff;">if</span> (<span style="color:#0000ff;">select</span>.Skip != <span style="color:#0000ff;">null</span>) {
            sb.Append(<span style="color:#800000;">"OFFSET "</span>);
            <span style="color:#0000ff;">this</span>.Visit(<span style="color:#0000ff;">select</span>.Skip);
            sb.Append(<span style="color:#800000;">" "</span>);
         }
         <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">select</span>;
      }
   }
}</pre>
<p>Try to build and you&#8217;ll notice that MySqlQueryFormatter is trying to access a lot of QueryFormatter members that are <em>private</em>, so you&#8217;ll need to make those <em>protected</em>.</p>
<p>Since all interaction with QueryFormatter is done through a single static method called Format, which creates an instance of the same type, we need to change the type of the created instance to MySqlQueryFormatter.</p>
<pre style="overflow:scroll;color:black;font-family:'Lucida Console',Consolas,'Courier New',Courier,Monospace;background-color:#ffffff;line-height:normal;font-size:9pt;width:100%;"><span style="color:#008000;">// line 22, QueryFormatter.cs</span>
<span style="color:#2b91af;">QueryFormatter</span> formatter = <span style="color:#0000ff;">new</span> <span style="color:#2b91af;">MySqlQueryFormatter</span>();</pre>
<p>This is the fast way to get things working, a better approach would be to have a QueryFormatter property on DbQueryProvider.</p>
<h3>Step 3: Comment the following two lines in DbQueryProvider.Translate method</h3>
<pre style="overflow:scroll;color:black;font-family:'Lucida Console',Consolas,'Courier New',Courier,Monospace;background-color:#ffffff;line-height:normal;font-size:9pt;width:100%;"><span style="color:#008000;">// line 123-124, DbQueryProvider.cs</span>
<span style="color:#008000;">//expression = SkipRewriter.Rewrite(expression);</span>
<span style="color:#008000;">//expression = OrderByRewriter.Rewrite(expression);</span></pre>
<p>Since these calls are used to support SQL Server&#8217;s complicated syntax for paging, for MySQL we don&#8217;t need them.</p>
<p>And that&#8217;s it!</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/maxtoroq.wordpress.com/55/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/maxtoroq.wordpress.com/55/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/maxtoroq.wordpress.com/55/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/maxtoroq.wordpress.com/55/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/maxtoroq.wordpress.com/55/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/maxtoroq.wordpress.com/55/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/maxtoroq.wordpress.com/55/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/maxtoroq.wordpress.com/55/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/maxtoroq.wordpress.com/55/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/maxtoroq.wordpress.com/55/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maxtoroq.wordpress.com&blog=905434&post=55&subd=maxtoroq&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://maxtoroq.wordpress.com/2008/10/19/linq-to-mysql-based-on-matt-warrens-provider/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1056a38ecd323c658a8c9e93bb41b18d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">maxtoroq</media:title>
		</media:content>
	</item>
		<item>
		<title>CSS design patterns: Helper classes</title>
		<link>http://maxtoroq.wordpress.com/2008/08/17/css-design-patterns-helper-classes/</link>
		<comments>http://maxtoroq.wordpress.com/2008/08/17/css-design-patterns-helper-classes/#comments</comments>
		<pubDate>Sun, 17 Aug 2008 07:38:21 +0000</pubDate>
		<dc:creator>maxtoroq</dc:creator>
				<category><![CDATA[web-dev]]></category>
		<category><![CDATA[patterns]]></category>

		<guid isPermaLink="false">http://maxtoroq.wordpress.com/?p=39</guid>
		<description><![CDATA[CSS can be one of the most frustrating technologies in web development. Things like browser inconsistencies/hacks, quirks&#124;standards modes, conditional comments, etc. are things I wish I didn&#8217;t have to worry about. To make it even worse, CSS lacks of one of the most fundamental features in any language, variables. Is it possible to write reusable [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maxtoroq.wordpress.com&blog=905434&post=39&subd=maxtoroq&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>CSS can be one of the most frustrating technologies in web development. Things like browser inconsistencies/hacks, quirks|standards modes, conditional comments, etc. are things I wish I didn&#8217;t have to worry about. To make it even worse, CSS lacks of one of the most fundamental features in any language, variables. Is it possible to write reusable CSS?</p>
<p><strong>Helper classes</strong> are reusable rules that use class selectors (sometimes combined with type|ID selectors). Helper classes are designed to let you:</p>
<ol>
<li><strong>Apply style to an element without having to create a special rule for that element</strong>: This means you can write less CSS (I like that). You can apply multiple helper classes to an element, as opposed to creating a special class and declare multiple properties in it.</li>
<li><strong>Abstract away browser inconsistencies</strong>: 1 helper class can declare multiple properties that have the same effect, but target different browsers.</li>
<li><strong>Make documents more <em>style readable</em></strong>: In server-side programming we are concerned to write readable programs, so by reading the code we can easily understand the program&#8217;s behaviour. When using helper classes in a document, by reading the code you should easily visualise it&#8217;s appearance. <strong>The class name should describe the effect of the rule</strong>, in other words, by knowing the class name we should have a solid idea of what the element will look like when that rule is applied.</li>
</ol>
<p><strong>Example 1: Combining rules</strong><br />
Given the following rules:</p>
<pre style="line-height:normal;background-color:#ffffff;width:100%;font-family:'Lucida Console',Consolas,'Courier New',Courier,Monospace;color:black;font-size:9pt;overflow:scroll;"><span style="color:#800000;">.underline</span> { <span style="color:#ff0000;">text-decoration</span>: <span style="color:#0000ff;">underline</span>; }
<span style="color:#800000;">.highlight</span> { <span style="color:#ff0000;">background-color</span>: <span style="color:#0000ff;">#ffc</span>; }</pre>
<p>&#8230;here is an example of how you can combine multiple rules by applying multiple classes to an element. As you can see it very easy to visualise how the element will render by reading the classes names.</p>
<pre style="line-height:normal;background-color:#ffffff;width:100%;font-family:'Lucida Console',Consolas,'Courier New',Courier,Monospace;color:black;font-size:9pt;overflow:scroll;"><span style="color:#0000ff;">&lt;</span><span style="color:#800000;">span</span> <span style="color:#ff0000;">class</span><span style="color:#0000ff;">="</span><span style="color:#0000ff;">underline highlight</span><span style="color:#0000ff;">"</span><span style="color:#0000ff;">&gt;</span>very important text<span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">a</span><span style="color:#0000ff;">&gt;</span></pre>
<p><strong>Example 2: </strong><strong>Abstracting away browser inconsistencies</strong></p>
<pre style="line-height:normal;background-color:#ffffff;width:100%;font-family:'Lucida Console',Consolas,'Courier New',Courier,Monospace;color:black;font-size:9pt;overflow:scroll;"><span style="color:darkred;">.block</span> { <span style="color:red;">display</span>: <span style="color:blue;">block</span>; }
<span style="color:darkred;">.inline-block</span> { <span style="color:red;">display</span>: <span style="color:blue;">-moz-inline-box</span>; <span style="color:red;">display</span>: <span style="color:blue;">inline-block</span>; }</pre>
<p>The .block class is useful when you need an inline element to behave like a block element, can be applied to <em>span</em>, <em>a</em>, <em>label</em>, etc. The .inline-block class shows how we can use helper classes to handle different browsers.</p>
<p><strong>Example 3: Powerful selectors</strong></p>
<pre style="line-height:normal;background-color:#ffffff;width:100%;font-family:'Lucida Console',Consolas,'Courier New',Courier,Monospace;color:black;font-size:9pt;overflow:scroll;"><span style="color:darkred;">.float_r</span> { <span style="color:red;">float</span>: <span style="color:blue;">right</span>; }
<span style="color:darkred;">p img.float_r</span> { <span style="color:red;">margin-left</span>: <span style="color:blue;">0.5em</span>; }</pre>
<p>I like the second rule very much, because it shows how helper classes can help us write more powerful CSS. This rule is not a helper class, but takes advantage of helper classes, it says: <em>for all images that are inside paragraphs and that are floating to the right, apply a 0.5em margin on the left, so there is a space between the image and the paragraph&#8217;s text</em>.</p>
<p>By using helper classes we are basically tagging the elements with style information that, as opposed with inline styling, it&#8217;s not actually implemented. The last example looks very similar to an attribute selector, like input[type="text"], which is almost the same as an XPath query with a predicate. In essence all selectors are queries against the document&#8217;s structure and/or user-defined class names. If you use class names that describe a particular style then you can query against the document&#8217;s style.</p>
<p><strong>Other people thinking alike:</strong></p>
<p><a href="http://www.mattvarone.com/2008/07/css-reusable-classes/">http://www.mattvarone.com/2008/07/css-reusable-classes/</a><br />
<a href="http://www.realmacsoftware.com/webshed/index_files/multiple-css-classes.php">http://www.realmacsoftware.com/webshed/index_files/multiple-css-classes.php</a><br />
<a href="http://www.aprilholle.com/technology-reviews/css-continued-part-2reduce-reuse-recycle/">http://www.aprilholle.com/technology-reviews/css-continued-part-2reduce-reuse-recycle/</a></p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/maxtoroq.wordpress.com/39/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/maxtoroq.wordpress.com/39/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/maxtoroq.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/maxtoroq.wordpress.com/39/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/maxtoroq.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/maxtoroq.wordpress.com/39/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/maxtoroq.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/maxtoroq.wordpress.com/39/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/maxtoroq.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/maxtoroq.wordpress.com/39/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/maxtoroq.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/maxtoroq.wordpress.com/39/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maxtoroq.wordpress.com&blog=905434&post=39&subd=maxtoroq&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://maxtoroq.wordpress.com/2008/08/17/css-design-patterns-helper-classes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1056a38ecd323c658a8c9e93bb41b18d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">maxtoroq</media:title>
		</media:content>
	</item>
		<item>
		<title>Writing SQL using lambda expressions (not Linq)</title>
		<link>http://maxtoroq.wordpress.com/2008/01/03/writing-sql-using-lambda-expressions-not-linq/</link>
		<comments>http://maxtoroq.wordpress.com/2008/01/03/writing-sql-using-lambda-expressions-not-linq/#comments</comments>
		<pubDate>Fri, 04 Jan 2008 01:27:27 +0000</pubDate>
		<dc:creator>maxtoroq</dc:creator>
				<category><![CDATA[ado.net]]></category>
		<category><![CDATA[dbextensions]]></category>
		<category><![CDATA[dynamic sql]]></category>
		<category><![CDATA[lambda expressions]]></category>

		<guid isPermaLink="false">http://maxtoroq.wordpress.com/2008/01/03/writing-sql-using-lambda-expressions-not-linq/</guid>
		<description><![CDATA[Some of the code in this post may be outdated, I suggest visiting the project site at http://dbex.googlecode.com/
Persistence ignorance and type safety, this is what Linq gives us. I can&#8217;t get enough of the latter, but in most cases a generic query API is not what I need, specially when I&#8217;m not querying in-memory objects.
You [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maxtoroq.wordpress.com&blog=905434&post=26&subd=maxtoroq&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p style="border:dotted 1px gray;background-color:lightyellow;padding:.5em;">Some of the code in this post may be outdated, I suggest visiting the project site at <a href="http://dbex.googlecode.com/" target="_blank">http://dbex.googlecode.com/</a></p>
<p>Persistence ignorance and type safety, this is what Linq gives us. I can&#8217;t get enough of the latter, but in most cases a generic query API is not what I need, specially when I&#8217;m not querying in-memory objects.</p>
<p>You know what I&#8217;m talking about, you work with SQL, XPath, etc. You know how to write queries and get the results you want. For instance, there are some things in SQL that I don&#8217;t know how to translate to Linq, <strong>and if they are going to look the same when translated back to SQL</strong>, like the <em>column IN (subquery) </em>syntax. Although you can instead write a join and get the same results I like this better because is more readable. Another concern are functions, what if you want to use a function that has no CLR mapping?</p>
<p>To address this problems and keep the type safety I wrote a class called SqlBuilder. Think of it as a StringBuider for SQL. Let&#8217;s take a look at an example:</p>
<pre style="overflow:scroll;font-size:9pt;width:100%;color:black;line-height:normal;font-family:'Lucida Console',Consolas,'Courier New',Courier,Monospace;background-color:#ffffff;"><span style="color:#0000ff;">var</span> query = <span style="color:#0000ff;">new</span> <span style="color:#2b91af;">SqlBuilder</span>()
   .Select&lt;<span style="color:#2b91af;">Product</span>&gt;(p =&gt; <span style="color:#0000ff;">new</span> { Description = p.ProductName, ID = p.ProductID })
   .From&lt;<span style="color:#2b91af;">Product</span>&gt;().Where&lt;<span style="color:#2b91af;">Product</span>&gt;(p =&gt; p.CategoryID == 1);         

<span style="color:#2b91af;">Debug</span>.WriteLine(query);         

<span style="color:#008000;">// -- the output:</span>
<span style="color:#008000;">// SELECT t0.ProductName AS Description, t0.ProductID AS ID</span>
<span style="color:#008000;">// FROM Product AS t0</span>
<span style="color:#008000;">// WHERE (t0.CategoryID = 1)</span></pre>
<p>This looks nice, but could be better. First of all, the name of the table we want to query is &#8216;Products&#8217; not &#8216;Product&#8217;. The SqlBuilder has no way of knowing that, unless we provide a MetaModel instance, which lives in the System.Data.Linq.Mapping namespace. This is the mapping API that Linq to Sql uses. Secondly, It would be nice if we could have the identifiers quoted. For that all we need is to provide a DbProviderFactory instance. Let&#8217;s change the constructor and run the example again:</p>
<pre style="overflow:scroll;font-size:9pt;width:100%;color:black;line-height:normal;font-family:'Lucida Console',Consolas,'Courier New',Courier,Monospace;background-color:#ffffff;"><span style="color:#0000ff;">var</span> query2 = <span style="color:#0000ff;">new</span> <span style="color:#2b91af;">SqlBuilder</span>(<span style="color:#2b91af;">SqlClientFactory</span>.Instance, <span style="color:#0000ff;">new</span> <span style="color:#2b91af;">AttributeMappingSource</span>().GetModel(<span style="color:#0000ff;">typeof</span>(<span style="color:#2b91af;">Product</span>)))
   .Select&lt;<span style="color:#2b91af;">Product</span>&gt;(p =&gt; <span style="color:#0000ff;">new</span> { Description = p.ProductName, ID = p.ProductID })
   .From&lt;<span style="color:#2b91af;">Product</span>&gt;().Where&lt;<span style="color:#2b91af;">Product</span>&gt;(p =&gt; p.CategoryID == 1);         

<span style="color:#2b91af;">Debug</span>.WriteLine(query2);         

<span style="color:#008000;">// -- the output:</span>
<span style="color:#008000;">// SELECT [t0].[ProductName] AS [Description], [t0].[ProductID] AS [ID]</span>
<span style="color:#008000;">// FROM [Products] AS [t0]</span>
<span style="color:#008000;">// WHERE ([t0].[CategoryID] = 1)</span></pre>
<p>Now it looks perfect. We get what we write, and that&#8217;s what we want. Let&#8217;s take a look at a more complex example, this is Northwind&#8217;s &#8216;Product Sales for 1997&#8242; view:</p>
<pre style="overflow:scroll;font-size:9pt;width:100%;color:black;line-height:normal;font-family:'Lucida Console',Consolas,'Courier New',Courier,Monospace;background-color:#ffffff;"><span style="color:#0000ff;">var</span> query3 = <span style="color:#0000ff;">new</span> <span style="color:#2b91af;">SqlBuilder</span>(<span style="color:#2b91af;">MySqlClientFactory</span>.Instance, <span style="color:#0000ff;">new</span> <span style="color:#2b91af;">AttributeMappingSource</span>().GetModel(<span style="color:#0000ff;">typeof</span>(<span style="color:#2b91af;">Product</span>)))
   .Select&lt;<span style="color:#2b91af;">Product</span>&gt;(p =&gt; <span style="color:#0000ff;">new</span> <span style="color:#0000ff;">object</span>[] { p.Category.CategoryName, p.ProductName })
   .Select&lt;<span style="color:#2b91af;">OrderDetail</span>&gt;(od =&gt; <span style="color:#0000ff;">new</span> { ProductSales = <span style="color:#2b91af;">Sql</span>.Sum(<span style="color:#2b91af;">Sql</span>.Round((od.UnitPrice * od.Quantity * <span style="color:#2b91af;">Convert</span>.ToDecimal(((1 - od.Discount) / 100))) * 100, 2)) })
   .From&lt;<span style="color:#2b91af;">Product</span>&gt;().Join&lt;<span style="color:#2b91af;">Product</span>, Category&gt;(<span style="color:#2b91af;">JoinType</span>.InnerJoin, (p, c) =&gt; p.CategoryID == c.CategoryID)
   .Join&lt;<span style="color:#2b91af;">Product</span>, <span style="color:#2b91af;">OrderDetail</span>&gt;(<span style="color:#2b91af;">JoinType</span>.InnerJoin, (p, od) =&gt; p.ProductID == od.ProductID)
   .Join&lt;<span style="color:#2b91af;">OrderDetail</span>, <span style="color:#2b91af;">Order</span>&gt;(<span style="color:#2b91af;">JoinType</span>.InnerJoin, (od, o) =&gt; od.OrderID == o.OrderID)
   .Where&lt;<span style="color:#2b91af;">Order</span>&gt;(o =&gt; <span style="color:#2b91af;">Sql</span>.Between(o.ShippedDate, <span style="color:#2b91af;">DateTime</span>.Parse(<span style="color:#800000;">"1997-01-01"</span>), <span style="color:#2b91af;">DateTime</span>.Parse(<span style="color:#800000;">"1997-12-31"</span>)))
   .GroupBy&lt;Category&gt;(c =&gt; c.CategoryName)
   .GroupBy&lt;<span style="color:#2b91af;">Product</span>&gt;(p =&gt; p.ProductName);         

<span style="color:#2b91af;">Debug</span>.WriteLine(query3);         

<span style="color:#008000;">// -- the output:</span>
<span style="color:#008000;">// SELECT `t0`.`CategoryName`, `t1`.`ProductName`, Sum(Round((((`t2`.`UnitPrice` * `t2`.`Quantity`) * ((1 - `t2`.`Discount`) / 100)) * 100), 2)) AS `ProductSales`</span>
<span style="color:#008000;">// FROM `Products` AS `t1`</span>
<span style="color:#008000;">// INNER JOIN `Categories` AS `t0` ON (`t1`.`CategoryID` = `t0`.`CategoryID`)</span>
<span style="color:#008000;">// INNER JOIN `Order Details` AS `t2` ON (`t1`.`ProductID` = `t2`.`ProductID`)</span>
<span style="color:#008000;">// INNER JOIN `Orders` AS `t3` ON (`t2`.`OrderID` = `t3`.`OrderID`)</span>
<span style="color:#008000;">// WHERE `t3`.`ShippedDate` BETWEEN {0} AND {1}</span>
<span style="color:#008000;">// GROUP BY `t0`.`CategoryName`, `t1`.`ProductName`</span></pre>
<p>Now I&#8217;m using the MySqlClientFactory just to show off it should work with any provider. Notice I&#8217;m using <strong>SQL functions</strong>, like Sum, Round and Between. Also notice I&#8217;m calling Select and GroupBy twice, but the second call appends &#8220;, &#8221; instead of the clause name, that&#8217;s something you can configure if you write your own methods. Also you can see that there are two placeholders for the DateTime values. The values are cached and the parameter names are generated when you call ToCommand() and inserted in those placeholders.</p>
<p>You can extend the SqlBuilder class using extension methods to add more clauses and statements, and static methods that represent server functions. This is a static class called MySql that encapsulates some functionality available in MySql Server.</p>
<pre style="overflow:scroll;font-size:9pt;width:100%;color:black;line-height:normal;font-family:'Lucida Console',Consolas,'Courier New',Courier,Monospace;background-color:#ffffff;"><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">static</span> <span style="color:#0000ff;">class</span> <span style="color:#2b91af;">MySql</span> { 

   [<span style="color:#2b91af;">SqlFunction</span>(Template = <span style="color:#800000;">"MATCH ({0}) AGAINST ({1})"</span>)]
   <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">static</span> <span style="color:#0000ff;">bool</span> Match(<span style="color:#0000ff;">object</span>[] members, <span style="color:#0000ff;">string</span> searchExpression) {
      <span style="color:#0000ff;">throw</span> <span style="color:#0000ff;">new</span> <span style="color:#2b91af;">InvalidOperationException</span>();
   } 

   [<span style="color:#2b91af;">SqlFunction</span>(Template = <span style="color:#800000;">"MATCH ({0}) AGAINST ({1} IN BOOLEAN MODE)"</span>)]
   <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">static</span> <span style="color:#0000ff;">bool</span> MatchBoolean(<span style="color:#0000ff;">object</span>[] members, <span style="color:#0000ff;">string</span> searchExpression) {
      <span style="color:#0000ff;">throw</span> <span style="color:#0000ff;">new</span> <span style="color:#2b91af;">InvalidOperationException</span>();
   } 

   <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">static</span> <span style="color:#2b91af;">SqlBuilder</span> Limit(<span style="color:#0000ff;">this</span> <span style="color:#2b91af;">SqlBuilder</span> builder, <span style="color:#0000ff;">int</span> maxRecords) {
      <span style="color:#0000ff;">return</span> Limit(builder, maxRecords, 0);
   } 

   [<span style="color:#2b91af;">SqlClause</span>(Name = <span style="color:#800000;">"LIMIT"</span>, IncludeInCountCommand = <span style="color:#0000ff;">false</span>)]
   <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">static</span> <span style="color:#2b91af;">SqlBuilder</span> Limit(<span style="color:#0000ff;">this</span> <span style="color:#2b91af;">SqlBuilder</span> builder, <span style="color:#0000ff;">int</span> maxRecords, <span style="color:#0000ff;">int</span> startIndex) { 

      <span style="color:#2b91af;">MethodBase</span> method = <span style="color:#2b91af;">MethodBase</span>.GetCurrentMethod();
      builder.OnClauseBuilding(<span style="color:#0000ff;">new</span> <span style="color:#2b91af;">ClauseBuildingEventArgs</span>(method)); 

      <span style="color:#2b91af;">StringBuilder</span> sb = <span style="color:#0000ff;">new</span> <span style="color:#2b91af;">StringBuilder</span>();
      sb.Append(maxRecords); 

      <span style="color:#0000ff;">if</span> (startIndex &gt; 0) {
         sb.Append(<span style="color:#800000;">" OFFSET "</span>);
         sb.Append(startIndex);
      } 

      builder.OnClauseBuilt(<span style="color:#0000ff;">new</span> <span style="color:#2b91af;">ClauseBuiltEventArgs</span>(method, sb.ToString())); 

      <span style="color:#0000ff;">return</span> builder;
   }
}</pre>
<p>You can see there are 2 functions, called Match and MatchBoolean, denoted by the SqlFunction attribute (mandatory). The SqlFunction.Template property is optional and useful for those functions that don&#8217;t look like functions at all. The Limit clause uses the SqlClause attribute which is optional. SqlBuilder also builds a second command for retriving the total number of records the main command is supposed to return. This is specially useful when doing paging. The SqlClause.IncludeInCountCommand indicates if the clause should be appended to the count command, which is not the case for Limit and OrderBy.</p>
<p>I hope you&#8217;ll find this useful enough to give it a try, specially for those who don&#8217;t want to give up the power of writing SQL.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/maxtoroq.wordpress.com/26/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/maxtoroq.wordpress.com/26/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/maxtoroq.wordpress.com/26/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/maxtoroq.wordpress.com/26/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/maxtoroq.wordpress.com/26/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/maxtoroq.wordpress.com/26/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/maxtoroq.wordpress.com/26/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/maxtoroq.wordpress.com/26/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/maxtoroq.wordpress.com/26/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/maxtoroq.wordpress.com/26/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/maxtoroq.wordpress.com/26/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/maxtoroq.wordpress.com/26/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maxtoroq.wordpress.com&blog=905434&post=26&subd=maxtoroq&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://maxtoroq.wordpress.com/2008/01/03/writing-sql-using-lambda-expressions-not-linq/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1056a38ecd323c658a8c9e93bb41b18d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">maxtoroq</media:title>
		</media:content>
	</item>
		<item>
		<title>Expando properties and the DomElement.getAttribute method in Firefox</title>
		<link>http://maxtoroq.wordpress.com/2007/11/10/expando-properties-and-the-domelementgetattribute-method-in-firefox/</link>
		<comments>http://maxtoroq.wordpress.com/2007/11/10/expando-properties-and-the-domelementgetattribute-method-in-firefox/#comments</comments>
		<pubDate>Sat, 10 Nov 2007 04:52:50 +0000</pubDate>
		<dc:creator>maxtoroq</dc:creator>
				<category><![CDATA[asp.net]]></category>
		<category><![CDATA[web-dev]]></category>
		<category><![CDATA[dom]]></category>
		<category><![CDATA[firefox]]></category>

		<guid isPermaLink="false">http://maxtoroq.wordpress.com/2007/11/10/expando-properties-and-the-domelementgetattribute-method-in-firefox/</guid>
		<description><![CDATA[When working in a custom validator control with client-side script I had issues with the javascript code in Firefox. Here is what I learnt.
Asp.net 2.0 uses expando properties to attach additional information to the validators, properties like &#8216;controltovalidate&#8217;, &#8216;errormessage&#8217;, &#8216;evaluationfunction&#8217;, etc. This is done programatically at the client, instead of just rendering invalid HTML attributes. Expando properties in [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maxtoroq.wordpress.com&blog=905434&post=25&subd=maxtoroq&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>When working in a custom validator control with client-side script I had issues with the javascript code in Firefox. Here is what I learnt.</p>
<p>Asp.net 2.0 uses <strong>expando properties</strong> to attach additional information to the validators, properties like &#8216;controltovalidate&#8217;, &#8216;errormessage&#8217;, &#8216;evaluationfunction&#8217;, etc. This is done programatically at the client, instead of just rendering invalid HTML attributes. Expando properties in javascript are perfectly legal. Here is an example of the generated javascript for 2 validators:</p>
<pre style="line-height:normal;background-color:#ffffff;width:100%;font-family:'Lucida Console', Consolas, 'Courier New', Courier, Monospace;color:black;font-size:9pt;overflow:scroll;">
<span style="color:#0000ff;">&lt;</span><span style="color:#800000;">script</span> <span style="color:#ff0000;">type</span><span style="color:#0000ff;">="text/javascript"</span><span style="color:#0000ff;">&gt;</span>
//<span style="color:#0000ff;">&lt;!</span>[CDATA[
var rutVal = document.all ? document.all["rutVal"] : document.getElementById("rutVal");
rutVal.controltovalidate = "TextBox1";
rutVal.errormessage = "RUT inválido";
rutVal.evaluationfunction = "ValidateRUT";
rutVal.required = "true";
rutVal.formatinput = "true";
var RequiredFieldValidator1 = document.all ? document.all["RequiredFieldValidator1"] : document.getElementById("RequiredFieldValidator1");
RequiredFieldValidator1.controltovalidate = "TextBox1";
RequiredFieldValidator1.errormessage = "RequiredFieldValidator";
RequiredFieldValidator1.evaluationfunction = "RequiredFieldValidatorEvaluateIsValid";
RequiredFieldValidator1.initialvalue = "";
//]]<span style="color:#0000ff;">&gt;</span>
<span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">script</span><span style="color:#0000ff;">&gt;</span></pre>
<p>To write the validation function you need to access this properties, so my first instinct was to use the <em>getAttribute</em> method, but this is what caused trouble in Firefox. Please pay attention to this: if the property is <strong>not part of the Dom definition</strong> for the element then <em>getAttribute</em> <strong>returns null</strong>. However, if the <strong>property is defined in the markup</strong>, in other words, as just another attribute, even if it makes the HTML invalid,  <em>getAttribute</em> <strong>returns the value</strong>.</p>
<p>The example above matches the first case, the properties are not part of the definition for the element (validators use the <em>span</em> element), and these are set via code, not markup. So, how should I get the values? Easy, the object-oriented way. Just write <strong>validator.propertyName.</strong></p>
<p>The safest practice is to try both ways. First you can try the validator.propertyName and if it returns null then try the getAttribute method. You can&#8217;t go wrong now.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/maxtoroq.wordpress.com/25/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/maxtoroq.wordpress.com/25/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/maxtoroq.wordpress.com/25/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/maxtoroq.wordpress.com/25/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/maxtoroq.wordpress.com/25/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/maxtoroq.wordpress.com/25/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/maxtoroq.wordpress.com/25/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/maxtoroq.wordpress.com/25/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/maxtoroq.wordpress.com/25/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/maxtoroq.wordpress.com/25/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/maxtoroq.wordpress.com/25/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/maxtoroq.wordpress.com/25/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maxtoroq.wordpress.com&blog=905434&post=25&subd=maxtoroq&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://maxtoroq.wordpress.com/2007/11/10/expando-properties-and-the-domelementgetattribute-method-in-firefox/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1056a38ecd323c658a8c9e93bb41b18d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">maxtoroq</media:title>
		</media:content>
	</item>
		<item>
		<title>Implementing a string.Format-like CreateCommand(string, params object[]) extension method</title>
		<link>http://maxtoroq.wordpress.com/2007/10/29/implementing-a-stringformat-like-createcommandstring-params-object-extension-method/</link>
		<comments>http://maxtoroq.wordpress.com/2007/10/29/implementing-a-stringformat-like-createcommandstring-params-object-extension-method/#comments</comments>
		<pubDate>Tue, 30 Oct 2007 01:21:18 +0000</pubDate>
		<dc:creator>maxtoroq</dc:creator>
				<category><![CDATA[ado.net]]></category>
		<category><![CDATA[extension methods]]></category>

		<guid isPermaLink="false">http://maxtoroq.wordpress.com/2007/10/29/implementing-a-stringformat-like-createcommandstring-params-object-extension-method/</guid>
		<description><![CDATA[When first trying out Linq to Sql I was very impressed about the very simple and concise ExecuteCommand method. This method take a SQL string plus zero or more of objects that represent the values of the parameters you wish to use in the command. The cool thing is that instead of writing in the string the name of the parameters, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maxtoroq.wordpress.com&blog=905434&post=24&subd=maxtoroq&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>When first trying out Linq to Sql I was very impressed about the very simple and concise ExecuteCommand method. This method take a SQL string plus zero or more of objects that represent the values of the parameters you wish to use in the command. The cool thing is that instead of writing in the string the name of the parameters, you use the same string.Format syntax. Using this technique, a simple call for deleting the Product that has ProductID set to 5 would be:</p>
<pre style="font-size:9pt;overflow:scroll;width:100%;color:black;line-height:normal;font-family:'Lucida Console', Consolas, 'Courier New', Courier, Monospace;background-color:#ffffff;">
ExecuteCommand(<span style="color:#800000;">"DELETE FROM Products WHERE ProductID = {0}"</span>, 5);</pre>
<p>One of the advantages for creating commands this way is that you can write provider-independent SQL, because you no longer need to use a marker like &#8216;@&#8217; or &#8216;?&#8217; in the command&#8217;s text. Also, you don&#8217;t need to assign the parameter names. Overall, it saves you a lot of repetitive code.</p>
<p>The only real problem for implementing this method is how to get the correct parameter marker for the provider being used. My solution depends on the specific ADO.NET provider implementations of the DbCommandBuilder.GetParameterPlaceholder and DbCommandBuilder.GetParameterName methods.</p>
<p>Here is the source code:</p>
<pre style="font-size:9pt;overflow:scroll;width:100%;color:black;line-height:normal;font-family:'Lucida Console', Consolas, 'Courier New', Courier, Monospace;background-color:#ffffff;">
<span style="color:#0000ff;">public</span> <span style="color:#0000ff;">static</span> <span style="color:#2b91af;">DbCommand</span> CreateCommand(<span style="color:#0000ff;">this</span> <span style="color:#2b91af;">DbProviderFactory</span> factory, <span style="color:#0000ff;">string</span> commandText, <span style="color:#0000ff;">params</span> <span style="color:#0000ff;">object</span>[] parameters) {
   <span style="color:#0000ff;">return</span> factory.CreateCommand(<span style="color:#0000ff;">null</span>, commandText, parameters);
}    

<span style="color:#0000ff;">public</span> <span style="color:#0000ff;">static</span> <span style="color:#2b91af;">DbCommand</span> CreateCommand(<span style="color:#0000ff;">this</span> <span style="color:#2b91af;">DbProviderFactory</span> factory, <span style="color:#2b91af;">DbConnection</span> connection, <span style="color:#0000ff;">string</span> commandText, <span style="color:#0000ff;">params</span> <span style="color:#0000ff;">object</span>[] parameters) {    

   <span style="color:#0000ff;">if</span> (commandText == <span style="color:#0000ff;">null</span>) <span style="color:#0000ff;">throw</span> <span style="color:#0000ff;">new</span> ArgumentNullException(<span style="color:#800000;">"commandText"</span>);    

   <span style="color:#2b91af;">DbCommand</span> cmd = factory.CreateCommand();    

   <span style="color:#0000ff;">if</span> (connection != <span style="color:#0000ff;">null</span>)
      cmd.Connection = connection;    

   <span style="color:#008000;">// No parameters passed</span>
   <span style="color:#0000ff;">if</span> (parameters == <span style="color:#0000ff;">null</span> || parameters.Length == 0) {
      cmd.CommandText = commandText;
      <span style="color:#0000ff;">return</span> cmd;
   }    

   <span style="color:#2b91af;">DbCommandBuilder</span> builder = factory.CreateCommandBuilder();
   <span style="color:#2b91af;">Type</span> builderType = builder.GetType();    

   <span style="color:#008000;">// These two lines are only to workaround some bad design in MySql Connector Net</span>
   builder.DataAdapter = factory.CreateDataAdapter();
   builder.DataAdapter.SelectCommand = cmd;    

   <span style="color:#2b91af;">MethodInfo</span> getParameterName = builderType.GetMethod(<span style="color:#800000;">"GetParameterName"</span>, <span style="color:#2b91af;">BindingFlags</span>.Instance | <span style="color:#2b91af;">BindingFlags</span>.NonPublic, Type.DefaultBinder, <span style="color:#0000ff;">new</span> Type[] { <span style="color:#0000ff;">typeof</span>(<span style="color:#2b91af;">Int32</span>) }, <span style="color:#0000ff;">null</span>);
   <span style="color:#2b91af;">MethodInfo</span> getParameterPlaceholder = builderType.GetMethod(<span style="color:#800000;">"GetParameterPlaceholder"</span>, <span style="color:#2b91af;">BindingFlags</span>.Instance | <span style="color:#2b91af;">BindingFlags</span>.NonPublic, Type.DefaultBinder, <span style="color:#0000ff;">new</span> Type[] { <span style="color:#0000ff;">typeof</span>(<span style="color:#2b91af;">Int32</span>) }, <span style="color:#0000ff;">null</span>);    

   <span style="color:#0000ff;">string</span>[] paramPlaceholders = (<span style="color:#0000ff;">string</span>[])<span style="color:#2b91af;">Array</span>.CreateInstance(<span style="color:#0000ff;">typeof</span>(<span style="color:#0000ff;">string</span>), parameters.Length);    

   <span style="color:#0000ff;">for</span> (<span style="color:#0000ff;">int</span> i = 0; i &lt; paramPlaceholders.Length; i++) {    

      <span style="color:#2b91af;">DbParameter</span> dbParam = cmd.CreateParameter();
      dbParam.ParameterName = (<span style="color:#0000ff;">string</span>)getParameterName.Invoke(builder, <span style="color:#0000ff;">new</span> <span style="color:#0000ff;">object</span>[] { i });
      dbParam.Value = parameters[i] ?? <span style="color:#2b91af;">DBNull</span>.Value;
      cmd.Parameters.Add(dbParam);    

      paramPlaceholders[i] = (<span style="color:#0000ff;">string</span>)getParameterPlaceholder.Invoke(builder, <span style="color:#0000ff;">new</span> <span style="color:#0000ff;">object</span>[] { i });
   }    

   cmd.CommandText = <span style="color:#0000ff;">string</span>.Format(commandText, paramPlaceholders);    

   <span style="color:#0000ff;">return</span> cmd;
}</pre>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/maxtoroq.wordpress.com/24/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/maxtoroq.wordpress.com/24/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/maxtoroq.wordpress.com/24/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/maxtoroq.wordpress.com/24/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/maxtoroq.wordpress.com/24/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/maxtoroq.wordpress.com/24/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/maxtoroq.wordpress.com/24/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/maxtoroq.wordpress.com/24/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/maxtoroq.wordpress.com/24/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/maxtoroq.wordpress.com/24/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/maxtoroq.wordpress.com/24/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/maxtoroq.wordpress.com/24/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maxtoroq.wordpress.com&blog=905434&post=24&subd=maxtoroq&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://maxtoroq.wordpress.com/2007/10/29/implementing-a-stringformat-like-createcommandstring-params-object-extension-method/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1056a38ecd323c658a8c9e93bb41b18d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">maxtoroq</media:title>
		</media:content>
	</item>
		<item>
		<title>Using Forms Authentication without a Membership Provider</title>
		<link>http://maxtoroq.wordpress.com/2007/09/27/using-forms-authentication-without-a-membership-provider/</link>
		<comments>http://maxtoroq.wordpress.com/2007/09/27/using-forms-authentication-without-a-membership-provider/#comments</comments>
		<pubDate>Fri, 28 Sep 2007 03:59:24 +0000</pubDate>
		<dc:creator>maxtoroq</dc:creator>
				<category><![CDATA[asp.net]]></category>
		<category><![CDATA[authentication]]></category>

		<guid isPermaLink="false">http://maxtoroq.wordpress.com/2007/09/27/using-forms-authentication-without-a-membership-provider/</guid>
		<description><![CDATA[This might seem obvious to some, but surely wasn&#8217;t to me. How to use Forms Authentication(that is, use the Login control, LoginStatus, etc) without a Membership provider?
ASP.NET comes with the built-in SqlMembershipProvider, which stores membership info in a SqlServer Express database (and saves it in ~/App_Data). The are a couple of reasons why you might not want [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maxtoroq.wordpress.com&blog=905434&post=23&subd=maxtoroq&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>This might seem obvious to some, but surely wasn&#8217;t to me. How to use Forms Authentication(that is, use the Login control, LoginStatus, etc) without a Membership provider?</p>
<p>ASP.NET comes with the built-in SqlMembershipProvider, which stores membership info in a SqlServer Express database (and saves it in ~/App_Data). The are a couple of reasons why you might not want to use it:</p>
<ul>
<li>You don&#8217;t have SqlServer installed in you production server.</li>
<li>You only want to give access to a couple of trusting users, so a database is a bit too much.</li>
</ul>
<p>So, how to prevent the usage of SqlMembershipProvider, or any configured provider? All you need to do is handle the Login.Authenticate event:</p>
<pre style="font-size:9pt;overflow:scroll;width:100%;color:black;line-height:normal;font-family:'Lucida Console', Consolas, 'Courier New', Courier, Monospace;background-color:#ffffff;">
<span style="color:#0000ff;">&lt;</span><span style="color:#800000;">script</span> <span style="color:#ff0000;">runat</span><span style="color:#0000ff;">="server"</span>&gt;
   <span style="color:#0000ff;">protected</span> <span style="color:#0000ff;">void</span> Login1_Authenticate(<span style="color:#0000ff;">object</span> sender, <span style="color:#2b91af;">AuthenticateEventArgs</span> e) { 

      e.Authenticated = <span style="color:#2b91af;">FormsAuthentication</span>.Authenticate(Login1.UserName, Login1.Password);
   }
<span style="color:#0000ff;">&lt;</span><span style="color:#800000;">/script</span><span style="color:#0000ff;">&gt;</span>    

<span style="color:#0000ff;">&lt;</span><span style="color:#800000;">asp:Login</span> <span style="color:#ff0000;">ID</span><span style="color:#0000ff;">="Login1"</span> <span style="color:#ff0000;">runat</span><span style="color:#0000ff;">="server"</span> <span style="color:#ff0000;">OnAuthenticate</span><span style="color:#0000ff;">="Login1_Authenticate"</span><span style="color:#0000ff;">/&gt;</span></pre>
<p>Since we are not using a Membership provider we can store our users credentials in the web.config&#8217;s system.web/authentication/forms/credentials section.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/maxtoroq.wordpress.com/23/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/maxtoroq.wordpress.com/23/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/maxtoroq.wordpress.com/23/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/maxtoroq.wordpress.com/23/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/maxtoroq.wordpress.com/23/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/maxtoroq.wordpress.com/23/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/maxtoroq.wordpress.com/23/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/maxtoroq.wordpress.com/23/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/maxtoroq.wordpress.com/23/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/maxtoroq.wordpress.com/23/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/maxtoroq.wordpress.com/23/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/maxtoroq.wordpress.com/23/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maxtoroq.wordpress.com&blog=905434&post=23&subd=maxtoroq&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://maxtoroq.wordpress.com/2007/09/27/using-forms-authentication-without-a-membership-provider/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1056a38ecd323c658a8c9e93bb41b18d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">maxtoroq</media:title>
		</media:content>
	</item>
		<item>
		<title>Importance of the Provider Metadata in Linq to Sql</title>
		<link>http://maxtoroq.wordpress.com/2007/07/31/importance-of-the-provider-metadata-in-linq-to-sql/</link>
		<comments>http://maxtoroq.wordpress.com/2007/07/31/importance-of-the-provider-metadata-in-linq-to-sql/#comments</comments>
		<pubDate>Wed, 01 Aug 2007 02:27:10 +0000</pubDate>
		<dc:creator>maxtoroq</dc:creator>
				<category><![CDATA[ado.net]]></category>
		<category><![CDATA[linq to sql]]></category>

		<guid isPermaLink="false">http://maxtoroq.wordpress.com/2007/07/31/importance-of-the-provider-metadata-in-linq-to-sql/</guid>
		<description><![CDATA[In this post I explain a simple way of how to take advantage of Linq to Sql for querying against any DBMS. However, today I realized that Linq to Sql was connecting to SqlServer when calling DataContext.GetCommand(). The reason is because it needed to figure out which version of SqlServer its going to get the data from, and [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maxtoroq.wordpress.com&blog=905434&post=22&subd=maxtoroq&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>In <a href="http://maxtoroq.wordpress.com/2007/07/24/querying-with-linq-to-sql-against-the-dbms-of-your-choice/">this post</a> I explain a simple way of how to take advantage of Linq to Sql for querying against any DBMS. However, today I realized that Linq to Sql was connecting to SqlServer when calling DataContext.GetCommand(). The reason is because it needed to figure out which version of SqlServer its going to get the data from, and for that uses the DbConnection.ServerVersion property.</p>
<p>You can avoid this by simply specifiying the provider metadata in your mapping info, so if you are using attributes you can add the ProviderAttribute to your DataContext class and pass either typeof(Sql2000Provider) or typeof(Sql2005Provider).</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/maxtoroq.wordpress.com/22/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/maxtoroq.wordpress.com/22/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/maxtoroq.wordpress.com/22/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/maxtoroq.wordpress.com/22/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/maxtoroq.wordpress.com/22/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/maxtoroq.wordpress.com/22/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/maxtoroq.wordpress.com/22/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/maxtoroq.wordpress.com/22/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/maxtoroq.wordpress.com/22/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/maxtoroq.wordpress.com/22/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/maxtoroq.wordpress.com/22/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/maxtoroq.wordpress.com/22/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=maxtoroq.wordpress.com&blog=905434&post=22&subd=maxtoroq&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://maxtoroq.wordpress.com/2007/07/31/importance-of-the-provider-metadata-in-linq-to-sql/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1056a38ecd323c658a8c9e93bb41b18d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">maxtoroq</media:title>
		</media:content>
	</item>
	</channel>
</rss>