Friday, February 25, 2011

[General-Dev]–FluentNHibernate cannot load NHibernate assembly when setup with NuGet

I ran into this issue today after using NuGet for the first time. I started a new project using NHibernate and I wanted to configure my mappings using Fluent NHibernate. NuGet makes setting up your references really easily, by right clicking on my references folder and going to Add Library Package Reference I could easily search for NHibernate and Fluent NHibernate and install them.

image

Very impressive – and certainly much easier than on my last NHibernate project which pushed me into DLL hell to get it setup! But, the DLL pain wasn’t quite gone – when trying to run my project after setting up the mappings I got the following error:

Could not load file or assembly 'NHibernate, Version=3.0.0.2001, Culture=neutral, PublicKeyToken=aa95f207798dfdb4' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

What? Isn’t NuGet meant to save me from this? well, turns out that it does, but I have to give it a push. To work around this, I had to open up the Package Manager Console (Tools > Library Package Manager > Package Manager Console) and typed the following:

Add-BindingRedirect

This redirects the bindings to the newer version of NHibernate which was installed by NuGet, whereas the Fluent NHibernate references was pointing to a slightly earlier build. I’m not sure why NuGet doesn’t do this by default, but this Stack Overflow answer seems to suggest they will do this soon.

Monday, February 21, 2011

[General-Dev]–Visual Studio Colour Schemes

I previously posted about my usage of a dark colour scheme for Visual Studio 2008. I find darker colour schemes a lot easier to stare at all day than the white background ones. However I recently ran into an issue with the scheme I was using. I started using the new ASP.NET MVC Razor View Engine for my mark-up, and it appears my colour scheme had not been setup for it, so I was getting some pretty horrible colour combinations.

I went online to find an updated theme and I came across this great website: http://studiostyl.es/. It features a nice clean gallery of various visual studio styles, which are tagged and rated. I ended up choosing WekeRoad Ink, which was very easy to install. Here’s how you do it:

First, download the vssettings file from studiostyl.es by clicking ‘Download this scheme’ then in Visual Studio go to Tools > Import and Export settings. Choose ‘Import selected environment settings’

image

Click next, and on the next screen select where to save a backup of your current settings

image

Click next, hit browse and find the vssettings file you downloaded

image

Hit next and then finish, and your settings will be imported and setup. If you don’t like them and want to swap back, simply import your backed up settings over the top of them.

Saturday, February 19, 2011

[General .NET]– DispatcherTimer is the WPF equivalent of Windows.Forms.Timer

In making the switch from Windows forms to WPF you may come across a situation where you want to do a certain action at a specified interval of time. In Windows Forms, the Timer class handled this situation for you, and in fact, if you really wanted to you could import the namespace and use the same class in your Windows Forms application – but this is not ideal, as the Timer class is optimized for use in a Windows Forms Window.

So, instead, use the System.Windows.Threading.DispatcherTimer class, which can perform a similar duty, but is optimized for use with WPF. It runs on the same thread as it’s dispatcher, so it is optimized for updating the UI – if you have large amounts of work to do, you should use a separate thread, or the BackgroundWorker class.

The two classes are very similar, though one difference to be aware of is that the Timer class’s Interval property is measured in milliseconds, where the DispatcherTimer uses an actual Timespan object, which measures time in ticks. Make sure you keep that in mind otherwise your actions may be performed more regularly than you expected.

To read more about how to use the DispatcherTimer and BackgroundWorker classes to build responsive WPF applications, check out this MSDN article.

Tuesday, February 15, 2011

[ASP.NET]–How to dynamically hide ListView LayoutTemplate headings

This is a very web forms specific technique that I needed to use on a project recently. I had a ListView control which had a LayoutTemplate similar to this:

<LayoutTemplate>
        <table class="staffList">
            <thead>
                <tr>
                    <th>
                        Name
                    </th>
                    <th runat="server" id="CountHeading">
                        Count
                    </th>
                </tr>
            </thead>
            <div id="itemPlaceholder1" runat="server">
            </div>
