Facebook.NET Configuration Section

I’m checking out the Facebook.NET libraries, and find the documentation to be very lacking. I could be looking in the wrong places. Anyway, to setup the configuration section, you need to reference the FacebookNET.Web.dll. Then in your config file add a section entry to the configSections tag like:

<section name="facebook" type="Facebook.Web.Configuration.FacebookSection, FacebookNET.Web" allowDefinition="MachineToApplication"/>

Then add the Facebook section with your info to the configuration tag:

<facebook>
    <application name="Facebook.NET App" apiKey="[App Key]" secret="[Secret]"/>
</facebook>

That’s it. Now you can access that info from code like:

var fbSection = (FacebookSection)ConfigurationManager.GetSection("facebook");
var secret = fbSection.Applications["Facebook.NET App"].Secret;

Castle microkernel Shows It’s strength

I’m a big fan of the CastleProject.org stack, but the MicroKernel really shows it’s strength when you need to do a couple of custom things, and find out that the customization is really easy, and intuitive.

Setting up a facility to add a custom bunch of objects. I think there are already facilities to do this, but it’s really simple for standard cases and allows you to easily get things setup. You basically just need to override the Init method.

protected override void Init()
{</p>



List<Assembly> assemblies = ReadConfigForAssemblies(FacilityConfig);
<span class="kwrd">foreach</span> (Assembly assembly <span class="kwrd">in</span> assemblies)
    LoadCommands(assembly);

}

The configuration is already read in for you, so parsing that is easy.

public List<Assembly> ReadConfigForAssemblies(IConfiguration facilityConfig)
{
    List<Assembly> assemblies = new List<Assembly>();
    try
    {
        foreach (IConfiguration configuration in facilityConfig.Children)
            if (configuration.Name.Equals("assembly", StringComparison.InvariantCultureIgnoreCase))
                assemblies.Add(Assembly.Load(configuration.Value));
    }
    catch (Exception e)
    {
        throw new ConfigurationErrorsException(
            "Assembly could not be loaded, check you have the correct name in the configuration.", e);
    }
    return assemblies;
}

Lastly, you can search through the configured assemblies and register any types that match what your looking for.

private void LoadCommands(Assembly assembly)
{
    foreach (Type type in assembly.GetTypes())
        if (typeof (IMyInterface).IsAssignableFrom(type) && !type.IsAbstract && type.IsPublic)
            Kernel.AddComponent(type.FullName, type);
}

This is getting to be a long post, but I'm sure you're wondering about testing. It's easy too! You have to mock out the configuration stuff, but that's really it. I just put into a setup method and once done you have your container setup and ready for testing.

[SetUp]
public void Setup()
{
    _container = new WindsorContainer();
    _facility = new CommandFacility();

    _mocks = new MockRepository();
    IConfiguration config = mocks.DynamicMock<IConfiguration>();
    IConfiguration configChild1 = mocks.DynamicMock<IConfiguration>();
    IConfiguration configChild2 = mocks.DynamicMock<IConfiguration>();

    using (_mocks.Record())
    {
        Expect.Call(config.Children).Return(new ConfigurationCollection(new IConfiguration[] { configChild1 }));
        Expect.Call(configChild1.Name).Return("assembly");
        Expect.Call(configChild1.Value).Return("MyAssemblyName");
    }

    using (_mocks.Playback())
    {
        _facility.Init(_container.Kernel, config);
    }
}

There's more documentation on the Castle site. Next time custom dependency resolvers and sub kernels...


Castle MicroKernel Shows It’s Strength P2

Continuing from my previous post… Using Custom Dependency Resolvers and Sub Kernels. I think this is more of an edge case, but the fact that I can be done really easily is where the Castle strength is.

First, I see two nice things about Sub Kernels, they can be used by themselves or added as a child to another Kernel, meaning for testing and other uses, the Kernel can be completely hidden. Next, when added as a child, dependencies that live in the parent container can be used by types in the child container, automatically. I don’t know if there are any guide lines as to when to use a Sub Kernel, but I would consider it when you have a custom facility or a factory class which stores a lot of types or if you need to customize the Kernel in some way. Using a container is as easy as creating the class and allowing a Kernel to be passed in a Constructor when needed.

