Archive for the ‘C#’ Category

Saturday, June 21st, 2014

C# is a wonderful language, with a rich eco system – unapologetically build your startup technology in .NET

.NET Logo

One thing I’ve noticed is very rarely do startups build on the .NET stack. I’ve been lucky to be a part of many startups that have used the Microsoft stack to quickly and cheaply (yes, cheaply <pause for comedic effect> on the Microsoft stack) get stuff done. This is a shame because people are missing out on a powerful option for their startup.

It’s understandable why so many startups are build on the OSS stack. The tools are plentiful and always free to download. The languages are fun. I’ve dabbled with Python. I’ve build Ruby on Rail prototypes. They’re fine tools. This isn’t an attempt to peel people away from the OSS stack, far from it. I want to expose what Microsoft and the community around .NET has to offer for a startup.

.NET is cheap

Yes, it’s cheap to get started with C# in your startup. I feel Microsoft has a reputation (admittedly a deserved reputation) for being expensive and this is the number one reason as to why startups don’t give Microsoft a chance. In reality Microsoft doesn’t want your money until you can afford to give it to them.

By Steve Evans from Citizen of the World (Piggy Bank Uploaded by russavia) CC-BY-2.0 via Wikimedia Commons

  • Visual Studio Express & SQL Server Express

    The first stage of your startup project will be some form of MVP. Before you even commit to doing a startup you can get started creating a prototype/MVP with Visual Studio Express. VS Express is simply a free version of Visual Studio. And Visual Studio is hands down the best IDE/debugger I’ve ever used. If there is one positive thing I’ve heard my OSS friends say about C# is that they wish they could use Visual Studio.

    There are a few features missing from VS Express. Most of the missing features won’t become a pain until you grow out your team, and grow out the code base. If upgrading to a newer version of VS makes sense for the current state of your startup the feel free to upgrade, the code you create with Express is compatible.

    If you require a database Microsoft also has a free version of SQL Server. There is also nothing preventing you from using MySQL, PostgreSQL, or really any RDMS with your C# project.

  • Azure

    Azure is Microsoft’s cloud offering and it’s really good. Getting started is easy, and it makes the licensing costs reasonable. Personally I even do my development inside an Azure VM. With any sort of MSDN subscription there is $150 monthly credit for using Azure. Again there is also nothing stopping you from using another cloud provider, like Amazon, with your .NET projects. Things are just a little bit easier if you go with Azure.

  • Bizspark

    Simply put, Bizspark is amazing. Free access to Microsoft tools for 3 years for startups. Bizspark isn’t as well known as it should be. Microsoft will also help promote and support your startup when you are in the Bizspark program. This Bizspark program also gives you an MSDN license so you can use the aforementioned Azure credit.

.NET is Popular (outside the startup world)

C# in particular is a very popular language in the professional world. Popularity matters because it’ll be easier to find developers fluent in the language, and rarely will you be blazing a completely new trail.

By Fire_breathing_2_Luc_Viatour.jpg: Luc Viatour derivative work: Amada44  talk to me (Fire_breathing_2_Luc_Viatour.jpg) CC-BY-SA-2.5-2.0-1.0, CC-BY-SA-3.0 or GFDL, via Wikimedia Commons

The more popular the language that the code is written in, the easier it is to find people to work in that language. You’ll be able to find the person with the skill set in the right level for what you need. Have some entry level work? Since it’s a popular language there are people itching to get experience in C#. Have some hard core problems? Since it’s a popular language there are people with 10+ years experience in C#.

A popular language/toolset has a plethora of people who are dealing with the same issues as you are, and people who solved them. The library support for .NET is amazing and getting better every day. Sure writing an OFX parser in Rust is fun, but wouldn’t it be better for your business to just download a library and get more important stuff done?


Yes, you should not pick a language/toolset solely on the promise of it easily scaling to bazillions of users. However all other things being equal wouldn’t you prefer a solution that doesn’t require architecture acrobatics after your first big burst of success? I’m being slightly facetious. The fact is Microsoft’s done a lot of the hard tuning work and put it right into the CLR.

Turning Torso 3 by Väsk - Own work. Licensed under CC BY-SA 3.0 via Wikimedia Commons

Turning Torso 3 by VäskOwn work. Licensed under CC BY-SA 3.0 via Wikimedia Commons

It’s been my experience that out of the box .NET code has the ability to scale far enough for most startups that performance becomes a non-issue, particularly at the early stages. This is just another thing to not think about as you are growing your company. Currently at eMoney advisor there are 2 middle of the road servers that can process millions of transactions a day. All the code for the processing is written in C#.

The .NET languages, and in particular C# also have design decisions built into the language that enable the CLR to do some pretty fantastic optimizations.