</LayoutTemplate>

I was hosting this inside a User Control where I had a property that would turn the display of the Count column on and off (named ‘ShowDetails’). It was easy for me to not display the count data for each Name, but the headings would stay there.

What I needed to do was add the runat=”server” id=”CountHeading” attributes to the th element in my LayoutTemplate as above, and then subscribe to the OnLayoutCreated event in the ListView

OnLayoutCreated="OnLayoutCreated"

Then in the OnLayoutCreated method I did the following:

protected void OnLayoutCreated(object sender, EventArgs e)
{
    if (!this.ShowDetails)
    {
        this.StaffListView.FindControl("CountHeading").Visible = false;
 
    }
}

This uses the FindControl method to find the control by its ID. Because I added runat=”server” to the th tag, it becomes a server side control and can be modified in such a way.

Sunday, February 13, 2011

[Housekeeping]– New Revit only RSS blog feed available

Many of you may be reading this post via an RSS feed reader from the blogs main feed. If you are reading the blog purely for the Revit API content, and don’t want to see my posts on other programming topics, I’ve created a custom RSS feed that will only display blog posts that are labelled ‘Revit’.

You will now see to the right of my blog:

Subscribe to all posts
Subscribe only to Revit related posts

Feel free to update your reader to the Revit only post if you wish. I am planning on adding more and more posts on other development topics, including ASP.NET MVC and mobile application development (Android initially, but perhaps IOS later on). If you aren’t interested in these topics, register to the Revit only feed!

[Revit API]–Introduction to VSTA as a rapid prototyping tool

At Autodesk University in December some of the Autodesk Revit API team were mentioning that they thought VSTA was a little underappreciated by Revit API developers, and that it is a very useful too, particularly for working things out before turning them into fully fledged applications.

I must say that I’ve always steered clear of VSTA, for a number of reasons, firstly it used to lack a few features, and secondly that I’ve always preferred the full Visual Studio professional as I can use plugins like the wonderful Resharper plugin. However, there are disadvantages to this, namely that you generally have to reboot Revit after each code change. I’ve purchased a good quality Solid State Drive in order to make Revit boot quickly, which has made this disadvantage bearable, and there are some techniques to try and avoid restarting Revit all the time but it’s still not ideal.

Enter VSTA. I recently decided to give it a try to quickly answer a question someone asked me via email. To get started using it, you need to install it from the Revit disk. After this, you should be able to open a document and go to the Manage ribbon tab and go to ‘Macro Manager’. This is somewhat confusing, as all non VSTA addins go in the ‘addins’ tab.
image

You will then see the Macro Manager, which lets you create either an Application level macro, or a Document level (ie the code is included in the actual Revit file you have open). To do some rapid prototyping we’ll create a document level macro by clicking on the tab that is named the same as your Revit file.
image
Here you’ll see a couple of tools I’ve made, to create a new one click ‘Create Module’ which opens a dialog box asking you to name your new Module.
image

This create a new module in the list.
image

Click on it, then Click Create ‘Macro’.
image

This will create a new instance of VSTA, which is a cut down version of Visual Studio 2008.
image

You can see here it has created a HelloWorld method which represents your macro, in addition to that there’s the usual Attributes you’d see on an External Command, and also the AddInID GUID is created – no need for you to set this up. There’s also Module_Startup and Shutdown methods which let you run some code which happens before or after every macro in the module. For now, we’ll just concentrate on the HelloWorld method.
To show a simple dialog box, first we need to import the Autodesk.Revit.UI namespace at the top, and then we can add in our Task Dialog code:

public void HelloWorld()
{
    TaskDialog.Show("Hello World","Hello World");
}

Now, to run this code first we need to build it, go to Build > Build Example. Then swap back to the Macro Manager and you’ll see the Example module can be expanded out to see all the macros underneath it.
image

