WSCF.blue V1.0.13 Update

by Alex Meyer-Gleaves 14 October 2011 - 6:53 AM

imageI have posted a V1.0.13 update for WSCF.blue to address a bug with the WSDL round-tripping feature. It was reported that message headers were not being round-tripped in the WSDL when fault messages existed for the same operation. I normally prefer to batch up a few bug fixes for an update build, but I can appreciate that this particular bug would get very annoying when using headers along with numerous operations.

Tags: ,

WSCF | Web Services

DateTime precision with MongoDB and the C# Driver

by Alex Meyer-Gleaves 30 September 2011 - 6:34 AM

When dealing with a database you need to be aware of any differences between how a data type is represented in your programming language and how it is stored in the database. These differences may not be noticeable at first but often surface later, when a query is not returning the expected results, or a round-tripped value is no longer exactly equal to the original value stored. The DateTime data type in .NET has a fairly high precision of 100-nanoseconds per tick and is a candidate for such issues.

Time values are measured in 100-nanosecond units called ticks, and a particular date is the number of ticks since 12:00 midnight, January 1, 0001 A.D. (C.E.) in the GregorianCalendar calendar (excluding ticks that would be added by leap seconds).

Even with SQL Server there was a considerable difference in precision prior to the introduction of the DATETIME2 data type, given that DATETIME values are stored with a precision of 3.33 milliseconds. When the required level of precision cannot find its way into the database to be round-tripped without loss a workaround needs to be created.

MongoDB stores data in a BSON format, which is a binary representation of the popular JSON format. The specification indicates that a UTC datetime value is stored as a 64-bit signed integer representing the number of milliseconds since the Unix epoch. Once again we have a mismatch in precision to the DateTime data type in .NET and need to find a workaround for this difference.

The officially supported C# driver for MongoDB provides us with some options when it comes to serializing DateTime values into the their BSON representation. Fortunately, one of these options is able to assist with the handling of precision without resorting to storing values in a different .NET data type. Lets have a look at how DateTime values are stored by working with a very simple object that has a single DateTime property called Timestamp. We will let MongoDB assign an Id value for the document.

public class Record
{
    public Guid Id { get; set; }

    public DateTime Timestamp { get; set; }
}

We will also need to write some code to insert a record so that we can have a look at the stored value. The code below creates a records collection in the test database of the local server. It then inserts a new Record document into the collection after ensuring that the collection is empty to begin with.

MongoServer server = MongoServer.Create("mongodb://localhost");
MongoDatabase database = server.GetDatabase("test");

MongoCollection<BsonDocument> records = database.GetCollection("records");
records.Drop(); // Remove any existing documents.

Record record = new Record {Timestamp = DateTime.UtcNow};
records.Insert(record);

server.Disconnect();

The result is a document with a Timestamp property that is saved using a call to ISODate. This is simply a helper function and the provided datetime will be stored as an integer value as per the BSON specification.

{ "_id" : ObjectId("4e848461d0ba9f8047c27dc7"), "Timestamp" : ISODate("2011-09-29T14:44:49.172Z") }

To gain further control of the serialization the BsonDateTimeOptionsAttribute can be applied to a DateTime property. The attribute has three properties: DateOnly, Kind and Representation. Setting the DateOnly property to true causes the time of day component to be stored as zero, and setting the Kind property allows us to store the DateTimeKind. These first two options are not going to help us with our precision issues but are obviously useful for other scenarios. It is setting the third option of Representation to BsonType.Document that will allow us to keep our tick level precision.

public class Record
{
    public Guid Id { get; set; }

    [BsonDateTimeOptions(Representation = BsonType.Document)]
    public DateTime Timestamp { get; set; }
}

After applying the attribute to our Timestamp property we can see that the value is now persisted in a format that includes the value from the Ticks property of the DateTime. This special handling of the BsonType.Document representation is being handled by the DateTimeSerializer class in the driver.

{ "_id" : ObjectId("4e848714d0ba9f8047c27dc8"), "Timestamp" : { "DateTime" : ISODate("2011-09-29T14:56:20.481Z"), "Ticks" : NumberLong("634529049804813857") } }

Instead of applying the attribute to each DateTime property it is possible to specify the default serialization behaviour by setting the DateTimeSerializationOptions.Default property.

DateTimeSerializationOptions.Defaults = new DateTimeSerializationOptions(DateTimeKind.Utc, BsonType.Document);

Now that we have the DateTime value stored with the desired precision we need to be aware of this document format when it comes time to query the values. In order to perform comparisons in a query we will compare the Ticks property of the reference DateTime to the Ticks property of the stored DateTime element.

DateTime utcNow = DateTime.UtcNow;
Record insertedRecord = new Record {Timestamp = utcNow};
records.Insert(insertedRecord);

QueryComplete query = Query.EQ("Timestamp.Ticks", utcNow.Ticks);
Record queriedRecord = records.FindOneAs<Record>(query);
Console.WriteLine(insertedRecord.Timestamp.Ticks == queriedRecord.Timestamp.Ticks);

