New scriptcs script pack – MemberPrint

I have just published a really simple little ScriptCs (I’m still not sure if I should be capitalising that or not) script pack. It’s intended to be used on the REPL. All it does it print some details about the objects and types to help you navigate the REPL more easily. As usual, the code is available on GitHub.

To install, run the following command:

scriptcs -install scriptcs.memberprint

Then just run scriptcs. The easiest way to figure out the API is to run it over itself, like this:

c:\test>scriptcs
scriptcs (ctrl-c or blank to exit)

> var print = Require<MemberPrint>();
> print.Methods(print);
+   Constructors(Type t, BindingFlags flags, String regex, Boolean verbose) : Void
+   Constructors(Object o, Boolean verbose) : Void
+   Constructors(Object o, String regex, Boolean verbose) : Void
+   Constructors(Type type, Boolean verbose) : Void
+   Constructors(Type type, String regex, Boolean verbose) : Void
+   Constructors(Object o, BindingFlags flags, Boolean verbose) : Void
+   Constructors(Type t, BindingFlags flags, Boolean verbose) : Void
+   Constructors(Object o, BindingFlags flags, String regex, Boolean verbose) : Void
+   Equals(Object obj) : Boolean
+   Events(Object o, Boolean verbose) : Void
+   Events(Object o, String regex, Boolean verbose) : Void
+   Events(Type t, Boolean verbose) : Void
+   Events(Type t, String regex, Boolean verbose) : Void
..... (etc)

MemberPrint supports a few filtering options. You can filter using BindingFlags, just as though you were doing the reflection yourself:

> print.Methods(new System.Text.RegularExpressions.Regex(""), BindingFlags.Static|BindingFlags.Public);
+ # CompileToAssembly(RegexCompilationInfo[] regexinfos, AssemblyName assemblyname) : Void
+ # CompileToAssembly(RegexCompilationInfo[] regexinfos, AssemblyName assemblyname, CustomAttributeBuilder[] attributes) : Void
+ # CompileToAssembly(RegexCompilationInfo[] regexinfos, AssemblyName assemblyname, CustomAttributeBuilder[] attributes, String resourceFile) : Void
+ # Escape(String str) : String
+ # get_CacheSize() : Int32
+ # IsMatch(String input, String pattern) : Boolean
..... (etc)

You can also filter using regular expression text.

> print.Methods(new System.Text.RegularExpressions.Regex(""), "^Is.+");
+ # IsMatch(String input, String pattern) : Boolean
+ # IsMatch(String input, String pattern, RegexOptions options) : Boolean
+ # IsMatch(String input, String pattern, RegexOptions options, TimeSpan matchTimeout) : Boolean
+   IsMatch(String input) : Boolean
+   IsMatch(String input, Int32 startat) : Boolean

You can run it over types as well as instances. Can’t remember the constructors for System.DateTime?

> print.Constructors(typeof(DateTime))
+   .ctor(Int64 ticks)
+   .ctor(Int64 ticks, DateTimeKind kind)
+   .ctor(Int32 year, Int32 month, Int32 day)
+   .ctor(Int32 year, Int32 month, Int32 day, Calendar calendar)
+   .ctor(Int32 year, Int32 month, Int32 day, Int32 hour, Int32 minute, Int32 second)
+   .ctor(Int32 year, Int32 month, Int32 day, Int32 hour, Int32 minute, Int32 second, DateTimeKind kind)
+   .ctor(Int32 year, Int32 month, Int32 day, Int32 hour, Int32 minute, Int32 second, Calendar calendar)
+   .ctor(Int32 year, Int32 month, Int32 day, Int32 hour, Int32 minute, Int32 second, Int32 millisecond)
+   .ctor(Int32 year, Int32 month, Int32 day, Int32 hour, Int32 minute, Int32 second, Int32 millisecond, DateTimeKind kind)
+   .ctor(Int32 year, Int32 month, Int32 day, Int32 hour, Int32 minute, Int32 second, Int32 millisecond, Calendar calendar)
+   .ctor(Int32 year, Int32 month, Int32 day, Int32 hour, Int32 minute, Int32 second, Int32 millisecond, Calendar calendar, DateTimeKind kind)