We can select that macro and click ‘Run’ to run it, or Step Into if we want to debug it.
image

As you can see it works fine. Now lets create one that does something a little different. Say we have a detail line on our document, like one from my previous post that creates a detail line:
image

And we want to know how to access the length of it in millimetres through the API. Here’s a workflow we can use to do that.
First, create a new macro under the Example module called GetLength

image

You should see it creates another public void for that macro. (You can create macros just by creating the methods yourself if you like)

image

Now, we want to figure out how to access the length. If you have two monitors (if you don’t, you should!) put the VSTA code on one window and on the other, select your detail line. To work out how to access this value, we can use RevitLookup, if you haven’t installed it, grab it from the SDK and install it – it’s essential for Revit API development.
Go to the add-ins tab, go to Revit Lookup and snoop the current selection. You’ll see the API’s view of this element

image

Click on the ParameterSet and you’ll see there is a parameter called Length.
image

This is what we want to access. Swap to the other window, and lets access it via code. First off, we’ll  have to reference the Autodesk.Revit.DB namespace. Then, we need to get at both the Document and UIApplication objects. To do this in a VSTA macro, you can use this.Document and this.Application. However rather than writing this each time in the code, I like to extract these to a variable. That way if the code I’m prototyping here ends up as a full API tool I can easily move it to a Visual Studio solution.

public void GetLength()
{
    Document doc = this.Document;
    UIApplication app = this.Application;
}

We’ll use the currently selected element as a way of getting to the detail line, then we’ll read through its parameters looking for the length, and display it in a TaskDialog.

public void GetLength()
        {
            Document doc = this.Document;
            UIApplication app = this.Application;
 
            foreach (Element selectedElement in app.ActiveUIDocument.Selection.Elements)
            {
                if (selectedElement is DetailLine)
                {
                    //the selected element is a detail line, so cast it to one.
                    DetailLine line = (DetailLine)selectedElement;
 
                    //loop through all the parameters
                    foreach (Parameter parameter in line.Parameters)
                    {
                        if (parameter.Definition.Name.ToLower().Equals("length"))
                        {
                            //found the length parameter
                            TaskDialog.Show("Length", parameter.AsValueString());
                        }
                    }
 
                }
            }
        }

To run this, go to Build > Build Example and then swap back to Revit, head into the Macro Manager and run your macro. As long as you have the line selected you should see the result flash up
image

Now you know how to access the length, you’ve experimented in VSTA, and you can convert this code over to your full blown Revit add-in that you have been working on, or planning to work on.

This has saved us a fair bit of time, instead of creating a new Visual Studio project, setting up our entry class, referencing the API, adding the transaction and regeneration attributes (and probably forgetting to do that once, starting Revit, having an error and then having to exit again), setting the references to not copy, setting up an addin manifest file, creating an addinID GUID etc we’ve just opened VSTA, and with the document still live in front of us we’ve written our code and tested it.
While it may not be so convenient when creating a comprehensive Revit addin, I believe VSTA is certainly very handy when just doing some trial and error coding to work out how to access things through the API.  For more examples on how to use VSTA, see the VSTA samples folder in the Revit SDK.

Saturday, February 12, 2011

[Revit API] – How to draw a detail line on a view

I got asked a question similar to this so thought I’d post it up. To draw a detail line on a view, from one point to another, you first need to create a ‘Line’ and then a ‘DetailCurve’.
This may be a little confusing, but a ‘Line’ is not the actual end result, it’s a geometry object that represents where the line will go. To actually draw the line you need to create a DetailCurve, which is the actual Detail Line.
Here’s the code that I’m talking about:
//Create the Points
double x1 = 5.0;
double y1 = 5.0;
double z = 0.0;
double x2 = 117.0;
double y2 = 115.0;
XYZ point1 = app.Application.Create.NewXYZ(x1, y1, z);
XYZ point2 = app.Application.Create.NewXYZ(x2, y2, z);
 
