ServiceStack’s Markdown Razor Engine. Wow.
ServiceStack is a pretty sweet-looking alternative to WCF. It provides strongly-typed, well-designed, REST/RCP+SOAP services for .NET and Mono. Check out the README in the repository to see how ridiculously easy it is to setup a service. Unfortunately, I haven't yet had a chance to use the stack. I was looking through the code today and saw a Markdown-Razor Engine.
I was like, "Wha....?
Yes, they offer an alternative view engine which blends Markdown and Razor. These are my two favorite syntaxes, so I had to see how well it compiles.
I compiled the ServiceStack.RazorEngine from source (in Ubuntu 12.04/Mono, no less!) to test a simple markdown file.
I created this markdown file, example.md, to throw at the framework.
# Example ServiceStack.Markdown
## Showing @examples.Count items
@foreach (var item in examples) {
- @item.Name: @item.Number
}
**Note: The template requires a space after the item.Number value**
For more information, check out
[the docs](http://www.servicestack.net/docs/markdown/markdown-razor).
Also, *don't forget* to check out the code at
[gh:ServiceStack/ServiceStack](https://github.com/ServiceStack/ServiceStack)
Here are some _other_ attempts to **break**
the markdown **generation_of_html**. **escaped\_underscore\_in\_tags**
A space after double-asterisk (<strong> tags) will ** break **
Now, when I say simple, I mean it has most elements of markdown that I use regularly. It also uses the markdown-razor foreach syntax which iterates over a collection of Example objects. This view is not strongly-typed, so this is equivalent to a dynamic Razor view.
The code to compile this view is really simple. You create the template engine, and provide a markdown page object which takes a full path (.e.g /fakepath/Debug) and the template contents (e.g. the above markdown snippet).
// Create the markdown-razor template compiler MarkdownFormat format = new MarkdownFormat(); string contents = File.ReadAllText(template); var page = new MarkdownPage(format, path, "example", contents ); format.AddPage(page);
Then, you create your view object (ViewBag?).
// Create our view container (ViewBag)
var view = new Dictionary<string, object>()
{
{ "examples", examples }
};
All that's left is to pass in the view object and compile it to html!
// Compile and output.
// This can be redirected to html file
// e.g. RazorExample.exe > output.html
var html = format.RenderDynamicPageHtml("example", view);
Console.WriteLine(html);
The Code
As always, the code for this post is available on github. More examples on the Markdown Razor syntax available in ServiceStack are available in the test project in ServiceStack's repository.
Proxy Objects
I started to familiarize myself with proxy objects a couple of years ago when I started used Fluent NHibernate on a pretty large project. NHibernate itself proxies objects to allow the framework to do its magic. Proxies are a fantastic thing. I spoke with a friend of mine today about some advanced coding techniques including proxy objects and IoC, which made me want to write a little about some of those topics.
From Wikipedia:
A proxy, in its most general form, is a class functioning as an interface to something else. The proxy could interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate.
Charles Bretana gave an excellent and succinct definition of proxy objects on Stack Overflow back in 2008:
One purpose is to "pretend" to be the real class so a client component (or object) can "believe" it's talking to the "real" object, but inside the proxy, other stuff, (like logging, transactional support, etc.) is being done at the same time... Secondly, a proxy can be very cheap in comparson to the real object,. and often is used so that the real objects can be conserved (turned off or released to a pool to be used by other clients) when the client is not using them... The proxy stays "alive" and the client thinks it still has a connection to the real object, but whenever it "calls" the object, it is actually calling the proxy, which goes and gets another real object just to handle the call, and then releases the real object when the call is done.
I've created an example (available on github) which demonstrates how to proxy method calls in a few different ways, ranging from very simple to using Castle.DynamicProxy and interceptors. The code is written in C# and although the code doesn't handle some of the more advanced topics of proxy objects, such as resource pooling as Charles described, it will (I hope) introduce proxy objects in a comprehensible way.
Read on for killer examples.
Debug.WriteLine
I answered a question on StackOverflow last week which made me remember a few years ago when I also wondered, "Where does Debug.WriteLine go?!"
The answer is very simple (and no, I'm not peeved that I was the first to answer and didn't get accepted).
If you look at the Debug.WriteLine documentation on MSDN, you will see a ConditionalAttribute:
[ConditionalAttribute("DEBUG")]
public static void WriteLine(
string message
)
This attribute is one of a few* compiler-time attributes. In other words, the compiler looks for this attribute specifically and, if found and the DEBUG condition is met (i.e. 'DEBUG' is defined), THIS METHOD IS NOT COMPILED. That's pretty awesome, but you don't need to take my word for it. I've created a quick example.
Program.cs
Program.cs is a small program with three important pieces: Console.WriteLine, Debug.WriteLine, and a final Console.WriteLine. We have a before and after Console.WriteLine to show that Debug.WriteLine is not compiled into Program.exe when DEBUG is not defined.
using System;
using System.Diagnostics;
class Program {
static void Main(string[] args) {
Console.WriteLine("Console.WriteLine #1");
Debug.WriteLine("Debug.WriteLine");
Console.WriteLine("Console.WriteLine #2");
}
}
To compile normally, run
csc Program.cs
.
To compile with the DEBUG constant defined, run:
csc /define:DEBUG Program.cs
You can run Program.exe after both compiles, but you will see the same output.
The IL
You can use a tool called ildasm to dump the IL code of Program.exe (ildasm is part of the Windows SDK, after installation it can be found at, e.g., C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools).
Just open ildasm, choose File->Open and select Program.exe. Next, choose File->Dump. Choose 'Dump IL Code' and any other options you want.
Here is the output of the main method for both versions of the exe:
Program-NoDefines.il
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 24 (0x18)
.maxstack 8
IL_0000: nop
IL_0001: ldstr "Console.WriteLine #1"
IL_0006: call void [mscorlib]System.Console::WriteLine(string)
IL_000b: nop
IL_000c: ldstr "Console.WriteLine #2"
IL_0011: call void [mscorlib]System.Console::WriteLine(string)
IL_0016: nop
IL_0017: ret
} // end of method Program::Main
Program-DEBUGDefined.il
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 35 (0x23)
.maxstack 8
IL_0000: nop
IL_0001: ldstr "Console.WriteLine #1"
IL_0006: call void [mscorlib]System.Console::WriteLine(string)
IL_000b: nop
IL_000c: ldstr "Debug.WriteLine"
IL_0011: call void [System]System.Diagnostics.Debug::WriteLine(string)
IL_0016: nop
IL_0017: ldstr "Console.WriteLine #2"
IL_001c: call void [mscorlib]System.Console::WriteLine(string)
IL_0021: nop
IL_0022: ret
} // end of method Program::Main
As you can see, Debug.WriteLine is only added to Program.exe when we pass the DEFINE constant! Pretty cool, huh?
* The only other compiler-time attribute I know off-hand is ObsoleteAttribute, which will generate compiler warnings or errors if passing true as a second parameter into the constructor.
ASP.NET, AppDomains, and shadow-copying
I answered a question on StackOverflow nearly two years ago, and I'm surprised at how few votes it has received, despite comments such as:
+1 for teaching me something new today thanks. -kobe
Being one of my favorite answers, I thought I should discuss it on my blog a little more in-depth than just posting the SO answer. I'd like to briefly discuss what ASP.NET really is (in the context of IIS), why AppDomains are needed, and lastly what shadow-copying does for an application. There is no code associated with this post, and it is driven more by contemplation than by a specific resolution to a problem. So, I apologize in advance if it seems disjointed at times.
Allowing only a single instance of a .NET application
In the past, whenever I constrained an application to having only a single instance running at any given time, I naively walked a list of running processes to find a process with the same name as the currently-running process. If it exists, there's another instance, if not I would assume there is no other instance. This was a quick and dirty approach, because I didn't know of any other way. Of course, this would fail if the user renamed the process; total fail.
In CLR via C# by Jeffrey Richter, a much quicker solution is presented (leaving my naive solution to be only dirty). This solution uses a Semaphore to count references to a resource (the application) as it will be managed by the operating system.
Here is a simple console application to display how this would work:
class Program
{
const string Id = "af49d266-e4f4-4a63-b73c-f62c1144b584";
static void Main(string[] args)
{
bool thisInstance;
using (var semaphore = new Semaphore(0, 1, Id, out thisInstance))
{
if (thisInstance)
{
Console.WriteLine("This is the first instance!");
Console.ReadLine();
}
else
{
Console.WriteLine("There is another instance running.");
Console.ReadLine();
}
}
}
}
A semaphore is designed to limit access to a given resource. If you read the Wikipedia - Semaphore article, you'll see that a semaphore is described as a librarian handing out passes to study rooms. The librarian doesn't care who is in which room, only whether there are rooms available. There could be 10 rooms, there could be 100. In this single application example, we have 1 available resource which is the application identified by a constant Guid - "af49d266-e4f4-4a63-b73c-f62c1144b584". Because the operating system will use this string to uniquely identify our application, I've chosen a Guid over something simple like "MySemaphore" because the chances of a Guid being duplicated are theoretically nil.
Using this Semaphore constructor:
public Semaphore( int initialCount, int maximumCount, string name, out bool createdNew )
we can create a binary semaphore.
A binary semaphore allows us to have an on/off switch for running our application -- is the resource available or not? When we have 1 resource available, and the first application starts up, it decrements the count of available resources to 0. If this decrement occurs, the createdNew out parameter will be true. On the other hand, if an application starts up and the semaphore's available resource count is 0, createdNew will be false.
Notice in the code above that Console.ReadLine() is used in each block of the if statement to block execution. Why is this not located at the end of the Main method?
It's because Semaphore is a type derived from WaitHandle. WaitHandle implements the IDisposable interface, which is why the Semaphore is wrapped in a using block. When the code exits this using block, semaphore.Dispose() executes semaphore.Close() and the currently-held resource is released. This increments the available resources back to the maximum value of 1. In a real application, the first block would call the Application's Run() method and the else block would either display a message, terminate silently, or switch to the first process.
It is also possible to have any subsequent processes wait for the semaphore to release its lock on the resource. This would be accomplished by calling semaphore.WaitOne() in the else block:
class Program
{
const string Id = "af49d266-e4f4-4a63-b73c-f62c1144b584";
static void Main(string[] args)
{
bool thisInstance;
using (var semaphore = new Semaphore(0, 1, Id, out thisInstance))
{
if (thisInstance)
{
Console.WriteLine("This is the first instance!");
Console.ReadLine();
// Release resource
semaphore.Release();
}
else
{
Console.WriteLine("There is another instance running.");
// Wait for resource
semaphore.WaitOne();
Console.WriteLine("There is now the only instance.");
Console.ReadLine();
}
}
}
}
Wait a second. Didn't I say that wrapping the Semaphore object in a using block would call Close()? Why did I have to explicitly call semaphore.Release()?
The answer to this is Garbage Collection. Sure, Close() will be called (and thus, Release() is called and signals all waiting threads that the resource is available) when the using block exits, but this will only happen when the object is disposed. If you plan to queue up applications (or windows, dialogs, or any other resource), note this signaling behavior.
Code
I've decided to start making code from my blog posts available from a single github repository.
https://github.com/jimschubert/blogs
References
C++ Global _CRT_SECURE_NO_WARNINGS
I became extremely annoyed by thousands of these messages while running MSBuild:
c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\string.h(105) : see declaration of 'strcpy' SomeFile.cpp(###): warning C4996: 'strcpy': This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
I looked for the online help, which doesn't really exist for this specific warning. I did find the Security Features in the CRT article, but that was useless. Because I'm working on a shared project, I didn't want to manually add this #define to every project. The workaround is to add it to the *.user.props file.
Add the ItemDefinitionGroup node below to C:\Users\Jschubert\AppData\Local\Microsoft\MSBuild\v4.0\Microsoft.Cpp.Win32.user.props:
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0"
xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemDefinitionGroup>
<ClCompile>
<PreprocessorDefinitions>_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ResourceCompile>
</ItemDefinitionGroup>
</Project>
And there you have thousands of annoying warnings disappear.
Because MSBuild always includes %(PreprocessorDefinitions) when chaining PreprocessorDefinitions, you can add any number of defines here to exist globally on your machine only.
C# Null-Coalescing (??) operator
The null-coalescing operator (??) is one of my favorites, and I see so few developers using it.
MSDN defines the null-coalescing operator as
The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise it returns the right operand.
Although this is somewhat similar to a conditional operator (sometimes called 'ternary operator'), it is much more concise.
The null-coalescing operator works with nullable value types and reference types. When I first started with the null-coalescing operator, I often underestimated the usage with empty strings. I think this is very important to discuss, hence this blog post.
Strings
For example:
// conditional operator string example = null; string first = example == null ? "default" : example; // null-coalescing operator string second = example ?? "default";
In both of these cases, the resulting string will be "default".
The problem with strings is that the null-coalescing operator only checks against nulls. Code may often return String.Empty instead of nulls. Meaning the following example is not the same.
// conditional operator string example = string.Empty; string first = string.IsNullOrEmpty(example) ? "default" : example; // null-coalescing operator string second = example ?? "default";
In this example, 'first' will be "default" while 'second' will be the empty string. This is a situation in which the null-coalescing operator is useful only when a string must not be null but string.Empty is still perfectly valid.
Nullable Value Types
When working with nullable types, the conditional and null-coalescing operators have another alternative when retrieving the underlying value: GetValueOrDefault(). The problem here is that the method returns the value type, not another nullable type.
For example:
int? example = null; // Conditional operator int? first = example == null ? 100 : example; int firstValue = first.Value; // null-coalescing operator int? second = example ?? 100; int secondValue = second.Value; // GetValueOrDefault() int third = example.GetValueOrDefault(); // third = 0 int fourth = example.GetValueOrDefault(100); // fourth = 100
Notice the catch in the GetValueOrDefault() example... you don't have to reassign the nullable and then get the value. This is useful when you only need the value type. Sometimes, you need a default value and the nullable type. In these cases, I still prefer the null-coalescing operator.
Reference types
The null-coalescing operator can be used with reference types to guarantee that properties or methods do not return nulls.
For example:
public List<Person> People
{
get
{
return _people ?? new List<Person>();
}
set { /* something */ }
}
This is definitely a design/coding preference. I've experienced environments where developers insist on the importance of the NullReferenceException being thrown in production code. I've also experience plenty of environments where exceptional code is properly handled and this construct would rarely, if ever, be useful.
Maybe it is not a well-known operator, or most developers would like code to be lengthier and explicit. In a web development team, I think the null-coalescing operator is very similar to the common JavaScript example of providing a default value using the || operator:
var process = function(val) {
val = val || 100;
/* etc. */
}
Visual Studio and Interface property stubs
Last year, I posted a question on StackOverflow asking if it was possible to replace the property stubs for interface refactoring
Is it possible to change the stub used to implement interfaces in Visual Studio 2008?
For instance, when I choose either
Implement interface 'IMyInterface'
or
Explicitly implement interface 'IMyInterface'
Instead of a number of properties that look like this:
public string Comment
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
I'd like my properties to use the C# 3.0 auto-implemented properties and look like this:
public string Comment {get;set;}
I want to do this to avoid forcing this interface to be an abstract class.
I've looked through the snippets in the Visual Studio folder, but I didn't see any that would be appropriate. I've also googled and searched SO, and found nothing.
If this isn't possible, does anyone have a macro I can steal?
Thanks.
I then discovered that you can edit the file at:
[program files]\Microsoft Visual Studio 10.0\VC#\Snippets\1033\Refactoring\PropertyStub.snippet
and modify the xml node 'Code' to contain the following:
<Code Language="csharp">
<![CDATA[ $signature$ { $GetterAccessibility$ get; $SetterAccessibility$ set;} $end$]]>
</Code>
I really wish this was the default for .NET 3.0 and higher (since auto-implemented properties have been around).
propv.snippet for creating Automatic virtual properties in C#
I'm all about saving time. I have a huge collection of helpful snippets. Here's one that automatically creates a virtual property, which is really helpful if you use Castle's DynamicProxy (NHibernate uses this).
Instead of embedding the code directly, I'm using http://gist.github.com so changes to the file will show immediately in the post.
testy C# Test Method Snippet
This is a pretty trivial snippet, but I use it quite a lot.
Save this file as testy.snippet in your [Visual Studio]\VC#\Snippets\1033\Test directory.
Then, in the code editor, type testy, TAB+TAB to expand the snippet.
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>testy</Title>
<Shortcut>testy</Shortcut>
<Description>Code snippet for creating an NUnit unit test in C#</Description>
<Author>James Schubert</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>summary</ID>
<ToolTip>Summary</ToolTip>
<Default>Summary</Default>
</Literal>
<Literal>
<ID>name</ID>
<ToolTip>Test name</ToolTip>
<Default>TestName</Default>
</Literal>
<Literal>
<ID>description</ID>
<ToolTip>Test Case</ToolTip>
<Default>Assumption_Does_Expectation</Default>
</Literal>
</Declarations>
<Code Language="csharp"><![CDATA[ ///<summary>
/// $summary$
///</summary>
[Test]
public void $name$_When_$description$()
{
// Arrange
// Act
// Assert
}
$end$]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>



