Posts

Showing posts with the label code

Applying WebInvoke without an Attribute

Haven't posted in a long time but thought I'd post this bit of WCF extensibility I was working on at home. There is nothing on the Internet about how to do this & I felt I should figure something out. Scenario: You have legacy WCF services that you want to switch to a WebHttpBinding w/ JSON but don't want to update 1,337 service contracts to include a WebInvoke attribute, UriTemplates and Request/Response Body Types In this scenario I'll be assuming use of IIS and Windows Process Activation Services to host your service. The WebInvokeAttribute implements IOperationBehavior. So what we need to do is somewhere in the WCF stack apply this operation behavior programmatically to our Endpoint's Contract.Operations. Let's start from the bottom up & take a look at an extension method that does this. /// <summary> /// Automatically applies the Web Invoke behavior to all operations in the collection /// </summary> /// <param name="operatio...

MapReduce in C# using Task Parallel Library

Back in August I starting playing with a C# implementation of Google's MapReduce algorithm. The implementation was based on something Stephan Brenner did, although I completely refactored it. Today I added a little bit of logic to split up the actual execution of Map & Reduce in this implementation using the Task Parallel Library in .NET 4.0. Check out the source code for MapReduce in C# on GitHub. Below is an excerpt from the Tests on how to implement the library. Counting Words in Files public static List<KeyValuePair<string, int>> Map(FileInfo document, string text) { var items = text.Split('\n', ' ', '.', ',','\r'); return items.Select(item => new KeyValuePair<string, int>(item, 1)).ToList(); } public static List<int> Reduce(string word, List<int> wordCounts) { if (wordCounts == null) return null; var result = new List<int> { 0 }; foreach (var value in wordC...

Require comment / message on all SVN commits for Visual SVN Server