Another argument I’ve heard against the .NET stack is people fear vendor lock-in. I’ll concede that this was an issue a decade or 2 ago. Today Microsoft plays much more nicely with other tools/platforms. Microsoft is even moving in the direction to be more open.

She left the door open by Hartwig HKD. Licensed under CC BY-ND 2.0

She left the door open by Hartwig HKD. Licensed under CC BY-ND 2.0 via Flickr

Go look at Github and CodePlex to see how many open source C# project there are. The projects are not only open, there are a lot of good open source projects.

Microsoft also has a whole "open center". The center is dedicated to showcasing Microsoft’s community efforts. If that’s still not open enough for you, there is also Mono that let’s you run .NET applications on Linux and Mac machines.

Microsoft’s made great strides in providing a robust, fun, popular community around it’s technology. More people in the startup world should embrace it.

Agree? Disagree? Drop me an email blog [at] sirchristian [dot] net or message me on twitter @sirchristian

Monday, October 21st, 2013

If you ever need to encode an integer into base64 AND you control both ends of the conversion (such as wanting to use an integer for your own URL shortener). Here is a method for how to how you can tweak base64 conversions to get rid of the trailing equal signs (padding) and leading zeros (this will make the resulting string smaller).

public static string IntToCustomBase64String(int i)
	// Get the bytes from the int (will be an array of 4 bytes) 
	byte[] b = BitConverter.GetBytes(i);

	// Remove any leading 0s from the byte array
	int idx = b.Length - 1;
	while (b[idx] == 0)

	// Construct smaller byte array to copy items into
	byte[] new_b = new byte[idx + 1];
	Array.Copy(b, new_b, idx + 1);

	// return the new array
		.Replace("/", "!") // Make the string url safe
		.TrimEnd('='); // trim the padding. We know the # of bytes, 
		               // and we control conversion so this is okay

public static int CustomBase64ToInt(string customBase64EncodedString)
	// Add back the padding
	string s = customBase64EncodedString;
	if (s.Length == 2 || s.Length == 6)
		s += "==";
	else if (s.Length == 3)
		s += "=";

	// Get the bytes
	byte[] b = Convert.FromBase64String(s.Replace("!", "/"));

	// We need to add back any zero's we stripped to make this a 4 byte array
	// so it is a valid integer format
	byte[] new_b = new byte[] {0, 0, 0, 0};
	Array.Copy(b, new_b, b.Length);
	return BitConverter.ToInt32(new_b, 0);

Similar amount of bit fiddling could be down with any .NET type as long as you understand the bit structure of the type, and how you are transforming it.

Wednesday, July 17th, 2013

Clockwork (stock photo by xtrapink)

This picks up with the code generation series. This is planned to be the last post in this mini series. See past posts:

This post will go over some basics using the CodeDom. The code samples used in this post come from a project I wrote that allowed me to copy/paste parts of a customer spec and generate classes that could be used for serialization.

CodeDom is flexible enough for a wide spectrum of code generation needs. As with all things, the power that comes with that generating code with CodeDom is balanced by the complexity of using CodeDom.

Let’s dive right into some code:

// Generate the container unit
CodeCompileUnit program = new CodeCompileUnit();

// Generate the namespace
CodeNamespace ns = new CodeNamespace("Net.Sirchristian");

// Add the required imports
ns.Imports.Add(new CodeNamespaceImport("System"));
ns.Imports.Add(new CodeNamespaceImport("System.Xml.Serialization"));

CodeDom works off of CodeCompileUnits. A CodeCompileUnit can be thought of as a file to be generated. Every file to be generated will construct a CodeCompileUnit. CodeNamespace is equivalent to a namespace block in C#.

namespace Net.Sirchristian { }

To the namespace we add CodeNamespaceImport which are the ‘using’ statements.

namespace Net.Sirchristian 
    using System;
    using System.Xml.Serialization;

So far fairly straight forward. Pretty much a one -> one CodeDom object to code structure. One thing to note is we have not yet added anything to our CodeCompileUnit. We have to fully construct the objects that will go inside the CodeCompileUnit then we can add namespace to it. This is true with any container object when using CodeDom. The children must be fully populated before getting put into the container. Next we will generate our class container.

// Declare the class
CodeTypeDeclaration recordClass = new CodeTypeDeclaration()
    Name = "Record", 
    IsClass = true

A class is represented by a CodeTypeDeclaration. A CodeTypeDeclaration can be any user definable types allowed by the CLR, currently that means class, interface, enum, struct, or delegate (although to generate a delegate you have to use CodeTypeDelegate which inherits from CodeTypeDeclaration). Now we have to generate objects to add to the class.

string anyString = "property of chris";

// Make a nice property name by making it title case, and no spaces
string propertyName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(anyString.ToLower());
propertyName = Regex.Replace(propertyName, @"\W|\s", "");

