Posts Tagged “c#”

Monday, August 4, 2014
  A Handy C# Async Utility Method

In the course of writing C# code utilizing the new (for 4.5.1) Task-based asynchronous programming, I've run across a couple of places where the await keyword either is not allowed (a catch block or a property accessor) or the async keyword greatly complicates the syntax (lambda expressions). I've found myself writing this method for two different projects, and so I thought I would drop this Q&D, more-comments-than-code utility method here for others to use if you see the need.

(UPDATE: This works well in console applications; it can cause deadlocks in desktop and web apps. Test before you rely on it.)

/// <summary>
/// Get the result of a task in contexts where the "await" keyword may be prohibited
/// </summary>
/// <typeparam name="T">The return type for the task</typeparam>
/// <param name="task">The task to be awaited</param>
/// <returns>The result of the task</returns>
public static T TaskResult<T>(Task<T> task)
{
    Task.WaitAll(task);
    return task.Result;
}

And, in places where you can't do something like this…

/// <summary>
/// A horribly contrived example class
/// </summary>
/// <remarks>Don't ever structure your POCOs this way, unless EF is handling the navigation properties</remarks>
public class ExampleClass
{
    /// <summary>
    /// A contrived ID to a dependent entity
    /// </summary>
    public int ForeignKeyID { get; set; }

    /// <summary>
    /// The contrived dependent entity
    /// </summary>
    public DependentEntity DependentEntity
    {
        get
        {
            // Does not compile; can't use await without async, can't mark a property as async
            return await Data.DependentEntities
                .FirstOrDefaultAsync(entity => entity.ID == ForeignKeyID);
        }
    }
}

...you can instead do this in that “DependentEntity” property…

    /// <summary>
    /// The contrived dependent entity
    /// </summary>
    public DependentEntity DependentEntity
    {
        get
        {
            return UtilClass.TaskResult<DependentEntity>(Data.DependentEntities
                .FirstOrDefaultAsync(entity => entity.ID == ForeignKeyID));
        }
    }
Categorized under
Tagged , ,

Saturday, October 22, 2011
  Database Abstraction v0.8

When we began developing C# web applications, we found ourselves in the position of determining what the best way of accessing the database is. We evaluated several technologies…

  • NHibernate - May be very good, but it was overkill for what we were trying to do.
  • LINQ to SQL - This brings C#'s LINQ (Language-Integrated Query) to SQL databases. You create database-aware classes and use LINQ to select from collections, which LINQ to SQL converts to database access. This is a good abstraction, but it relies on SQL Server; as we typically deploy to PostgreSQL, this didn't work. (We also couldn't get DBLinq, a database-agnostic implementation, to work.)
  • ADO.NET - This is the tried-and-true database access methodology, released as part of the initial release of the .NET framework. The downside to this is that it encourages SQL in the code at the point of data retrieval; it does not provide a clean separation of data access from data processing.
  • EF Code First - This didn't exist; it's also very SQL Server-centric. Not faulting Microsoft for that, especially since they release a free version now; but, as we deploy on Linux, until they release a Linux version, SQL Server is not an option.

With our PHP applications, we had written a database service that read queries from XML files. Then, queries were accessed by name, with parameters passed via arrays. The one thing that ADO.NET has that was useful was the fact that it is based on interfaces. This means that if we wrote something that exposed, manipulated, and depended on IDataConnection (instead of SqlConnection, the SQL Server implementation of that interface), we could support any implementation of database. The SqlDataReader implements IDataReader as well. Our solution was becoming apparent.

Over time, we developed what is now the Database Abstraction project hosted on CodePlex (UPDATE: migrated project to GitHub). On Thursday, we released the first public release (although the DLLs are in the repository, and are usually current at every commit). If you are looking for a way to separate your data access from the rest of your code, or want a solution that's database-agnostic, check it out. It supports SQL Server, MySQL, PostgreSQL, SQLite, and ODBC connections *, using the data provider name to derive the proper connection to implement. There is also a Mock implementation to support unit tests; this mock can provide data, providing a useful way to test methods. Finally, there is a membership and role provider based on Database Abstraction; simply configure the connection string, create the database tables, and away you go! **

A pre-release version is already in production use in our PrayerTracker application, and others are being built around it. If this sounds like something that could help your project, certainly feel free to check it out!

* Oracle is omitted from this list, as their DLL had redistribution restrictions; this meant that the source code repository, upon check-out, would have build errors. There may be an Oracle implementation in the future (it would be trivial), but there is not one now.

** The membership and role providers are untested; they will be tested and tweaked by version 0.9.

Categorized under , , , , ,
Tagged , , , , ,