//Create line
Line line = app.Application.Create.NewLineBound(point1, point2);
DetailCurve detailCurve = doc.Create.NewDetailCurve(doc.ActiveView, line);
 
TaskDialog.Show("Done", "Line Created");
First off, we are setting up the XYZ for each point that we are going to draw between. These are points in the model. Then we use the NewLineBound method to create a bound line in space between point1 and point2. If you just stopped here, you would see nothing in your model. To actually draw the Detail Line you use the NewDetailCurve method to specify which view you want to draw the line on, and the line that represents it’s geometry.
To run the code you’ll need to be in a transaction (or use Automatic transaction mode), and need to initialize the app and doc variables as you normally would. When you run the tool, the final result is this:
image
A simple line drawn on the page.

Wednesday, February 9, 2011

[General-Dev]–Getting NHibernate configuration to work with Web.Config transformations

Web.config transformations are a great new feature of Visual Studio 2010. They let you have a base Web.Config file, and then make modifications to it based on wether you are in a Debug or Release configuration. This simplifies scenarios such as using a test database in debug mode. You can read more on this feature on MSDN.
I’m currently using NHibernate on an ASP.NET project, and wanted to use web config transformations to swap the databases that I am using. To do this, I setup the nhibernate configuration sections in the web config as per usual, that is, similar to this:
 
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
  <session-factory name="PmqccSessionFa ctory">
    <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
    <property name="connection.connection_string">
      Data Source=SQL_SERVER;Initial Catalog=TEST_DATABASE;Integrated Security=SSPI;
    </property>
..... etc 
Here I setup using my test database details, and then in the web.release.config I chose to replace these with the real database.
 
<hibernate-configuration>
  <session-factory name="PmqccSessionFactory" >
    <property xdt:Transform="Replace" xdt:Locator="Match(name)" name="connection.connection_string">
      Data Source=SQL_SERVER;Initial Catalog=REAL_DATABASE;Integrated Security=SSPI;
    </property>
  </session-factory>
</hibernate-configuration>
However this did not seem to work – after pulling my hair out for a while, this stack overflow post helped me to find the solution. It appears the problem is to do with the xmlns attribute on hibernate-configuration. It conflicts with some part of the transformation procedure.
To solve the issue, I tried to remove the namespace attribute, which appeared to work when I deployed it, but then I ran into some issues with cassini not using the hibernate configuration from the web.config and instead looking for nhibernates own config xml file.
In the end, the solution was to go to my web.release.config file and add the following to the <configuration> tag:
xmlns:hib="urn:nhibernate-configuration-2.2"
this declares the hib: prefix on tags to relate to the hibernate namespace, so then I updated my hibernate transformation code to be
<hib:hibernate-configuration>
  <hib:session-factory name="PmqccSessionFactory">
    <hib:property xdt:Transform="Replace"  xdt:Locator="Match(name)" name="connection.connection_string">
      Data Source=SQL_SERVER;Initial Catalog=REAL_DATABASE;Integrated Security=SSPI;
    </hib:property>
  </hib:session-factory>
</hib:hibernate-configuration>
and all worked correctly.

Monday, February 7, 2011

[General IT]–How to export the ‘on behalf of’ address of all emails in a folder in Outlook

We recently hired a new I.T. assistant at Bornhorst + Ward, and I wanted to email everyone who applied for the job to let the know the position was no longer available. I had all the application emails in one folder, and just needed to extract the email addresses.

If the emails were sent direct to me, that is easy to do, you can do it using the import and export wizard.

Just go to export to a file

image

Choose CSV

image

Select the folder

image

Name the CSV

image

and you are done, open it in excel and you have the addresses.