private readonly IKernel _container = new DefaultKernel();</p>



public MyFactory() {

_container.Resolver.AddSubResolver(<span class="kwrd">new</span> CaseInsensitiveDependencyResolver());

}

public MyFactory(IKernel parent) : this()
{

parent.AddChildKernel(_container);

}

Secondly, Customizing the Kernel with a CustomDependencyResolver, is easy and very useful when you need to do that. In this case I have a simple Resolver which looks at the additional parameter dictionary (passed to the Resolve Methods) and looks for a match ignoring case. I just needed to implement the ISubDependencyResolver interface which only has two methods, and register it on the container using Resolver.AddSubResolver (You can also overwrite the main Resolver when the Kernel is created). SubResolvers should return null if they didn't resolve the dependency, the main Resolver will throw an error if it's a required dependency.

internal class CaseInsensitiveDependencyResolver : ISubDependencyResolver
{
    public object Resolve(CreationContext context, ISubDependencyResolver parentResolver, ComponentModel model,
                          DependencyModel dependency)
    {
        foreach (DictionaryEntry entry in context.AdditionalParameters)
            if (dependency.DependencyKey.Equals(entry.Key as string, StringComparison.InvariantCultureIgnoreCase))
                return entry.Value;
        return null;
    }

    public bool CanResolve(CreationContext context, ISubDependencyResolver parentResolver, ComponentModel model,
                           DependencyModel dependency)
    {
        if (context == null || context.AdditionalParameters == null)
            return false;

        foreach (DictionaryEntry entry in context.AdditionalParameters)
            if (dependency.DependencyKey.Equals(entry.Key as string, StringComparison.InvariantCultureIgnoreCase))
                return true;
        return false;
    }
}

Again, as always, there’s more info on the CastleProject.org site.


Using flags in c#

Some notes about using enums as flags in C#. Use the FlagsAttribute on you enum. Have a None option set to 0. Have the first option start at 1, and each next value should be 2 times the previous one (I wonder what that pattern is called). Something like:

[Flags]
public enum PropertyOptions
{</p>



None = 0,
IgnoreProperty = 1,
DisplayName = 2

}

Checking if a flag is set is done using the following syntax:

bool isIgnoreSet = (_options&PropertyOptions.IgnoreProperty) == PropertyOptions.IgnoreProperty;

Guidelines: http://msdn2.microsoft.com/en-us/library/ms229062.aspx

Using The Enum: http://dotnet.org.za/kevint/pages/Flags.aspx


Attribute Values on interfaces are not inherited

I guess it makes sense, that an interface is implemented, not inherited, but I think it’s confusing that interfaces are ignored when searching for custom attributes, using the GetCustomAttributes methods.

Attributes shouldn’t be thought of as part of an interface, strictly meta data in that case? No, I think, interfaces should have been searched, that member is part of an interface, and implementations should have access to that members metadata. If nothing else, custom attributes defined with inheritance should be required to be implements by the implementers.


Tortoise SVN global ignores

I know tons of people have already posted their global ignores list, but here’s mine:

*/bin */obj *.user *.suo *.webinfo bin obj *.dll *.pdb *.exe  _ReSharper* */_ReSharper* *.resharper *.DLL

http://tortoisesvn.tigris.org/ – Tortoise Explorer Client for SVN


NS3Library now has support for SQLiteS3Service

More refactoring and support added for SQLite. There are now two IS3Service implementations, one using Amazons S3 and one using SQLite locally. This allows for easier testing (and free) testings and just a config change to your IoC config for deployment.

The IS3Service Interface has been simplied and cleaned up as well. It’s not perfect, but it is open source, so feel free to make changes.

http://sqlite.phxsoftware.com/ – You can get the SQLite for .net from there.

 


Aws S3 Library changed to NS3Library

I did some major refactoring to the AwsS3Library including renaming it to NS3Library and setting up a new project at http://code.google.com/p/ns3library/

The major changes were around adding interfaces to the public objects to allow different implementations. I hope to add a Sql Lite Implementation soon.


Moving from Castle RC3 to Trunk