// Make the private file starting with 2 underscores and an all lower name
string privateFieldName = "__" + propertyName.ToLower();

// Generate the private field
CodeMemberField field = new CodeMemberField()
	Name = privateFieldName,
	Type = new CodeTypeReference(typeof(string)),
	Attributes = MemberAttributes.Private

// Generate the property
CodeMemberProperty property = new CodeMemberProperty()
	Name = propertyName,
	Type = new CodeTypeReference(typeof(string)),
	Attributes = MemberAttributes.Public | MemberAttributes.Final,
	HasGet = true,
	HasSet = true

// Add the return field statement to the property
property.GetStatements.Add(new CodeMethodReturnStatement(
	new CodeFieldReferenceExpression(
		new CodeThisReferenceExpression(), privateFieldName)));

// Add the set field to value to the property
	new CodeAssignStatement(
		new CodeFieldReferenceExpression(
			new CodeThisReferenceExpression(), privateFieldName),
		new CodePropertySetValueReferenceExpression()));

// Add a comment
string comment = "Remember children: ALWAYS COMMENT YOUR CODE.";
property.Comments.Add(new CodeCommentStatement(comment, true));

// Add the XmlElement Attribute
CodeAttributeDeclaration attribute = new CodeAttributeDeclaration(
	new CodeTypeReference(typeof(XmlElementAttribute)),
		new CodeAttributeArgument("Type", new CodeTypeOfExpression(typeof(string))),
		new CodeAttributeArgument("ElementName", new CodePrimitiveExpression(propertyName)),
		new CodeAttributeArgument("Namespace", new CodePrimitiveExpression("")))

What the above code does is add a public property with a getter and setter that will get and set the private field. The public property is decorated with an XmlElement attribute. This is where you can start to notice some of the power/flexibility trade offs of using CodeDom. Conceptually we will be building out something that looks like.

// Remember children: ALWAYS COMMENT YOUR CODE.
public string PropertyOfChris
        return this.__propertyofchris;
        this.__propertyofchris = value;
private string __propertyofchris;

To generate that we use the following objects from CodeDom:

I won’t go over all the objects in details, but I want to illustrate that everything that needs to be generated will have an object associated with it. To see more of the CodeDom objects look at the CodeDom namespace on MDSN.

There are patterns on how the CodeDom object model is structured. Mostly this can be inferred by the object name. There are CodeObjects , CodeExpressions, CodeStatements, all of which need to be combined just like you would need to type out tokens when editing a source file. The big benefit to CodeDom is that once the structures are built out with CodeDom objects it is easy to add additional logic around them. This is the flexibility of CodeDom.

So we’ve pretty much constructed all the objects we need to have the code generated for us, the last step is to add the constructed CodeDom objects to the appropriate parent objects.

// add property to the class

// add the field to the cass

// Add record class to the namespace


We finally added the members to the class, the class to the namespace, and the namespace to the CodeCompileUnit. We have a whole source file finally constructed. The last step is to render the CodeCompileUnit into a C# source file. We do that by created a CodeProvider. Specifically a CSharpCodeProvider (although as long as the CodeDom objects don’t contain any C# specific features all the C# code used above could generate a VB file just by changing CSharpCodeProvider to a VBCodeProvider).

using (var outFile = File.Open("out.cs", FileMode.Create))
using (var fileWriter = new StreamWriter(outFile))
using (var indentedTextWriter = new IndentedTextWriter(fileWriter, "    "))
	// Generate source code using the code provider.
	var provider = new Microsoft.CSharp.CSharpCodeProvider();
		new CodeGeneratorOptions() { BracingStyle = "C" });

One more cool thing…creating an assembly at runtime!

Another cool thing about CodeDom is that an Assembly can actually be compiled and used at runtime.

// Build the parameters for compilation
CompilerParameters cp = new CompilerParameters();

// Add references

// Save the assembly in memory
cp.GenerateInMemory = true;

// Invoke compilation.
CompilerResults cr = provider.CompileAssemblyFromDom(cp, program);

if (cr.Errors.Count > 0)
    // Build an exception
    ApplicationException exception = new ApplicationException("Error building assembly");
    StringBuilder errorBuilder = new StringBuilder();
    foreach (CompilerError ce in cr.Errors)
        exception.Data.Add(ce.ToString(), ce);

    throw exception;

Assembly assembly = cr.CompiledAssembly;

CompilerParameters and CompilerResults are also part of the CodeDom namespace. Feed the CodeProvider with the CompilerParameters and the CodeCompileUnit and the provider can compile the generated code for you, without even needed to generate code!

This is the last entry I planned for the code generation series. Want more, or have questions, leave a comment, or ping me on twitter @sirchristian.