But, a number of applications came through a web based job advertisement board, which sends the emails from ‘do-not-reply@jobboard.com on behalf of the-real-person@emailserver.com’. Unfortunately this information seems really hard to get to in outlook. You could hit reply on each email one by one, but the import and export wizard, and the field chooser both don’t give you access to this.

Luckily, there is a free export add-in which can do it. CodeTwo Outlook Export is available from their website, download the 32bit or 64bit version based on what version of Office you installed – probably 32bit and install it.

You can then go to the folder and hit the tiny export button

image

Click the ‘add’ button to select a new field and choose ‘Sent on behalf of (address)’

image

Then just follow the wizard, and you’ll have a CSV file with the actual address for you to email.

[Revit API]–Hide Warnings in Revit using the API

The general rule ever since the Revit API was released, is that whatever you can do in the API, you can also do through the normal user interface.

In recent versions I’ve come across a few different examples of where the API is starting to let you do some things you can’t do through the interface (as far as I know – there may be a way I am missing!). One such example is interacting with warnings.

Revit 2011 introduced the new Failures API. This API lets you do two things:

1. Create new warnings within Revit

2. Respond to warnings reported by Revit.

I’m going to discuss option 2 today through a quick example. Lets say that you have a burning desire to place two walls in exactly the same position. Normally when you do this in Revit, you’ll get a warning that looks like the following:

image

Which you can ignore. This is a bit of a silly example, but in many offices there may be warnings in Revit which you ALWAYS accept, and therefore having them in the warnings menu simple messes up the signal to noise ratio, and could mean that real warnings get lost in the crowd.

To stop this warning from displaying, we can make use of the new failures API. To do this, we use an event called the FailuresProcessing event, so as per usual with events we need to make a new ExternalApplication and subscribe to that event:

 

public Result OnStartup(UIControlledApplication application)
{
    application.ControlledApplication.FailuresProcessing += ControlledApplication_FailuresProcessing;
    return Result.Succeeded;
}
 
public Result OnShutdown(UIControlledApplication application)
{
    application.ControlledApplication.FailuresProcessing -= ControlledApplication_FailuresProcessing;
    return Result.Succeeded;
}

Whenever Revit does its failures checks, which is at a number of points in time, including after making our wall, or when opening the warnings menu, our ControlledApplication_FailuresProcessing method will get called.

void ControlledApplication_FailuresProcessing(object sender, Autodesk.Revit.DB.Events.FailuresProcessingEventArgs e)
   {
       FailuresAccessor accessor = e.GetFailuresAccessor();
       IList<FailureMessageAccessor> messages = accessor.GetFailureMessages();
       foreach (FailureMessageAccessor failure in messages)
       {
           FailureDefinitionId failId = failure.GetFailureDefinitionId();
           if (failId == BuiltInFailures.OverlapFailures.WallsOverlap)
           {
               TaskDialog.Show("Deleting Failure", failure.GetDescriptionText());
               accessor.DeleteWarning(failure);
           }
       }
   }

In the code above, you get an object of type ‘FailuresAccessor’ which, funnily enough, lets you access the failures.

Then you can get all of the failure messages and loop through them, then I use the BuiltInFailures listings to match the unique ID of each failure with the one that I’m looking for, that is BuiltInFailures.OverlapFailures.WallsOverlap. The WallsOverlap property simply returns a FailureDefintionId which is used when a WallsOverlap failure is added, so by comparing this with our ID we can find the failures we are after.

If they match, I’m showing a task dialog (you may like to remove this, it’s just there for demonstration purposes) and deletes the warning.

If you load Revit and try to create walls again you’ll see:

image

and you won’t get the Revit warning. Take out the call to task dialog and you’ll always have the warning deleted silently – meaning it’s never displayed to the user. Fairly quickly and easily you can remove a certain failure from the list, and as long as your ExternalApplication is running in the background it will never show up.

This can only be used for warnings, so errors can’t be simply deleted, however the Failures API has some neat options to do with automatically resolving errors, but that’s a topic for another day.