There are multiple overloads for each of the following methods:

  • Methods(object o)
  • Properties(object o)
  • Events(object o)
  • Constructors(object o)
  • Members(object o) (this one just calls all of the others)

The code is a little rough around the edges at the moment, but so far I have found it useful enough that I decided to share the script pack.

Posted in Programming | Tagged | Leave a comment

Solutions to some problems hosting Windows Workflow Foundation applications in AppFabric

I’m trying to stand up some Windows Workflow Foundation applications in AppFabric for a spike on an application I’m building and so far it has been… unpleasant. Here are a couple of solutions to some frustrating problems I encountered. Hopefully I can help save someone else a bit of time.

Workflow persistence is not functional because the net.pipe binding is not enabled for this web site

Encountered while trying to configure my WF service on an IIS virtual directory. In particular I encountered this error on the Workflow Persistence tab and a similar one onthe Workflow Host Management tab in the Configure WCF and WF for Application dialog.

Enable the net.pipe protocolNow, in theory this will be automatically fixed when you click Apply. And in theory, even if it’s not then it should be resolved by taking the following steps:

  • Right click the web site that hosts your service in the IIS Connections pane, click Manage Websites -> Advanced Settings and add ,net.pipe to the end of the “Enabled Protocols” setting (no spaces!)
  • With the same site selected, click Edit Bindings on the Actions pane and add a net.pipe binding with Binding Information = *

And in theory, practice and theory are the same. But in practice, unfortunately, they are not. If you’re not running Windows Server (or your install is a bit wonky) then there’s an extra step to take, because you’ll find that net.pipe is not an available binding type in the bindings dialog.

To resolve: Open the “Turn Windows features on or off” dialog (find it by searching in the Start menu/screen, under Settings). Open up the Microsoft .NET 3.5 folder and tick “Windows Communication Foundation Non-HTTP Activation”. This should make the net.pipe binding available to you. You may need to run iireset in a console as admin first.


Error: Unable to start debugging on the Web Server

or, if you try running without debugging

Error: Cannot obtain Metadata from xamlx The remote server returned an unexpected response: (405) Method Not Allowed.

or, if you drill further into that error

HTTP Error 404.3 – Not Found The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map

The honest truth is I’m not sure what caused this error. I tried a whole bunch of stuff. I added some handlers to my root Web.config, installed some Workflow hosting modules in IIS, played with permissions, all kinds of stuff and I couldn’t get the site to handle the .xamlx request. Ultimately here’s what resolved the issue for me. The first step may not be necessary, I honestly don’t know (I recommend reading the linked article). But it worked.

  • Run the following command: “%WINDIR%\Microsoft.Net\Framework\v3.0\Windows Communication Foundation\ServiceModelReg.exe” -r
  • Uninstall and reinstall the following Windows features from the “Turn Windows features on or off” dialog: Windows Communication Foundation HTTP Activation, Windows Communication Non-HTTP Activation. They are both under the .NET Framework 3.5 feature.

applicationHost.config : Unrecognised attribute: ‘serviceAutoStartMode’

After I got my workflow up and running I realised that every other service and website on my machine was broken. It seems that AppFabric stepped all over my applicationHost.config file and left an invalid attribute in there. Take a look at this thread for the solutions to this issue.

Posted in Programming | Tagged , , | 1 Comment

Building a scriptcs script pack

If you haven’t seen scriptcs yet you should check it out. It’s a scripting environment for C#, but more interestingly it incorporates a module system similar to what you’d see in node.js using NuGet as a packaging mechanism. I won’t go into an intro to scriptcs, because others like Scott Hanselman and the man himself, Glenn Block (and contributors) have done a better job that I could have.

Instead I’ll talk about a concept that (so far) hasn’t had a lot of documentation love – script packs.

What is a scriptcs script pack?

The basic idea is that a script pack is an object (generally compiled in a DLL and available in your script’s bin directory) that either exposes some functionality to the scripting environment or simplifies the usage of some other functionality. This seems like an overly broad definition so let’s start with an example of script pack usage. From the scriptcs.WebApi script pack.

public class TestController : ApiController {
  public string Get() {
    return "Hello world!";
  }
}