Today I moved from Castle Project RC3 to Trunk there were a couple changes that I needed to make. The IFilter interface has changed, The ExecuteEnum has changed to ExecuteWhen. The IRailsEngineContext name has changed to IEngineContext. I think there’s been a fair amount of refactoring around the Controller, I think the IController interface is new and there is now an IControllerContext interface. The EngineContextModule has been removed, so I needed to remove that from the web.config. and the Windsor integration facility name has changed from RailsFacility to MonoRailFacility, which also required a web.config change. The upgrade seems to be working well.


Send Email using RenderViewAndSend on Monorail

Templates

When sending an email using RenderMessageAndSend the following will be parsed for the message and removed what’s left is sent as the body.

from: name <address> or address
to: address,address
cc: address,address
bcc: address,address
subject: value
X-header: value
body text

</span>If the body text contains ‘’ it will be sent as html.

By default layouts will not be applied. It looks for views stored in
Common if the view name starts with a /. Otherwise it looks for
views in the Mail folder.
</p>


  • /MailTemplate.brail should be stored in views/common/MailTemplate.brail</li>

  • MailTemplate.brail should be stored in views/mail/MailTemplate.brail
  • </ul>

    Testing

    The test support doesn’t currently render the message, but you can check for the number of message sent and the template name and properties.
    </p>

    Assert.That(MessagesSent.Length, Is.EqualTo(2));
    Assert.That(RenderedEmailTemplates[0].Name, Is.EqualTo(“MailTemplate”));
    Assert.That(RenderedEmailTemplates[0].Parameters[“to”], Is.EqualTo(emails[0]));

    </span>In the MessageSent Collection all the messages are hard coded as
    </p>

    new Message(“from”, “to”, “subject”, “body”);

    </span>Also added to using.castleproject.org Sending Email With RenderViewAndSend



    </p>


Unit Testing Castle Monorail Filters

I’m really liking the unit test support in the Castle Monorail project. Here’s an example to create a simple test for testing filters.

[TestFixture]
public class AdminAuthorizationFilterTest : BaseControllerTest
{
private Controller _controller;

[SetUp]
public void Setup()
{
_controller = new TestController();
PrepareController(_controller);
}

[Test]
public void Perform_No_User_Expect_False()
{
AdminAuthorizationFilter filter = new AdminAuthorizationFilter();
bool perform = filter.Perform(ExecuteEnum.BeforeAction, Context, _controller);
Assert.That(perform, Is.False);
Assert.That(Response.WasRedirected, Is.True);
}
}

internal class TestController : Controller {}

</p>

Setup is the same as testing a controller, but I needed to create an basic test controller. I attempted to use Rhino Mocks to partial mock the controller, but that disconnected the BaseControllerTest resulting in things like checking the Response object not working. Creating the class is one less line of code anyway.

More on test support here.
And Here.


Storing DateTime objects in Amazon Simple DB