The same technique can be used with the other comparison operators such as GT, GTE, LT and LTE. You can always encapsulate these details into a simple helper class like the sample below for the comparisons you require.

public static class DateTimeQuery
{
    public static QueryComplete EQ(string name, DateTime value)
    {
        return new QueryComplete(new BsonDocument(GetTicksName(name), value.Ticks));
    }

    public static QueryConditionList GT(string name, DateTime value)
    {
        return new QueryConditionList(GetTicksName(name)).GT(value.Ticks);
    }

    public static QueryConditionList GTE(string name, DateTime value)
    {
        return new QueryConditionList(GetTicksName(name)).GTE(value.Ticks);
    }

    public static QueryConditionList LT(string name, DateTime value)
    {
        return new QueryConditionList(GetTicksName(name)).LT(value.Ticks);
    }

    public static QueryConditionList LTE(string name, DateTime value)
    {
        return new QueryConditionList(GetTicksName(name)).LTE(value.Ticks);
    }

    static string GetTicksName(string name)
    {
        return name.EndsWith(".Ticks") ? name : name + ".Ticks";
    }
}

This lets you query directly on the property name and provide the DateTime value. No worrying about ticks.

QueryComplete query = DateTimeQuery.EQ("Timestamp", utcNow);
Record queriedRecord = records.FindOneAs<Record>(query);

The end result seems reasonable. Persisted DateTime values keep full precision and are deserialized into a DateTime value. Querying for the data becomes a little more difficult but some helpers can reduce the friction. These results were confirmed using MongoDB 2.0.0 and the MongoDB C# Driver 1.2.0.4274.

Tags:

Database

BlogEngine.NET 2.5 Upgrade

by Alex Meyer-Gleaves 31 July 2011 - 6:39 AM

I just upgraded to BlogEngine.NET 2.5 and found the process to be fairly straight forward. The upgrade instructions suggest that you start from a v2.5 installation, and then copy your existing data and settings into the fresh install. I did this and then copied some additional files that were not explicitly mentioned in the instructions. Most of these were files that I added myself to customise the blog.

  • The apple-touch-icon.png file into the root folder.
  • Extensions I added into the App_Code/Extensions folder.
  • The assembly for a custom extension I wrote into the bin folder.
  • SQL Server CE runtime files and .NET provider assembly into the bin folder.
  • JavaScript files for the jQuery lightBox plugin that I use.

After the upgrade I did get one compiler error in the SimpleDownloadCounter extension.

Compiler Error Message: CS1061: 'BlogEngine.Core.BlogSettings' does not contain a definition for 'StorageLocation' and no extension method 'StorageLocation' accepting a first argument of type 'BlogEngine.Core.BlogSettings' could be found (are you missing a using directive or an assembly reference?)

That was easily fixed by replacing the occurrence of BlogSettings.Instance.StorageLocation with BlogConfig.StorageLocation.

I moved from VistaDB to SQL Server CE during the 2.0 upgrade so that more difficult migration was already done. This time I only needed to run the SQL_CE_UpgradeFrom2.0to2.5.sql upgrade script to update my SQL Server CE database schema. I used the SQL Server Compact Toolbox add-in for Visual Studio 2010 to run the script and had no problems.

Because I run a custom theme I check for new additions to the Standard theme and add any that I feel are required into my own. A quick check of the differences showed a new item was added to the header menu in the site.master file. It adds a link to the menu that allows a user to switch between the regular and mobile version of the site when viewed on a mobile device.

<% if (Utils.IsMobile)
   { %>
<li><blog:MobileThemeSwitch runat="server" /></li>
<%
   }
%>

It seemed like a cool feature so I added the new code to my custom theme and tested the site from my iPhone to check that the new menu item was working. There were also a couple of CSS modifications that I moved over too. The last thing was to fix the titles on the Recent Comments and Recent Posts widgets. Either the space in the titles was removed during the upgrade or they were never there and I have only just noticed.

Overall, nothing too stressful. The complete list of new features in 2.5 can be found here.

Tags:

BlogEngine.NET

WSCF.blue V1.0.12 Update

by Alex Meyer-Gleaves 26 June 2011 - 5:44 AM

A V1.0.12 update release of WSCF.blue is now available for download from CodePlex. Like the previous update, this one contains a few bug fixes and one new feature. This update is made available to you courtesy of user contributed patches. A big thank you to users BartKoelman, cjberg, jamaica and MrGlover for their contributions.

Features

  • Added a new AutoSetSpecifiedPropertiesDecorator to automatically set the _Specified property to true when setter on matching property is called. Obviously this will only work when the Properties option is used.