(I've been posting a lot the last few days!) Something that drives me nuts is not having a comment or message when looking at SVN history. It's impossible to know what went on. Even a bad comment is better than no comment. SVN hooks are a great way to solve this. If we make a pre-commit.bat file that checks the commit data for a comment, returns an error code of 1 if it wasn't found (with some text) or returns 0 if the comment is there. Check out the pre-commit hook that I found online (thanks, Anuj Gakhar!) or check out the hook below. @echo off setlocal rem Subversion sends through the path to the repository and transaction id set REPOS=%1 set TXN=%2 rem check for an empty log message svnlook log %REPOS% -t %TXN% | findstr . > nul if %errorlevel% gtr 0 (goto err) else exit 0 :err echo. 1>&2 echo A log message or comment is required to commit 1>&2 exit 1 This works perfectly except for 1 downfall -- you have to distribute it in every freaking reposito...

Using ref Keyword with Reference Types in C#

One of our developers was using the ref keyword in a method that needed to replace the value of a property of the method's parameter. In other words... public class Person { public int ID { get; set; } public string Name { get; set; } public string Email { get; set; } } public static class ReferenceExample { public static void Main() { var person = new Person { Name = "Mark", Email = "none@none.com", }; Save(ref person); Console.WriteLine(person.ID); Console.ReadLine(); } public static void Save(ref Person person) { person.ID = 1; // Pretend this saves to a database or something } } The thinking is correct. Person needs to be passed by reference. So why not use the ref keyword, right? Well...Person is already a reference type . So if we are just replacing properties, we don't need the ref keyword. Removing it changes nothing with our code. T...

Service Cloud - dynamic calls to a cloud of WCF services

Image
For awhile, myself and another developer have been trying to build a working prototype of an idea he proposed for a Service Cloud. Essentially the Service Cloud is a collection of WCF services hosted on a number of servers and environments that can all communicate with one another via a common interface. An "application" would then be built by orchestrating these services together. Instead of the application adding service references for each of the services it needs -- it would simply send a request to the "Gateway" service and it would figure out the rest. It would call the other services. Finally, when the execution is complete and your request has bounced all over the cloud, you get a response that many services have built together. I finally was able to create a working prototype (albeit completely contrived). The Service Cloud prototype is available on GitHub, see: http://github.com/xeb/ServiceCloud . Client The client is simple. The client adds a WCF Se...

TwoRingBinder - a Custom ASP.NET MVC Model Binder

I haven't posted in a few months. Been busy at work and starting playing WoW (I know -- its awful but its fun). But a few weeks ago I made a Custom ModelBinder -- called TwoRingBinder -- for ASP.NET MVC. Ok, it's not an implementation but rather a class inheriting from DataAnnotationsModelBinder that allows for easier custom Binding methods. I put it on github but will explain how to use it below. Download or check out the meat of the code. Essentially, TwoRingBinder allows you to write Binding Extensions instead of writing your own Custom Model Binder every time you want to do something tricky or different with Model Binding. Example: We have a model called SignUp . SignUp has FirstName, LastName, Origin, IsFemale and FromRoot properties. Only the FirstName and LastName properties will be bound from a form via a ValueProvider; however, we need IsFemale to have a value (assume for a service of some type). Now, we don't want a checkbox on the site for people to se...

ASP.NET MVC and MSBuild via Command-Line

I struggled with this one for a couple hours & wanted to post some help. I'm trying to move towards better deployment processes. I'd like to use TeamCity but until then, command-line will do. It's how I roll anyways. When I first ran MSBuild on my ASP.NET MVC CSPROJ file I got the following error: C:\Projects\MvcApplication.WebUI>msbuild /p:Configuration=Debug MvcApplication.csproj Microsoft (R) Build Engine Version 2.0.50727.3053 [Microsoft .NET Framework, Version 2.0.50727.3603] Copyright (C) Microsoft Corporation 2005. All rights reserved. Build started 5/18/2010 9:27:29 PM. __________________________________________________ Project "C:\Projects\MvcApplication.WebUI\MvcApplication.csproj" (default targets): Target ResolveProjectReferences: C:\Projects\Assembly.csproj(200,11): error MSB4019: The imported project "C:\Microsoft .CSharp.targets" was not found. Confirm that the path in the declaration is correct, and that the file exists on...

Why TradingBlox is so Awesome

TradingBlox is a relatively expensive piece of software that you've (probably) never heard of. You may never use it. But I still think you should know about it. I've been passionate about the financial markets for years. Later I'll explain this month why you should at least know something about them. I had the pleasure of working at Carmichael and Company LLC and learned a great deal about trading from Ralph Carmichael. It excited a passion in me. This passion was fueled by books like: Market Wizards, Reminisces of a Stock Operator and The Way of the Turtle. Also this little PDF about the original Turtle trading rules really helped. After trying to program my own recreation of the Turtle rules, I stumbled upon TradingBox. It did everything I wanted and more. It has an amazing community. It supports trading & optimizing multiple markets with the same system (which was a pain -- if not impossible -- using TradeStation). TradingBlox lets you program trading r...

Spark - Optional Parameters in Partials

While on the topic of the Spark View Engine , there is an easy way to make a parameter of a partial optional so you don't always need to pass a value when calling the partial. Simply define the variable as part of the viewdata property. <!-- samplePartial.spark --> <viewdata optionalParameter="string" /> <a class="active?{optionalParameter == "home"}">Home</a> That's it. Now you can call the partial by itself... <samplePartial /> ... or with the optionalParameter ... <samplePartial optionalParameter="home" /> A helpful trick that I couldn't find a lot about online.

Spark - Recursive rendering of partial files not possible (but it is!)

We've been using the Spark View Engine a lot at work. I absolutely love it. Our front end developers love it (they don't need to re-learn something like we had to for NHaml ) and if they don't want to use Spark's features, standard HTML works without problems. During one project, I was making some contextual menus. I wanted to call a Spark partial recursively in order to not repeat myself & keep things flexible for the future. Unfortunately Spark specifically disallows this. If you try it, you will get an Exception that states "Recursive rendering of partial files not possible" . Well that just sucks. I understand the limitation in the View Engine itself but there is a way around it. Not super elegant but definitely functional without sacrificing anything other than style . I posted the following example in the Spark project itself. The trick is using the HtmlHelper 's RenderPartial method. Let's say we have a partial called: navigation...

TrustButVerify - simple jQuery validation powered by LiveValidation