I’m working with the Amazon Simple DB web service. It stores everything in strings as such I needed to store a DateTime in ISO 8601 format for later sorting the strings in correct order. The frameworks has at least three formating strings. Either s or u or o. The s format seems like a good choice as it’s called the sortable format. However it doesn’t store any sub second data or timezone info. The u format is s in universal time, but still lacks the sub second data. Lastly the o format for round trip stores all the DateTime info in ISO 8601 format and should remain sortable as long as all dates are stored in the same time zone. MSDN DateTime format strings{#uww6}

Here’s more good info on storing data as a string in ways that are sortable later and useful Simple DB info.

http://docs.amazonwebservices.com/AmazonSimpleDB/2007-11-07/GettingStartedGuide/{#acr4}
http://docs.amazonwebservices.com/AmazonSimpleDB/2007-11-07/DeveloperGuide/{#gy.7}
http://developer.amazonwebservices.com/connect/entry.jspa?externalID=1231&categoryID=152{#dl7j}
http://developer.amazonwebservices.com/connect/entry.jspa?externalID=1232&categoryID=152{#f-:g}







Castle monorail brail view template

I finally spent two minutes to create a view.brail VS template today. It’s really basic, but at least I won’t end up with a class definition every time I try to add a new view. Below is the zip file, just drop in into My Documents\Visual Studio 2005\Templates\ItemTemplates.

View.zip (5.12 KB)


Updates to AwsS3Library – Bucket contents support

Posted updates and fixes to the AwsS3Library. Added support for AwsBucket Contents to be parsed when getting a bucket.

AwsBucket bucket = _service.Get(new AwsBucket("somebucket"));
foreach (AwsObjectKey awsObjectKey in bucket.AwsObjectKeys)
{
Console.WriteLine("Object Key " + awsObjectKey.Key);
}

</p>


OpenId Authentication In Castle Monorail with ExtremeSwank OpenID Consumer

I spent some time today setting up OpenId in Monorail using ExtremeSwank OpenId consumer library. I went with a view component that can be on every page and a login controller to handle the authenticate and logout functions. This code is mostly a mix of the ExtremeSwank sample code and monorail sample code and probably shouldn’t be used in a production environment.

Anyway, we’ll start with the controller. It has three methods, Index, Authenticate, and Logout. The Index is just an empty action to explain OpenId to those who may not have experience with it. Authenticate takes the OpenId URL provided by the user to authenticate.  We store that in the session and pass to the consumer. Then we call BeginAuth which will process the request as long as the URL is correct. If not I render the Index view.

public void Authenticate(string openIdUrl)
{
try { OpenIDConsumer consumer = new OpenIDConsumer();
consumer.Identity = openIdUrl;
Session[OPENID_LOGIN] = consumer.Identity;
consumer.ReturnURL = Context.UrlReferrer;
consumer.BeginAuth();
}
catch (Exception e)
{
PropertyBag["message"] = "Login attempt failed.";
}
RenderView("Index");
}
ly, I have the Logout method which just removes the OpenIdUser object from the session.<!-- code formatted by http://manoli.net/csharpformat/ -->
public void Logout()
{
Session[OPENID_USEROBJECT] = null;
RedirectToReferrer();
}

Next I have the ViewComponent which checks to see if the user is authenticating, authenticated, or not. I check for the OpenIDUser in the session first, if it finds that, then the user is authenticated. Otherwise, it creates a OpenIdConsumer object which looks at the state of authentication and executes accordingly, rendering either the default URL box or the logout link.

public override void Render()
{
OpenIDUser user = Session[LoginController.OPENID_USEROBJECT] as OpenIDUser;
if (user != null)
{
RenderLoggedIn(user);
}
else { OpenIDConsumer consumer = new OpenIDConsumer();
switch (consumer.RequestedMode)
{
case RequestedMode.IdResolution:
consumer.Identity = (string)Session[LoginController.OPENID_LOGIN];
if (consumer.Validate())
{
user = consumer.RetrieveUser();
Session[LoginController.OPENID_USEROBJECT] = user;
RenderLoggedIn(user);
}
else { RenderLoginFailed(); } break;
case RequestedMode.CancelledByUser:
RenderLoginCancelled();
break;
default:
base.Render();
break;
}
}
}
eded to add the appropriate views, but thats mostly all that's needed for this simple setup. <br><p></p>

How to test a mocked object when that object requires an attribute

Today I needed to unit test a method that checked for and required a specific attribute on the class. I ended up with a fairly simple solution, the decorator pattern. Simply create a decorator for the type that needs the attribute, put the attribute on the decorator. Pass you mocked class to a new instance of the decorator when you pass to the method being tested. I sounds like more work then it is, of course it may not always make sense to go this route. Anyway, here’s the code.



using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;
using Rhino.Mocks;

namespace MockingClassesWithRequiredAttributes
{
[TestFixture]
public class Class1
{
[Test]
public void Test()
{
MockRepository mocks = new MockRepository();
IRun mockedRun = mocks.DynamicMock<IRun>();
using (mocks.Record())
{
mockedRun.Run();
LastCall.On(mockedRun);
}
using (mocks.Playback())
{
IRequireCategoryAttribute(new MockDecorator(mockedRun));
}
}

static void IRequireCategoryAttribute(IRun run)
{
object[] attributes = run.GetType().GetCustomAttributes(
typeof(System.ComponentModel.CategoryAttribute), false);
Assert.That(attributes.Length, Is.GreaterThan(0));
run.Run();
}
}

[System.ComponentModel.Category]
class MockDecorator : IRun
{
private readonly IRun run;

public MockDecorator(IRun run)
{
run = run;
}

public void Run()
{
_run.Run();
}
}

public interface IRun
{
void Run();
}
}

One downside to this approach is the MockDecorator class that is just for testing. Any other approaches you’ve used?


Circuit City Sucks [rant]

Warning: off topic rant, sorry.

If you are going to buy anything from Circuit City be warned that you will be dealing with either lying

or ignorant and lazy sales people and rude customer service.

Recently on two different occasions I bought a product based on what the sales

person told me and both times they were completely wrong.

The first

time was regarding a Sony handy-cam, they had two models, one was the DCR-SR82 (with a 60 Gig drive) and a DCR-SR42

(with a 30 Gig drive). The sales staff claimed they were the same

except for the drive size, which is completely false. I found this out

after getting home, and reading the manual. It turns out Sony

also has a DCR-SR62

which is the same as the 82 with a smaller drive. One huge difference, among many,

is that the 42 doesn’t record in wide screen format. So I took it back

and had to get the manager of the store to issue a refund. Which he

finally did after talking to the head camera guy who confirmed my

claims. End result: bought the SR62 elsewhere (online).

I’ve shopped at Circuit City a lot in the past, and so I thought, maybe the sales

person was just new or something. So, I wanted some speaker mounts for my front

speakers and I gave Circuit City another shot. When asked if I need

help, I ask if the speaker mounts I’m looking at will fit

my speakers and proceeded to show the sales guy which speakers I have

(bought from them). He say confidently that they will work with those

speakers. I get home and surprise they don’t. So today I took them back

with the intention of getting the right ones. When I returned them, I

told the CSR

that these don’t fit my speakers, even after showing the sales guy which speakers

I own. He says “That sucks. You should yell at him.” in a very

sarcastic, I don’t give a shit, way. I was shocked to be treated so

poorly. So, I’m done with Circuit City. It’s right on it’s way to being

the next CompUSA.

Too bad really, because at one point they were much better then Best Buy

(the worse electronics store ever), and I bought a lot from them then.

Circuit City sucks, don’t buy from them.


IoC smell: Having IContainerAccessor as a dependency.

Looking back, it should have been an obvious thing to not do, but it wasn’t. I wanted to get access to the container and so I made IContainerAccessor a dependency for my class. The I added that to the container. The Main problem was that the IContainerAccessor interface was implemented on the class that also created the container. So, after startup I had two containers, one I created for the application and one that container created when the IContainerAccessor was created.

Okay, there are other ways to implement the IContainerAccessor, but is that what I really needed? No, I really needed a way to create a specific kind of component. Maybe like a factory of some sort. Oh, yea the factory pattern is already sitting around waiting to be used. And it was a good solution here.

That makes me think, for most cases where you want the container directly, there is a better solution waiting to be used.


Prefer Equals over operator== because generic types will not behave how you expect

I stumbled across this unit testing some Immutable model objects. I’m overriding equals on these object and as so thought, how about I create a generic method to test equality? Sounded like a good idea, got rid of some duplicate code, made sure I’m testing all the variations on each object. Then my tests Failed! WTF? It turns out that using == on Generic Type objects is a bad idea, even it you’ve provided you own operator==! Even if you’ve implemented the IEquatable interface!

This is bad:

private static void TestGeneric<T>(T first1, T second1) where T:class 
{
Console.WriteLine("{0} == {1} is {2}", first1, second1, IsTrue(first1 == second1));
}

The compiler will emit IL that does two odd things, IMO. First, box’s the args first1 and first2. That’s a waste as they are constrained to be classes. Second it’s calling the IL method ceq (check equals). Why doesn’t it call Equals()? I’m guessing there are reasons for this, as it’s the same behavior in 3.5. Maybe if you meant to call Equals you should have?

This is good:

private static void TestGeneric<T>(T first1, T second1) where T:class 
{
Console.WriteLine("{0} Equals {1} is {2}", first1, second1, IsTrue(first1.Equals(second1)));
}

The above code won’t box the objects and it will call your overridden Equals method as expected. I know it’s been said before, but alway use the Equals method!

One more interesting thing with the class constraint you can’t use the == syntax. I guess because once the box and class ceq it will break operator== for value types.

Worse is that if your type constraint is a specific class it will allow and call the operator== method but only on that class so any subclass that are passed in will use the base classes operator== for the compare.

Full code to see this in action is attached:

Program1.cs (2.38 KB)


Getting Finance::Quote installed and working on windows for GnuCash

A little off the coding topic. I use the windows version of GnuCash as such I wanted it to be able to get stock and fund updates automatically. This took a bit more work then I expected so I hope this helps someone else.

  1. Install active state perl
  2. Install OpenSSL Win32
  3. Install nmake following these directions
  4. Run the Perl Package Manager from the start menu and install the Crypt-SSLeay package
  5. From a command prompt in C:\program files\gnucash\bin run perl -w gnc-fq-update

That should be it. One think to note, as far as I can tell you have to call update from the command prompt while your GNU file is Not open. As described here.


ThreadPool + Async methods + ManualResetEvent = Bad

Okay, today it was re enforced that the ThreadPool is not good for long running tasks, specifically those that might use the ThreadPool or use async methods or ResetEvents. I didn’t really track down the root cause, but generally it locked while waiting for a set event. Regardless, the solution as is usually the case was to simplify the code. First by not using a ResetEvent and ThreadPooling for queuing the workload. In place of that a simple QueueRunner class was created using the Monitor class. Using the Monitor.Wait and Monitor.Pulse was new to me, but works well and seems to be very fast. There is a great article here about threading in c#. I’m not going to re-explain what already been said there, but below is the code. It could be enhanced for other uses and performance.

[TestFixture]
public class QueueRunnerTest
{
private int _count = 0;

[Test]
public void Test100ExpectSuccess()
{
Queue<int> queue = new Queue<int>();
for (int i = 0; i < 100; i++)
queue.Enqueue(i);

_count = 0;

QueueRunner<int> runner = new QueueRunner<int>(Work, queue);
runner.RunAndWait();

Assert.That(_count, Is.EqualTo(100));
}

private void Work(object obj)
{
Console.WriteLine("Working " + obj);
Interlocked.Increment(ref _count);
}
}

class QueueRunner<T>
{
private readonly object _syncLock = new object();
private readonly Queue<T> _queue = new Queue<T>();
private int _running = 0;
private readonly int _maxThreads;
private readonly ParameterizedThreadStart _workerDelegate;
private int _toBeCompleted = 0;

public QueueRunner(ParameterizedThreadStart workerDelegate, Queue<T> queue)
: this(workerDelegate, queue, 5)
{
}

public QueueRunner(ParameterizedThreadStart workerDelegate, Queue<T> queue, int maxThreads)
{
_workerDelegate = workerDelegate;
_maxThreads = maxThreads;
_queue = queue;
_toBeCompleted = _queue.Count;
}

public void RunAndWait()
{
new Thread(Start).Start();
Wait();
}

private void Start()
{
lock (_syncLock)
while (_queue.Count > 0)
{
while (_running < _maxThreads)
{
new Thread(DelegateWrapper).Start(_queue.Dequeue());
Interlocked.Increment(ref _running);
}
Monitor.Wait(_syncLock);
}
}

private void DelegateWrapper(object state)
{
_workerDelegate(state);
DecrementCount();
}

private void Wait()
{
lock (_syncLock)
while (_toBeCompleted > 0)
Monitor.Wait(_syncLock);
}

private void DecrementCount()
{
Interlocked.Decrement(ref _running);
Interlocked.Decrement(ref _toBeCompleted);
lock (_syncLock)
Monitor.PulseAll(_syncLock);
}
}
</p>

Resources:
Threading in C# - Joseph Albahari
Delegate BeginInvoke and ManualResetEvent.WaitOne()


Deleting multiple objects with NHibernate using a query

I needed to delete a bunch of objects based on some parameters of those objects. It fairly obvious that one of the Delete overloads on ISession would work, but a couple of things throw me. First you need a full select query, not too hard to figure out. But second, where are IType’s defined? In NHibernateUtil (thanks to this). Anyway, here is some sample code. I’m guessing there might be a more efficient way, but this should work for most cases.



session.Delete(“select b from Bar as b where b.Instrument = :instrument and b.BarMinutes = :barMinutes”,
new object[] {instrument, barMinutes},
new IType[]
{
NHibernateUtil.Entity(typeof (Instrument)),
NHibernateUtil.Enum(typeof (BarMinutes))
});


Brutalist Framework