Bug Fixes

  • Reduced the number of times menu visibility is updated in the SelectionEvents.OnChange event to help prevent OutOfMemoryException inside EnvDTE.
  • Fixed NullReferenceException in OnTypeNameChanged method of MessageContractConverter.
  • Improved validation of namespace identifiers. The original implementation only allowed ASCII letters among other deficiencies, even though C# allows most Unicode letters in identifiers.
  • Data contract generation - choice element name incorrect in generated class (http://wscfblue.codeplex.com/workitem/10624).
  • Incorrect XmlTypeAttribute for same-named types in different namespaces (http://wscfblue.codeplex.com/workitem/12733).
  • Patch for NullReferenceException on inline XSD (http://wscfblue.codeplex.com/workitem/13714).

Tags: ,

WSCF | Web Services

Windows 8 Videos

by Alex Meyer-Gleaves 2 June 2011 - 5:56 AM

It looks like the recent rumours were indeed true. The first official previews of Windows 8 are starting to surface from the D9 and Computex conferences. It appears that just like the conferences the focus is all on tablet devices.

Today, at the D9 Conference, we demonstrated the next generation of Windows, internally code-named “Windows 8,” for the first time. Windows 8 is a reimagining of Windows, from the chip to the interface. A Windows 8-based PC is really a new kind of device, one that scales from touch-only small screens through to large screens, with or without a keyboard and mouse.

If you are a Windows user looking to buy a tablet, do you buy a Windows 7 tablet now and upgrade to Windows 8 later? Running Windows 8 on the same hardware shouldn’t be a problem, but your upgrade wont be happening until sometime next year. The Android Honeycomb 3.1 update has started to roll out, and more important than just being a good update, you can actually buy a tablet and start using it right now. It’s a shame that Microsoft are still so far away from making a serious venture (back) into the tablet market.

Windows 8 sneak peak

COMPUTEX: Microsoft introduces Windows 8

Tags:

General

Random links for April 2011

by Alex Meyer-Gleaves 30 April 2011 - 5:22 AM

Here are a few links that I found interesting for one reason or another.

  • Helvetireader²
    Helvetireader is a hosted user stylesheet for Google Reader served via a user-script. It aims to make the interface a clean, minimal experience where you're not assaulted by an array of colours, social features and buttons (using Shortcuts instead). It's designed for people who just read the latest entries in expanded view without all the other gubbins.
  • DotNetOpenAuth | C# Library for OpenID, OAuth and InfoCards
    Compiled library that adds support for your site visitors to login with their OpenIDs by just dropping an ASP.NET control onto your page. It’s that easy. An AJAX-style OpenID Selector control is also included for a slick, streamlined user experience.
  • sstephenson/stitch - GitHub
    Develop and test your JavaScript applications as CommonJS modules in Node.js. Then Stitch them together to run in the browser.
  • CommonJS: JavaScript Standard Library
    JavaScript is a powerful object oriented language with some of the fastest dynamic language interpreters around.
  • JustDecompile - Free .NET Decompiling Tool
    JustDecompile is a new, free developer productivity tool designed to enable easy .NET assembly browsing and decompiling. JustDecompile lets you effortlessly explore and analyze compiled .NET assemblies, decompiling code with the simple click of a button.
  • JustTrace - Memory and Performance Profiling by Telerik
    JustTrace is a new developer productivity tool, which enables you to profile .NET applications easier and faster than ever before. By quickly and effortlessly identifying disabling application bottlenecks, JustTrace helps you achieve optimal performance and memory usage for all of your .NET projects, from Silverlight to ASP.NET to WinForms.
  • Echo - Build Highly Social Real-time Apps.
    Apps listed here are real-time, social and interoperable through open standards. They are designed to transform your site into a first class social experience.
  • RealTidbits - Real Time Database Widgets
    Create exceptional experiences for your users and leverage the social activity occurring on your site with real-time database applications.
  • OpenStack Open Source Cloud Computing Software
    Open source software to build private and public clouds.
  • Online Presentation Software | Free PowerPoint Online | Web Presentation | SlideRocket.
    SlideRocket is a powerful, unique, comprehensive presentation software solution that provides a full suite of features and capabilities to address all facets of the presentation lifecycle - from authoring, collaboration, and review and approval, through publishing, delivery, and management. SlideRocket provides users with all the tools they need to create and manage stunning online presentations, share them securely with people across the globe, and measure their effectiveness, in a single, fully-integrated package.
  • monitter : real time, live twitter search and monitoring
    Monitter is a real time twitter search tool that enables you to monitor a set of keywords on twitter. It also allows you to narrow the search to a particular geographic location, allowing you to find out what’s going onin a particular part of the world.
  • chartbeat - real-time website analytics and uptime monitoring
    Control the story, track a product launch, or exploit an opportunity as it happens. Our dashboard, iPhone app, and email & SMS alerts let you know the minute your traffic spikes, your servers crash, or your page slows to a crawl.
  • jQuery Form Framework - jFormer
    jFormer is a form framework written on top of jQuery that allows you to quickly generate beautiful, standards compliant forms.
  • Download details: Producer for PowerPoint
    Use Microsoft Producer for Microsoft Office PowerPoint to capture and synchronize audio, video, slides, and images, then preview and publish a rich media presentation virtually anywhere for viewing in a Web browser.
  • Download details: Psscor4 Managed-Code Debugging Extension for WinDbg
    Psscor4 can help you diagnose high-memory issues, high-CPU issues, crashes, hangs and many other problems that might occur in a .NET application; in scenarios involving live processes or dump files.If you are familiar with SOS.dll, the managed-debugging extension that ships with the .NET Framework, Psscor4.dll provides a superset of that functionality.
  • Incredible StartPage - Productive Start Page for Chrome! - Google Chrome extension gallery
    A new, customizable start page for Chrome. Easily find your favorite bookmarks and closed tabs. Take notes as you browse.
  • Serene
    Serene is a library for Windows Phone 7 that allows applications to self monitor usage and try to prompt good users to leave feedback on marketplace.
  • Simple Service Bus
    Simple Service Bus is an asynchronous messaging framework that enables the rapid construction and customization of messaging endpoints, allowing services and applications to interact with one another across the network in a fault tolerant, robust environment that is less susceptible to network volatility than traditional synchronous approaches to distributed systems. SSB can be used as a message bus in an SOA, or simply as an integration tool enabling reliable cross process communication among distributed software components.
  • SpecsFor - Yet Another BDD Framework For .NET
    SpecsFor is another Behavior-Driven Development framework that focuses on ease of use for *developers* by minimizing testing friction.
  • Intel® Inspector XE Thread and Memory Checker - Intel® Software Network
    Intel® Inspector XE 2011 is a powerful and easy-to-use memory and threading error checking tool for C, C++, C# .NET, and Fortran developers designing serial and parallel applications on Windows*- and Linux*-based platforms.
  • KeyFocus - KF Web Server - High performance HTTP Server
    KF Web Server is a free HTTP Server that can host an unlimited number of web sites. Its small size, low system requirements and easy administration make it the perfect choice for both professional and amateur web developers alike.
  • mongrel2: mongrel2
    Mongrel2 is an application, language, and network architecture agnostic web server that focuses on web applications using modern browser technologies.
  • Apache Thrift
    Thrift is a software framework for scalable cross-language services development. It combines a software stack with a code generation engine to build services that work efficiently and seamlessly between C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, Smalltalk, and OCaml.
  • BSON - Binary JSON
    BSON [bee · sahn], short for Bin­ary JSON, is a bin­ary-en­coded seri­al­iz­a­tion of JSON-like doc­u­ments. Like JSON, BSON sup­ports the em­bed­ding of doc­u­ments and ar­rays with­in oth­er doc­u­ments and ar­rays.
  • UltiDev Cassini 2.0 - Free Redistributable ASP.NET Web Server from UltiDev LLC
    UltiDev Cassini is a free, light-weight and redistributable web server that can host ASP.NET 3.5, 3.0, 2.0 and 1.1 applications and static HTML sites. Whenever your customers need an alternative to IIS — UltiDev Cassini web server is the answer.
  • Ext.NET | Open-Source ASP.NET Web Components
    Ext.NET is an open source ASP.NET (WebForm + MVC) component framework integrating the cross-browser Sencha Ext JS JavaScript Library. Includes 100+ high performance controls for Data Grids, Trees, Menus, Forms, Advanced Layouts and AJAX communication.
  • HAProxy - The Reliable, High Performance TCP/HTTP Load Balancer
    HAProxy is a free, very fast and reliable solution offering high availability, load balancing, and proxying for TCP and HTTP-based applications. It is particularly suited for web sites crawling under very high loads while needing persistence or Layer7 processing.
  • nginx
    nginx [engine x] is a HTTP and reverse proxy server, as well as a mail proxy server written by Igor Sysoev.
  • nginn-messagebus - An application message bus implementation for .Net - Google Project Hosting
    NGinn Message Bus is a very simple ESB for .Net supporting publish-subscribe message distribution. It uses SQL server as message queuing mechanism - each message queue is stored in a separate table.
  • bclcontrib-abstract - .Net Abstraction library for complex systems, with adaptor libraries for common implemetations. - Google Project Hosting"
    .Net Abstraction library for complex systems, with adaptor libraries for common implemetations.
  • Shuttle Service Bus
    This project aims to provide a free open-source enterprise service bus.
  • Subversion Hosting, Git Hosting, Project Management
    Unfuddle is a secure, hosted project management solution for software development teams.
  • Yoono - Twitter Facebook MySpace LinkedIn Flickr - Share and Download Youtube videos
    Yoono is free software that allows you to connect and share with all your social networks and instant messaging services in one place.
  • Welcome to Cloud Foundry
    The industry’s first open platform as a service. Run your Spring, Rails and Node.js applications. Deploy from your IDE or command line.
  • Topshelf's Profile - GitHub
    An easy service hosting framework for building Windows services using .NET.
  • Learn You Some Erlang for Great Good!
    Oh Hello! Welcome to my guide to Erlang! This guide is intended to be read by beginners, but if you're average or somewhat advanced you can probably learn a few things too!
  • Less is More - zeromq
    The socket library that acts as a concurrency framework.
  • Ninite - Install or Update Multiple Apps at Once
    Just pick your apps and click Get Installer. Ninite does the rest — fully automatic.
  • Sci2ools - Free Online Productivity Tools - Sciweavers
    Free online document processor and image converter toolbox.
  • OpenVPN - Open Source VPN
    OpenVPN, our award-winning open source VPN product, has established itself as a de-facto standard in the open source networking space, with over 3 million downloads since inception.
  • StyleCop - Download: 4.5 Preview
    This release includes the very latest StyleCop for ReSharper plugin and will automatically uninstall previous versions of StyleCop.
  • Greenshot - a free and open source screenshot tool for productivity
    Being easy to understand and configurable, Greenshot is an efficient tool for project managers, software developers, technical writers, testers and anyone else creating screenshots.
  • PNGGauntlet - PNG Compression Software | BenHollis.net
    PNGGauntlet is a .NET program that uses Ken Silverman's PNGOUT command line utility to optimize PNG files.
  • was it up?
    We perform a HTTP HEAD request and check that the status code is 200 OK. If you provided a text to match we perform a GET request, check that the status code is 200 OK, and check that the text is present/not present in the returned HTTP body.
  • QUnit
    QUnit is a powerful, easy-to-use, JavaScript test suite. It's used by the jQuery project to test its code and plugins but is capable of testing any generic JavaScript code (and even capable of testing JavaScript code on the server-side).

Tags:

Random

Random links for March 2011

by Alex Meyer-Gleaves 31 March 2011 - 5:20 AM

Here are a few links that I found interesting for one reason or another.

  • EventStore
    The EventStore is a persistence library used to abstract different storage implementations when using event sourcing as storage mechanism. Event sourcing is most closely associated with a concept known as CQRS.
  • QuickTime Alternative (QT Lite) 4.1.0
    QT Lite is a lightweight version of QuickTime. It contains only the essential components that are required for viewing QuickTime content in your favorite browser.
  • HTML5 Readiness
    HTML5 Readiness now shows how HTML5 support has evolved since 2008. Click away to see the spurt of growth in 2010!
  • CSS3 Buttons
    CSS3 Buttons is a simple framework for creating good-looking GitHub style button links.
  • jquery.domsearch
    It lets you search within an element (e.g.: a table or a list), narrowing down the inner elements using LiquidMetal, which is way better than whatever else you could come up with.
  • Orbit Downloader: the ultra file & social media (YouTube etc..) download manager
    Orbit Downloader, leader of download manager revolution, is devoted to new generation web (web2.0) downloading, such as video/music/streaming media from Myspace, YouTube, Imeem, Pandora, Rapidshare, support RTMP.
  • Using OAuth 2.0 to Access Google APIs - Authentication and Authorization for Google APIs - Google Code
    Google supports a recent draft of the OAuth 2.0 protocol with bearer tokens for authorizing access to private user data. The spec is close to settling down, and we intend to update our code to match the final OAuth 2.0 and bearer token standards.
  • Official Google Blog: Advanced sign-in security for your Google account
    2-step verification requires two independent factors for authentication, much like you might see on your banking website: your password, plus a code obtained using your phone.
  • Amplify - A Component Library for jQuery
    Amplify is a set of components designed to solve common web application problems with a simplistic API. Amplify's goal is to simplify all forms of data handling by providing a unified API for various data sources.
  • Easy WebSocket - a WebSocket client to broadcast messages to webpages
    EasyWebSocket is simple websockets broadcasting. It is perfect for a quick prototype.. getting it going quick. 90% this is all you need if you're doing websocket something.
  • flensed :: flXHR means Easy Cross-Domain Ajax
    flXHR [flek's?r],(flex-er) is a *client-based* cross-browser, XHR-compatible tool for cross-domain Ajax (Flash) communication.
  • Zero Base-Overhead Data-Race Detection - Microsoft Research
    This tool finds data races in multithreaded code. It uses a combination of code and data break points to find data races effectively with little or no runtime overhead.
  • The Book Depository
    Free shipping worldwide on all our books.
  • CQRS-FAQ - home
    Welcome, this is a place to collect frequently asked questions, and hopefully some answers, about Command Query Responsibility Segregation.
  • WCF Binding Converter
    BindingBox is an online application that converts WCF bindings to a customBinding configuration.
  • NoScript - JavaScript/Java/Flash blocker for a safer Firefox experience! - what is it? - InformAction
    The NoScript Firefox extension provides extra protection for Firefox, Seamonkey and other mozilla-based browsers: this free, open source add-on allows JavaScript, Java and Flash and other plugins to be executed only by trusted web sites of your choice.
  • Readability
    Readability is a web & mobile app that zaps online clutter and saves web articles in a comfortable reading view. No matter where you are or what device you use, your reading will be there.
  • Internet Explorer 6 Countdown
    We know that web developers are spending too much time supporting Internet Explorer 6. We understand, and we’re here to help. Join us in moving Internet Explorer 6 users to a modern browser.
  • Welcome to Solr
    Solr is the popular, blazing fast open source enterprise search platform from the Apache Lucene project.
  • ILSpy
    ILSpy is the open-source .NET assembly browser and decompiler. Development started after Red Gate announced that the free version of .NET Reflector would cease to exist by end of February 2011.
  • OpenWrap - Package Management for .NET
    OpenWrap lets you search for and consume packages in your projects, and resolve for you the various dependencies that each of those packages contain.
  • JQuery IFrame Loader
    This is jQuery iFrame, a plugin to help you set iframe source and squirt content into iframes, by Michael Mahemoff, under MIT License.
  • PowerConsole
    This extension provides an extensible VS command window with default PowerShell integration. You can now script Visual Studio interactively in PowerShell, and enjoy familiar VS style syntax coloring and tab-completion.
  • PowerGUI Visual Studio Extension
    The PowerGUI Visual Studio Extension adds PowerShell IntelliSense support to Visual Studio.
  • git-tfs
    git-tfs is a two-way bridge between TFS and git, similar to git-svn.
  • About MyDreamCity.org | My Dream City
    MyDreamCity.org is a fun worldwide project. It encourages children without families and raises social awareness about their situation. Any city in the world can join and contribute!
  • RStudio
    RStudio™ is a new integrated development environment (IDE) for R. RStudio combines an intuitive user interface with powerful coding tools to help you get the most out of R.
  • Portable Library Tools CTP
    Portable Library Tools is a new Visual Studio add-in from Microsoft that enables you to create C# and Visual Basic libraries that run on a variety of .NET-based platforms without recompilation.

Tags:

Random

FilterAttribute Property Injection in Autofac MVC 3 Integration

by Alex Meyer-Gleaves 24 March 2011 - 3:56 AM

The current mechanism for performing property injection on FilterAttribute instances via the ExtensibleActionInvoker had to be removed recently due to a rather nasty bug. These are the notes that Nick provided outlining the problem he discovered (possibly with the help of the exciting new Whitebox profiler).

Because the filters passed from the base action invoker also include the controller, property injection happens on the controller itself several times as the filters are processed.

The filter attributes also included in the collection may also be singletons cached by MVC, and so it is quite likely that dependencies may be overwritten with those from a concurrently executing request.

In all this behaviour is probably too risky to reliably support.

Removed property injection routine. (Breaking change.)

I have replaced the old mechanism using an approach that leverages the improved dependency injection support added to MVC 3 (this will be in the next release). To make use of property injection for your filter attributes all you will need to do is call the RegisterFilterProvider method on the ContainerBuilder before building your container and providing it to the AutofacDependencyResolver.

ContainerBuilder builder = new ContainerBuilder();

builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.Register(c => new Logger()).As<ILogger>().InstancePerHttpRequest();
builder.RegisterFilterProvider();

IContainer container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

Then you can add properties to your filter attributes and any matching dependencies that are registered in the container will be injected into the properties. For example, the action filter below will have the ILogger instance that was registered above injected. Note that the attribute itself does not need to be registered in the container.

public class CustomActionFilter : ActionFilterAttribute
{
    public ILogger Logger { get; set; }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        Logger.Log("OnActionExecuting");
    }
}

The same simple approach applies to the other filter attribute types such as authorization attributes.

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    public ILogger Logger { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        Logger.Log("AuthorizeCore");
        return true;
    }
}

After applying the attributes to your actions as required your work is done.

[CustomActionFilter]
[CustomAuthorizeAttribute]
public ActionResult Index()
{
    // ...
}

To make this work I added a custom FilterAttributeFilterProvider implementation. The custom filter provider delegates the job of collecting the filters to the base class. Once the filters have been retrieved by the base class, the ILifetimeScope for the current HTTP request is retrieved and used to perform property injection on the filters. The false passed to the base FilterAttributeProvider constructor sets the cacheAttributeInstances parameter to ensure that attribute instances are not cached. Allowing the attribute instances to be cached would result in race conditions and other unexpected behaviour.

/// <summary>
/// Defines a filter provider for filter attributes that performs property injection.
/// </summary>
public class AutofacFilterAttributeFilterProvider : FilterAttributeFilterProvider
{
    /// <summary>
    /// Initializes a new instance of the <see cref="AutofacFilterAttributeFilterProvider"/> class.
    /// </summary>
    /// <remarks>
    /// The <c>false</c> constructor parameter passed to base here ensures that attribute instances are not cached.
    /// </remarks>
    public AutofacFilterAttributeFilterProvider() : base(false)
    {
    }

    /// <summary>
    /// Aggregates the filters from all of the filter providers into one collection.
    /// </summary>
    /// <param name="controllerContext">The controller context.</param>
    /// <param name="actionDescriptor">The action descriptor.</param>
    /// <returns>
    /// The collection filters from all of the filter providers with properties injected.
    /// </returns>
    public override IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
    {
        var filters = base.GetFilters(controllerContext, actionDescriptor).ToArray();
        var lifetimeScope = AutofacDependencyResolver.Current.RequestLifetimeScope;

        if (lifetimeScope != null)
            foreach (var filter in filters)
                lifetimeScope.InjectProperties(filter.Instance);

        return filters;
    }
}

The RegisterFilterProvider method has been added to the ContainerBuilder using an extension method. This method will register the AutofacFilterAttributeFilterProvider using the IFilterProvider interface that MVC uses when asking the dependency resolver for filter providers. Following the instructions outlined in Brad Wilson’s post on the subject of dependency injection and filters, I made sure that the default FilterAttributeFilterProvider instance is removed from the static collection of providers.

/// <summary>
/// Registers the <see cref="AutofacFilterAttributeFilterProvider"/>.
/// </summary>
/// <param name="builder">The container builder.</param>
public static void RegisterFilterProvider(this ContainerBuilder builder)
{
    if (builder == null) throw new ArgumentNullException("builder");

    foreach (var provider in FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().ToArray())
        FilterProviders.Providers.Remove(provider);

    builder.RegisterType<AutofacFilterAttributeFilterProvider>()
        .As<IFilterProvider>()
        .SingleInstance();
}

If you were using the old mechanism you will have breaking changes to contend with, but as you can see it should be easy to get back on track again.

Tags: ,

Autofac | Web Development

Random links for February 2011

by Alex Meyer-Gleaves 7 March 2011 - 12:15 AM

I can’t believe another month has past already. It really is time to get back to writing some proper blog posts. Anyway, here are a few links that I found interesting for one reason or another.

  • Oapt
    An NUnit addin for running one assert per test.
  • Debug Analyzer.NET
    Debug Analyzer.NET is a debugging automation tool to analyze memory dumps using analysis plug-ins written in .NET!
  • arbor.js
    Arbor is a graph visualization library built with web workers and jQuery.
  • jLabel - A jQuery Label plugin by William Duffy
    jLabel is a jQuery plugin that formats text input fields with unobtrusive labels featuring interactive suggestions. This allows input fields to be labelled clearly and presented with minimal interface obstruction.
  • CSS Reset.com - CSS Resets and Free CSS Tutorials
    All the most common CSS Reset scripts in one place, with complete documentation, guides and tutorials.
  • jRating : Ajaxed star rating system with jQuery
    jRating is a very flexible jQuery plugin for quickly creating an Ajaxed star rating system. It is possible to configure every detail from" the number of the stars" to "if the stars can represent decimals or not".
  • CLR Profiler for .NET Framework 4
    The CLR Profiler allows developers to see the allocation profile of their managed applications.
  • Silverlight 4 Application Themes
    4 new application themes for Silverlight 4: JetPack, Accent Color, Windows 7 and Cosmopolitan. These themes can be used for the navigation template provided by the Silverlight 4 Tools installer or using the various resource dictionaries provided in this d
  • JustMock Free Edition
    JustMock Free Edition is a developer productivity tool designed to make it easy to create mock objects. JustMock Free Edition cuts your development time and helps you create better unit tests without requiring you to change your code.
  • Microsoft All-In-One Code Framework
    The Microsoft All-In-One Code Framework is a free, centralized code sample library provided by the Microsoft Community team. Our goal is to provide typical code samples for all Microsoft development technologies.
  • Rocket SVN for Microsoft Visual Studio: Subversion add-in for VS 2008/2010
    OnTime integration, no svn:ignore patterns, as easy to install as it is to use, keyboard friendly, and no more relying on TortoiseSVN. All these features come together in RocketSVN for Visual Studio. Not to mention it's 100% Free for Unlimited Users!
  • AppHarbor
    We’re building af Git-enabled .NET Platform-as-a-Service. That means we’ll build, deploy and host your .NET websites for you. To get started all you have to do is to create an account and git push your code to AppHarbor.
  • Elevate
    Elevate is an easy to pick up library containing things you wish were in the BCL. Use one component or many. Contribute your own utilities. Share your ideas with the community.
  • HTML5Labs - Home
    The HTML5 Labs site is the place where Microsoft prototypes early and unstable web standard specifications from standards bodies such as the W3C.
  • Whisper Systems
    Welcome to the public beta of the Whisper Systems mobile security suite for Android. We have two applications in the initial beta, RedPhone and TextSecure, which help restore your ability to conduct your personal and business communications privately.
  • EasyHttp
    After writing smaller wrappers around WebRequest on a few occasions, I decided it’s time to formalize the wrapper. This has given way to EasyHttp.
  • AnjLab Sql Profiler
    SQL Server Express Edition Profiler provides the most of functionality standard profiler does, such as choosing events to profile, setting filters, etc. By now there are no analogue free tools.
  • PusherDotnet
    An implementation of the Pusher REST API in C#.
  • Fizzler
    A .NET library to select items from a node tree based on a CSS selector. The default implementation is based on HTMLAgilityPack and selects from HTML documents.
  • Jurassic - A Javascript Compiler for .NET
    Jurassic is an implementation of the ECMAScript language and runtime. It aims to provide the best performing and most standards-compliant implementation of JavaScript for .NET.
  • Coroutine
    Coroutine makes writing asynchronous code in C# as easy and natural as writing synchronous code.
  • Kayak, a C# HTTP server.
    Kayak is an asynchronous HTTP server written in C#. It has been designed to be easy to embed into a variety of applications. Kayak natively supports the OWIN 1.0 Draft specification.
  • ReactiveUI
    This library is an exploration I've been working on for several weeks on combining WPF Model-View-ViewModel paradigm with the Reactive Extensions for .NET (Rx).
  • Nancy
    Nancy is a lightweight web framework for the .Net platform, inspired by Sinatra. Nancy aims to deliver a low ceremony approach to building light, fast web applications.
  • OWIN — Open Web Interface for .NET
    OWIN defines a standard interface between .NET web servers and web applications.
  • grumpydev/TinyIoC - GitHub
    Welcome to TinyIoC - an easy to use, hassle free, Inversion of Control Container. TinyIoC has been designed to fulfil a single key requirement - to lower the "level of entry" for using an IoC container; both for small projects, and developers who are new
  • Encog Java and DotNet Neural Network Framework | Heaton Research
    Encog is an advanced neural network and machine learning framework. Encog contains classes to create a wide variety of networks, as well as support classes to normalize and process data for these neural networks.
  • Grammarly - English grammar checker, proofreader
    Grammarly is an automated proofreader and your personal grammar coach. Check your writing for grammar, punctuation, style and much more.
  • SeeNowDo :: Digital Taskboards for Distributed Agile Teams
    SeeNowDo is a simple, flexible and free taskboard designed specifically to meet the needs of distributed Agile teams.
  • Pivotal Tracker - Simple, Effective Agile Project Management
    Collaborative, lightweight project management tool, brought to you by the experts in agile software development.
  • Banana Scrum - scrum tool for agile teams
    Banana Scrum is a very simple Scrum tool. Designed to help your team keep track of things, but never meant to replace your daily human interactions. A tool to know where you are, but not so complex as to blurr the picture.
  • Kanbanize.com
    Kanbanize.com is a free web-based software tool that modernizes and builds on top of the well-known from Toyota's factories visualization method - kanban.
  • Scrumy
    Scrumy is a project management tool loosely based off of Scrum.
  • Semantic Versioning
    I call this system "Semantic Versioning." Under this scheme, version numbers and the way they change convey meaning about the underlying code and what has been modified from one version to the next.
  • PowerDbg - Automated Debugging using WinDbg and PowerShell
    PowerDbg is a PowerShell library that enables you to easily create PowerShell scripts to automate a WinDbg / CDB debugging session. You can use PowerDbg for Kernel Mode or User Mode, Post-Mortem debugging or Live Debugging and for native or managed code.
  • Google Public Policy Blog: Keep your opt-outs
    Today we’re making available Keep My Opt-Outs, which enables you to opt out permanently from ad tracking cookies. It’s available as an extension for download in Chrome.

Tags:

Random

Upgrading through every version of windows

by Alex Meyer-Gleaves 7 March 2011 - 12:08 AM

This is a great video showing upgrades of all major Windows versions from 1 through to 7. In fact, the whole process starts with the installation of MS-DOS 5.0 before moving onto Windows. Monkey Island and Doom 2 are installed in MS-DOS to test the backwards compatibility of Windows. The level of legacy support that Microsoft has managed to maintain over such a long period of time is certainly impressive. This has definitely got to be a very heavy burden. You can read more about the whole process on the author’s blog.

Watching this certainly brings back a lot of memories. Looking at the DOS screens I quickly started to reminisce about how much I loved Norton Commander. There was no need to reach for the mouse and everything was just a quick tap of the keyboard away. I remember having to install Trumpet Winsock because Windows 3.0 didn’t support the TCP/IP protocol stack. Gone are the days of the screeching modem and the Gopher session. I never imagined I would have instant access to the internet on a phone that fit snuggly into my pocket. Anyway, that’s enough nostalgia from me, check the video out to bring back your own memories.

Tags:

Random

About the author

Alex Meyer-Gleaves I'm a Technical Architect living in Australia (that island like continent in the southern hemisphere). I love Microsoft .NET and C#. I hate early mornings, slow drivers and Lotus Notes.

Google Shared

 

Month List

Recent Posts

Recent Comments

Comment RSS

Links

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010