var webApi = Require<WebApi>();
var server = webApi.CreateServer("http://localhost:8080");
server.OpenAsync().Wait();

Console.WriteLine("Listening...");
Console.ReadKey();
server.CloseAsync().Wait();

That’s the complete script – no using statements and ridiculously simple API. The script pack takes care of “injecting” using statements into any script that uses the script pack (ie, calls that Require method above – we’ll get into that) and returning a script-friendly object to the shell.

Let’s get started building a script pack. I want to create a script pack that allows me to pull down arbitrary strings from an HTTP request – let’s keep it really nice and simple.

Fire up Visual Studio (note: you don’t actually need Visual Studio for this, but I’ll assume if you’re comfortable enough to use other tools then you’ll know when to adjust the steps) and create a new Class Library project. Delete that damn Class1.cs file, open the Package Manager console and execute the command

Install-Package scriptcs.contracts

The contracts library has a couple of interfaces we’ll need to implement to make our script pack work. Let’s start by creating our “convenience object”. We’ll call it Http, and all it’s going to do is make GET requests and return strings. So let’s implement this class.

using System.Net;
using ScriptCs.Contracts;

namespace ScriptCs.Http
{
    public class Http : IScriptPackContext
    {
        public string Get(string uri)
        {
            var client = new WebClient();
            return client.DownloadString(uri);
        }
    }
}

That IScriptPackContext interface there is a marker interface that scriptcs seems to use to identify objects that are capable of being returned by script packs. It has no members, so there’s nothing to implement.

The next step is to implement the script pack itself. This object will be picked up by the scriptcs engine and is capable of generating and returning IScriptPackContext objects. Because our script pack is so simple we don’t need to do much in the implementation of this interface:

using ScriptCs.Contracts;

namespace ScriptCs.Http
{
    public class HttpScriptPack : IScriptPack
    {
        IScriptPackContext IScriptPack.GetContext()
        {
            return new Http();
        }

        void IScriptPack.Initialize(IScriptPackSession session)
        {}
        void IScriptPack.Terminate()
        {}
    }
}

This is fairly self-explanatory. The scriptcs engine will cache all available IScriptPack objects and when a particular script pack is requested (see below) then the appropriate script pack context will be returned.

The Initialize method here is interesting. We’re not doing anything with it in this particular program, but it’s worth going over what can be done. This method gives us an IScriptPackSession object which has two important methods:

  • AddReference – use this method to add library references to be available in your script. After your script pack is loaded into a script the specified references will be available for your use with no further code inside the script.
  • ImportNamespace – this method can import namespaces for use in your scripts. It’s just a nice convenience so that your user’s scripts can stay nice and clean. We don’t need to do this in our current script pack, but if you refer back to the WebApi script above you’ll notice we’re using the ApiController class without any using statements. This is because the WebApi script pack imports this namespace for you.

Obviously the Terminate method should be used for cleaning up any resources after yourself and leaving the machine in a good state.

So that’s pretty much all there is to building a script pack. Now we’ll go ahead and use it. Build your library, grab the DLLs from your bin directory and move it into a test folder like c:\myscripts\bin. Create a new script that looks like

var http = Require<Http>();
Console.WriteLine(http.Get("http://google.com"));

Save it into your scripts folder (c:\myscripts\myscript.csx in my above example) and execute it using

scriptcs myscript.csx

And observe the output. All done! Now all that’s left is to package your script up in a NuGet package and publish.

Posted in Programming | Tagged , , | 4 Comments

Visual Studio quick tip – cool behaviour of Ctrl-C and Ctrl-X

I’m writing this quick post because a number of people have been watching me edit code in VS and have been surprised when they see me do this, not realizing this functionality exists.

In the editor, hitting Ctrl-C while nothing is selected will copy the entire line that the text cursor is currently on. Now pressing Ctrl-V will insert that line above the text cursor (plus a newline). Using Ctrl-X instead of Ctrl-C will do the same thing except it will cut instead of copy the current line.

Give it a try, it’s a nifty trick that can often save a lot of keystrokes.

I have confirmed that this behaviour exists in Visual Studio 2008, 2010 and 2012. It’s probably there in 2005 and earlier but I haven’t checked.

Posted in Programming | Tagged | 3 Comments