Saturday, February 20, 2010

Fun with F#

No pun intended.

My first F# program: a command-line program that takes a starting path, a file name pattern, and pattern to search for, iterates through the path and its subfolders loading all files with the given file name pattern and returning the names of those files that contain the pattern to search for.


// Learn more about F# at http://fsharp.net
open System.IO

[<EntryPoint>]
let main (args : string[]) =

let filesInFolder : string [] =
System.IO.Directory.GetFiles(
args.[0], args.[1],
SearchOption.AllDirectories)

let fileInfos : System.IO.FileInfo[] =
Array.map
(fun file -> new System.IO.FileInfo(file))
filesInFolder

let getStreamForFile (file : FileInfo) : StreamReader =
new StreamReader(file.OpenRead())

let getFileContents (fileStream : StreamReader) : string =
fileStream.ReadToEnd()

let fileContentsContainPattern (fileContents : string) : bool =
fileContents.Contains(args.[2])

let writeNameOfFilesContainingPattern(file : FileInfo, containsPattern : bool) =
match containsPattern with
| true -> System.Console.WriteLine(file.FullName)

Array.map
(fun fileInfo -> writeNameOfFilesContainingPattern(fileInfo,
fileContentsContainPattern(getFileContents(getStreamForFile(fileInfo)))))
fileInfos
0

Thursday, September 3, 2009

Windows 7 Doesn't Include a Disk Image Mounter: Why?

This is a rant.

Why does Microsoft fail to include the ability to mount disk images as a basic feature of their operating systems?

I just don't get it.

Wednesday, September 2, 2009

StructureMap In Five Minutes or Less

[Filed under old stuff.]
StuctureMap is possibly the best IoC solution out there. And it is really easy to get started.

Here's some of the steps required to get started with something simple. These steps assume that you are going to handle configuration within an app.config or web.config file.
1. Go to http://sourceforge.net/projects/structuremap/files/ to get the latest release.
2. Copy the StructureMap.dll file to a location relative to your solution.
3. Add a reference to the StructureMap.dll to your project.
4. Within your config file, add the following configSection configuration:

<section name="StructureMap" type="StructureMap.Configuration.StructureMapConfigurationSection,StructureMap"/>

5. Within your config file, add the following configuration for StructureMap:

<StructureMap>
<DefaultInstance PluginType="Namespace.IInterfaceType,AssemblyNameForInterfaces" PluggedType="Namespace.ImplementationType,AssemblyNameForImplementation">
</DefaultInstance>
</StructureMap>

6. Add the following code to your project (this must be executed first):

ObjectFactory.Initialize(x =>
{
// Tell StructureMap to look for configuration
// from the App.config file
// The default is false
x.PullConfigurationFromAppConfig = true;
});

7. Use this code to get intstances of your mapped types, and you're ready to go:

ObjectFactory.GetInstance(typeof(Namespace.IInterfaceType));

There you have it. StructureMap in five minutes or less.

Monday, August 31, 2009

Extending WCF

[Filed under old stuff.]
Microsoft has provided a large number of seams/hooks into WCF so that we can extend it. I believe that the two most powerful are the IInstanceProvider and IOperationInvoker.

IInstanceProvider can be implemented in a class that specifies how WCF creates the instance of the service requested. By default, WCF creates an instance of the service by invoking its parameterless constructor. If you have a case in which you need to do other things when that instance is created - say you want to inject dependencies into it - you have to create your own instance provider. Additionally, in order to make the whole thing work you have to create three other custom classes - a custom behavior responsible for assigning your custom instance provider to the InstanceProvider property of the DispatchRuntime, a custom service host that applies the custom behavior, and finally a custom service host factory that builds the custom service host. This may sound like a lot, but it really is fairly straightforward. The best example of this I've seen can be found as Los Techies.

IOperationInvoker allows you to decorate existing operations with additional responsibilities at runtime. A really good example (within a really good article) can be found over at MSDN. Another example - this one allows WCF to call COM objects within STA (single apartment threads): Scott Seely's Blog.

Tuesday, May 19, 2009

Extension Method for Getting All Properties of a Type

I was writing a helper class that I needed to iterate through all of the properties of a type; later realized that my code didn't grab every property, specifically those that were interface types. Then I found this at beaucrawford.net (http://beaucrawford.net/post/Using-Reflection-to-get-inherited-properties-for-an-interface.aspx). I then turned it into an extension method. Behold:


namespace System
{
public static class TypeExtensionMethods
{
public static PropertyInfo[] GetAllProperties(this Type type)
{
List<Type> typeList = new List<Type>();
typeList.Add(type);

if (type.IsInterface)
{
typeList.AddRange(type.GetInterfaces());
}

List<PropertyInfo> propertyList = new List<PropertyInfo>();

foreach (Type interfaceType in typeList)
{
foreach (PropertyInfo property in interfaceType.GetProperties())
{
propertyList.Add(property);
}
}

return propertyList.ToArray();
}
}
}

Tuesday, December 16, 2008

Type Fidelity in WCF

Check out Evan's post on handling odd serialization problems in WCF. Old post, but well worth the read: Type fidelity across the wire in WCF.

Friday, December 12, 2008

SQL Session State, Response.Redirect() and HttpApplication.Dispose()

Our customer-facing ASP.NET web applications are load balanced, so of course we utilize SQL SessionState.

Thing is, SQL SessionState is much less forgiving than InProc session state. Everything you store must be marked with the Serializable attribute.

Problem is, the application has a funny way of telling you that you've forgotten that important attribute somewhere. Funny in that it doesn't throw an exception when it can't write the item to the session database.

See, the items you store in session during a Request are stored InProc until the ReleaseRequestState event is fired. At that time, the items you've stored in session are written to state. In the case of SQL Session State, this is when the stored procedure to write the data to the database is actually invoked.

In my case, I was storing a business entity in session, to be pulled right back out in the next request. Problem was, it was vanishing between the time it was written and the time the next Request came through, right after a Response.Redirect(). I was getting no exceptions, no indications at all as to what was happening.

After slamming my head against my desk for a couple of days, I found something that will now become a best practice. I call the Dispose() method on the ApplicationInstance of the current request. This manually calls the Dipose() method on each of the httpModules you have registered in your application - and somewhere in there the ReleaseRequestState event is raised. In doing this, I finally got the exception I was looking for - the entity that I was trying to store in session had a property of a type that was not marked Serializable. So I fixed it, and everything is working nicely.

Manually calling Dispose() right after a Response.Redirect() is a nice, clean way of freeing up resources and finishing the current Request in a tidy way. And it helps expose these little issues.