I really like the way LiveValidation runs; however, I REALLY LOVE jQuery selectors & chaining. Unfortunately the LiveValidation approach to validation doesn't feel right when looking at a lot of field-specific validators surrounded by super terse jQuery syntax. So I decided to make a small 79-line wrapper-type of plugin that is powered by LiveValidation but comes with all the power of jQuery's selectors, chaining and... well, jQuery. I called the plugin, TrustButVerify . Check it out & let me know your thoughts or if there is room for improvement (which there definitely is). I have NOT exposed all of the LiveValidation methods; just the ones I found useful & necessary :-p Here's a sample of some validation: $(document).ready(function(){ $('#form .required').required(); $('#email').validEmail(); $('#zip').matches(/^\d{5}$/); $('input.address').required().validate(someCustomFunction, 'your address is out of our area ...

Convert SQL types in destination to SQL type in source

Another little script I needed for today. Feel free to expand on the CASE statement for your own types (which I will do should I need to run this again). /* Will transform destination table's column types to match the source database's (when column names match) codesnippet:83d07e82-3866-4877-849f-0ae06322b9fb */ declare @destination varchar(50) declare @source varchar(50) ---- Configuration ----- set @destination = 'PlanImport' set @source = 'Plan' ------------------------ declare @i int declare @count int declare @sql varchar(8000) declare @columnName varchar(8000) declare @columnType varchar(8000) declare @columns table (id int identity(1,1), columnName varchar(50), columnType varchar(50) ) -- insert source columns that are in destination insert into @columns select source.[Name], (CASE source_types.[Name] WHEN 'decimal' THEN source_types.[Name] + '(' + cast(source.[precision] as varchar(50)) + ',' + cast(source.[scale] as varc...

Convert literal SQL 'NULL' to real NULL

Pretty straight forward. Had to do this today & thought I'd share the solution I came up with. /* Will turn literal "NULL" into SQL NULL in any table (for all columns) codesnippet:25616582-ced6-4e59-ab4c-25d2128cc4b6 */ declare @tableName varchar(50) ---- Configuration ----- set @tableName = 'PlanImport' ------------------------ declare @i int declare @count int declare @sql varchar(8000) declare @columnName varchar(8000) declare @columns table (id int identity(1,1), columnName varchar(50)) insert into @columns select [Name] from sys.columns where object_id = object_id(@tableName) and system_type_id in (select system_type_id from sys.types where [name] like '%varchar%' or [name] like '%text%' ) set @i = 1 set @count = (select max(id) from @columns) while(@i begin set @columnName = (SELECT [columnName] FROM @columns WHERE [ID] = @i) set @sql = 'UPDATE [' + @tableName + '] SET [' + @columnName + '] = NULL WHERE [' + @...

Fluent NHibernate - Incorrect syntax near the keyword 'Group'

I have to share this. I spent a good amount of time searching around Fluent NHibernate for a way to escape columns in the generated SQL while still using AutoMapping. My initial configuration looked like: Fluently.Configure() .Database(MsSqlConfiguration.MsSql2005.ConnectionString( c => c.Is(ConfigurationManager.ConnectionStrings["Something"].ConnectionString))) .Mappings(x => x.AutoMappings.Add(AutoPersistenceModel.MapEntitiesFromAssemblyOf () .WithSetup(convention => { convention.FindIdentity = p => p.Name == p.DeclaringType.Name + "Id"; convention.GetComponentColumnPrefix = type => type.Name + "Id"; } ) .BuildSessionFactory() This works great, but I had a property in my class (SomeType) that is called Group. This was causing the SqlException: Incorrect syntax near the keyword 'Group' (others would be like: Incorrect syntax near the keyword 'User' or Incorrect syntax near the keyword ...

Strongly typed AppSettings with defaults

Very often I want configurable options for miscellaneous settings; but I hate to shift my focus from the code I'm working on to add a new AppSetting. Sometimes these settings are essential but more often than they are just options that I may need. So the solution I like to use is to make default values for such AppSettings. If the service you are writing needs to retry a database or web service call a few times, why not make that option configurable but use a default of 5. The method below will grab an AppSetting & try to convert it. If it fails, it uses the default. Plus the generic T can be a value or reference type. public static T GetAppSetting<T>(string key, T defaultValue) { if (String.IsNullOrEmpty(ConfigurationManager.AppSettings[key])) return defaultValue; try { return (T)Convert.ChangeType(ConfigurationManager.AppSettings[key], typeof(T)); } catch { } return defaultValue; } // Sample Usage public void DoSomething() { if(GetAppSetting("Shou...

Stream was not readable

TL;DR - flush & reset, see: [Fact] public void BaseStream_Is_Not_Empty() { MemoryStream stream = new MemoryStream(); LogWriter logWriter = new LogWriter(stream); logWriter.WriteLine(new[] { DateTime.Now.ToString("yyyy-MM-dd"), "Log data" }); logWriter.BaseStream.AutoFlush = true; stream.Seek(0, SeekOrigin.Begin); using (StreamReader sr = new StreamReader(stream)) { Assert.NotEmpty(sr.ReadToEnd()); } } I recently started writing some tests (in xUnit using Moq + StructureMap) for a service that calls a class -- let's call it LogWriter -- that simply writes formatted logging data to a Stream. After creating an interface for the logging class, ILogWriter, I wanted to write some tests on LogWriter to see if it was working as expected (before testing out my service which depends on ILogWriter). After the ILogWriter was done, I used StreamReader to check out it's input. The Stream I told it to write to was a MemoryStream (this is unit testin...

Fluent NHibernate + Encrypting Values

I recently created two CLR User Defined Functions for SQL Server 2005 (written in C#) to decrypt & encrypt a given string (based on a hard-coded key). select dbo.EncryptString('Testing') -- Returns: Fjfds243qcm43fsdj2343== select dbo.DecryptString('Fjfds243qcm43fsdj2343==') -- Returns: Testing Pretty simple stuff. This will allow the user with enough access to pull encrypted data out of the database and provide the ability to restrict decryption to other SQL users. Now to implement this in code... Because it's awesome, Fluent NHibernate has a method called FormulasIs that assists in building out values using SQL. public class User { public virtual int Id { get; set; } public virtual DateTime DateOfBirth { get; set; } } public sealed class UserMap : ClassMap { public UserMap() { WithTable("dbo.[User]"); Id(x => x.Id, "[ID]"); Map(x => x.DateOfBirth, "DOB").FormulaIs("dbo.DecryptString(DOB)"); ...

Simple ASP.NET Localization

Image
I've seen a lot of solutions for localization in ASP.NET -- many of which use a database to store the localized content. The problem with this approach is that you have to recreate the tools that you are already using. Specifically: text editors (now you need an admin site to update the database content), source control (now you need revision history), content uploading (now you need an SSIS or custom Windows Service to deploy content). It's a bigger project than you want. Generally, whenever HTML goes into a database (apart from a Forum), I question the need. The reason being that HTML is code and code belongs in Source Control. If Developers are the only ones updating the content (we're not talking about CMSs here) then why force them to use tools they aren't familiar with to do the same job they do all day long? A solution that I've found that works well is to use an HTTP Module and a Localized directory of files. First, let's go over the HTTP Module. ...

Unsvn - a way to un-checkout an svn repository

Sometimes other developers push up .svn directories to production. This drives me nuts. Not only does it create clutter but the directory contains sensitive information about where your SVN repository is located and who the user is. Removing these directories is a pain to do manually, so why bother? The C# code below will remove all .svn directories & all the files beneath them for any given path. See the source below or just download the Windows Binary . using System; using System.IO; namespace UnSvn { class Program { static void Main(string[] args) { if (args == null || args.Length != 1) { Usage(); return; } DirectoryInfo root = new DirectoryInfo(args[0]); try { if(!Process(root)) { Console.WriteLine("Nothing to do"); } } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); } } static void Usage() { Console.WriteLine("usage: unsvn [/path/to/direct...

Syntax Highlighting in Blogger -- with jQuery & SyntaxHighlighter

There are a few reasons I decided to go with Blogger over other blogging options. 1) I want to spend time writing not setting things up, 2) BlogEngine.NET didn't seem to look right no matter what theme I used and I didn't like the admin and 3) Wordpress is all MySQL. That being said I wanted to get SyntaxHighlighter working. After reading Guogang Hu's post about how to get it working (& not likely a lot of code), I decided to do it with jQuery. The real issue with SyntaxHighligher and Blogger is the line breaks. Posts have line breaks replaced by <br /> tags -- which SyntaxHighlighter will faithful display. Using the replaceWith method in jQuery makes this a snap. Check out the code below. <link href='/syntaxhighlighter/styles/SyntaxHighlighter.css' rel='stylesheet' type='text/css'/> <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js' type='text/javascript'></script> <sc...