How do you retrieving the XmlEnumAttribute values for an Enum

January 8, 2010 06:27 by bryan

When you are playing with Web Services you quite often find information held in an Attribute, but how do you get it out?

e.g.

public enum Classification {

        [System.Xml.Serialization.XmlEnumAttribute("Test drive demonstrator")]
        Testdrivedemonstrator,

        [System.Xml.Serialization.XmlEnumAttribute("Showroom vehicle")]
        Showroomvehicle,

 

By using reflection you can gain access to the attribute, here is how:

Type enumType = typeof(velocityUom);

foreach (FieldInfo fi in enumType.GetFields())

{

object[] attrs = fi.GetCustomAttributes(typeof(XmlEnumAttribute), false);

if (attrs.Length > 0)

{

Console.WriteLine(((XmlEnumAttribute)attrs[0]).Name);

}

}

 


Building up an MVC application

June 10, 2009 11:35 by bryan

When you open up MVC out of the box, you get the basic configuration, after a little playing around you soon see areas that require enhancing to, not only make your application more flexable, but also easier to maintain.

Here are a number of additional tasks you can perform that will help with your application.

Which IoC to use?

Don't worry, if you use the Common Service Locator it provides an adstraction over the IoC

How to validate?

I have already covered this one in a previous post, but I'd still go with xVal

Need to generate Themes?

I think it is so important to start correctly and generating the User Interface should be configurable, the easiest way of doing this is to implement a Theme, and Chris Pietschmann has do this for us, Implement Theme Folders using a Custom ViewEngine

Here is a copy of the source for safe keeping.

ASPNETMVC_Preview5_CustomThemeImplementation.zip (226.05 kb)

Need Ajax to work in MVC

Ajax.BeginForm and PartialViews

Extend the UrlHelper

Placing all your assets in one place is not only a good idea, but it also means you can be more flexable if you want to programmically change the theme of your user interface.

 

 

Which can be used like this:

Using Strongtypes and keep away from Strings

It appears so easy with MVC to use String everywhere, just DON'T, generate an extension for the UrlHelper

Now in your view it will look like this

Testing

I've been hit before by Microsofts in build Testing within Visual Studio 2008, great to have this feature built in, BUT, and a big but in order to run the tests you need to have Visual Studio install, so if you try and setup a Continuous Integration server you will also be required to install Visual Studio.

So best to go with what works well and that is nUnit, simple and easy, and more importantly loosely coupled

Mocking

With testing comes Mocking, and which framework do you use?  I also always say keep it simple and easy, so I'm going with Moq, short for "Mock-You", as this is the only Mock Framework that is built around .Net 3.5 and LINQ.

 

 


Continuous Integration

May 20, 2009 11:17 by bryan

Task today is to decide and implement an Continuous Integration build process, I will be looking at two options CruseControl and Team City.  The are a lot more but for the purpose of the current .NET environment these are the two I'll be looking at.

When working in a team, the developer needs to know that any changes he makes and stores in to your repository will work for others.  When the developer submits code to the repository they must first update their code to reflect the changes in the repository since they took their copy. The more changes there are to the repository, the more work the developer must do before submitting their own changes.

Eventually, the repository may become so different from the developer's baseline that they enter what is sometimes called, "integration hell," where the time it takes to integrate is greater than the time it took to make their original changes. In a worse case scenario, the changes the developer is making may have to be discarded and the work redone.

Continuous Integration is the practice of integrating early and often, so as to avoid the pitfalls of "integration hell". The ultimate goal is to reduce timely rework and thus reduce cost and time. When done well, continuous integration has been shown to achieve these goals.

After speaking and Googling for each of the products, I quickly came to the  conclusion that although a number of clients I have work with before have been using CruseControl I have found it quite hard to setup and the configuration of XML configuration files can be a bit of a nightmare, and as such we just need a tool to work and not have to maintain.  So for the rest of this article I will be focusing on Team City by JetBrains.

I will be using version 4.5.1. TeamCity-4.5.1.exe (231 mb)

What I like about this product is the licensing, currently the Professional version is free for up to 20 users and 20 build configurations, and when the project get larger you purchase an enterprise license, currently £1,560, ideal way of working and getting you to use the produce.

It's worth watching this short introduction video from Dime Cast, to find out how easy it is to create and use Team City.

The Server automates the integration process by monitoring the team's source control repository directly. Every time a developer commits a new set of modifications, the server will automatically launch an integration build to validate the changes. When the build is complete, the server notifies the developer whether the changes that they committed integrated successfully or not.

Effectively, integration becomes as easy as checking in code. Using an automated integration server not only makes integration easy, it also guarantees that an integration build will happen. There is no danger of developers forgetting to validate their changes after checking in.

The Team City offers several key features:

• Integration with a variety of Source Control systems

• Integration with other external tools, such as NAnt and Visual Studio

• Can build multiple projects on one server

• Remote management and reporting

So down to the installation, once downloaded (231mb file), I installed using all the default settings and it worked, very easy to setup.

Next was to setup a project, again quite easy, I was attaching to a Visual SourceSafe (VSS) solution, I ran in to my first issue as I was getting directory authentication failed.  This was because the running "TeamCity Web Server" was using my System login and it did not have permissions to the network drive for the VSS.  A quick change to the TeamCity Build Server service login and it all worked.

I ran the build on a simple project and it worked without a hitch.

Next was to install the System Tray Notifier, quite simple, going to the "My Settings & Tools" tab brings a list of download, after a simple download and run, then pointing the HTTP location of the Team City installation, it worked.

What can I say it's all just too easy to setup.

Pre-tested Commit

One issue I had, but not with Team City, is that if you are using MS Test, the built in Visual Studio 2008 testing tool, then you will need to run MS Test.  But to run MS Test it is tightly coupled with Visual Studio.  Which means to run MS test you'll need to install a version of Visual Studio on your Continous Intergration machine.  Therefore it might be worth using NUnit for testing.

One very nice feature of Team City is the ability to perform a Pre-tested Commit, this is possible when you install the Visual Studio Addin

An approach which prevents committing defective code into a build, so the entire team's process is not affected.

Submitted code changes first go through testing. If it passes all of the tests, TeamCity can automatically submit the changes to version control. From there, it will automatically be integrated into the next build. If any test fails, the code is not committed, and the submitting developer is notified.

The TeamCity plugins for IntelliJ IDEA, Microsoft Visual Studio 2005/2008 and Eclipse extend the respective IDE with the remote run and pre-tested commit features. Developers test their changes by performing a Remote Run. A pre-tested commit is enabled when commit changes if successful option is selected. 

 

Reference

http://en.wikipedia.org/wiki/Continuous_Integration

Beyond Continuous Integration: Continuous Monitoring with Owen Rogers

Setting up CruiseControl.NET to be a Continuous Monitoring Server

http://www.stevetrefethen.com/blog/archives.aspx#Continuous+Integration

http://www.stevetrefethen.com/blog/CCNETBasedEDIInvoicingProjectGoesIntoProduction.aspx

http://sourceforge.net/project/showfiles.php?group_id=71179&package_id=83198

http://ccnetconfig.codeplex.com/

http://ccnetbuildstation.codeplex.com/


How to sort a generic List

May 19, 2009 09:34 by bryan

I came across a little issue today, in that I had an Interface object and I needed to be able to sort the list, I would normally implement the IComparable interface on the concreate type, but I don't have access to the concreate type in my case.

I tried several different methods in the end I ended up with using a delegate, and found in SimoneB Blog, which I have extracted the content below:

Sorting a generic List<T> is pretty straightforward if you know how to do it. With C# 2.0, anonymous methods come at hand, as well as the little known Comparison<T> delegate (check out this post for more information about this class as well as other useful classes new to C# 2.0).

Ok, let's suppose we have a product class (let me save some space by using C# 3.0 syntax).

 

class Product

{

    public int ProductID { get; set; }

    public string ProductName { get; set; }

    public decimal UnitPrice { get; set; }

}

When we have a list of products we may want to sort it on the ProductName property before displaying it to the user. This can be accomplished with the Sort method of the List<T> class, which defines several overloads. The most handy in this case is the Sort(Comparison<Product>) method and the result is easily achieved with a couple lines of code.

 

List<Product> products = new List<Product>();

 

products.Sort(delegate(Product p1, Product p2)

              {

                  return p1.ProductName.CompareTo(p2.ProductName);

              });

So far so good, but what if we need to sort our list in several places during the execution of our program? Do we have to write that code each time? Actually no, since we can use the parameterless Sort() method of our list class. What this method does is use the "default comparer" to sort the list. So what's this default comparer? It's the comparer that's automatically created if we implement the IComparable<T> interface. This way we can centralize the sorting logic into our class, and just call the parameterless Sort() method on it whenever we need it sorted on the ProductName property.

 

public class Product : IComparable<Product>

{

    [...]

 

    public int CompareTo(Product other)

    {

        return ProductName.CompareTo(other.ProductName);

    }

}

Ok, now what if we want to be able to sort it on the other two properties, ProductID and UnitPrice? Do we have to write an anonymous method each time as we did in the beginning? Of course no, since there's a useful trick which prevents us from needing to do that. We can define two static Comparer<Product> properties in our product class, and supply them as parameters to the Sort(Comparer<T>) method of our list whenever we need it sorted on something which is not the default sorting logic.

 

public class Product : IComparable<Product>

{

    [...]

 

    public static Comparison<Product> PriceComparison =

        delegate(Product p1, Product p2)

        {

            return p1.Price.CompareTo(p2.Price);

        };

 

    public static Comparison<Product> IDComparison =

        delegate(Product p1, Product p2)

        {

            return p1.ProductID.CompareTo(p2.ProductID);

        };

 

    [...]

}

Since they are static they can be used simply like so: products.Sort(Product.PriceComparison) or products.Sort(Product.IDComparison), which will respectively sort the list by price and id.

 

Below is the full code of the Product class.

 

public class Product : IComparable<Product>

{

    private int id;

    private string prodName;

    private decimal price;

 

    public static Comparison<Product> PriceComparison = delegate(Product p1, Product p2)

                                                        {

                                                            return p1.price.CompareTo(p2.price);

                                                        };

 

    public static Comparison<Product> IDComparison = delegate(Product p1, Product p2)

                                                     {

                                                         return p1.id.CompareTo(p2.id);

                                                     };

 

    public int ProductID

    {

        get { return id; }

        set { id = value; }

    }

 

    public string ProductName

    {

        get { return prodName; }

        set { prodName = value; }

    }

 

    public decimal UnitPrice

    {

        get { return price; }

        set { price = value; }

    }

 

    public Product(int id, string prodName, decimal price)

    {

        this.id = id;

        this.prodName = prodName;

        this.price = price;

    }

 

    #region IComparable<Product> Members

 

    public int CompareTo(Product other)

    {

        return ProductName.CompareTo(other.ProductName);

    }

 

    #endregion

 

    public override string ToString()

    {

        return string.Format("Id: {0} Name: {1} Price: {2}", id, prodName, price);

    }

}



Well all love a good Hack

May 18, 2009 09:53 by bryan

Been playing around with this hack for some time, it's fun, I can't remember where I first got the application from, but I've had some harmless fun with it in the office.

This small hack allows you to write information to most HP printers LCD screen.

HPHack.zip (6.49 kb)


Copy one object to another Object

May 15, 2009 13:43 by bryan

I was in need to copying one concreate object to another concreate object, but I needed the flexability that when a new property is added the method would not need to be changed, also I needed the ability for the method to take in any types.

So the first take was to generate a method that uses reflections to go over the obecjts properts and set the returning object properties.  That was quite simple, then to make the method more flexable I used generics to help with my method, to allow for any types to be used.

One thing to note is that you require the try catch, in case the GetValue or SetValue fails, such as if the object is null.

This is what I ended up with.

Here is the VB.NET method

Here is the C#

 


PDB, what and why?

May 14, 2009 13:17 by bryan

If you are like me when you are developing you create a Debug version of your application and in turn .NET provides you with .PDB files for debugging, that is as far as I know, want to know more about it then take a look at John Robbins' Blog on PDB files: what every developer must know


Only get the data that is needs to be displayed

May 12, 2009 09:58 by bryan

I have been on the look out for the ability to display and search a customers database, but having the ability to display millions of records if that what the end users wants.  But the trouble is that it can take a long time to return a million records from a data source.

I've talked about paging before in my article LINQ-to-SQL-and-Paging, which works fine for internet based paging, but what about WPF and WinForm Grids, well I came across Vitrual Mode for the Microsoft Data Grid, which can provide an answer.  What this allow you to do is, load the data you can see on the screen very quickly and as you scroll through the data is fetched when required.

By setting the VirtualMode = true for a data grid, it allows you to add a handler for deail with CellValueNeeded 

Here is the main body of the code

Each time the Data grid needs some values it will call the following:

And of course the NameListCache class

 

I have attached the source, you will also find a PopulateData project to populate the database with data.

 

DataGridViewVirtualModePaging.zip (19.43 kb)

PopulateData.zip (11.43 kb)

Here are a few of the database scripts that yu will need for the sample

Names.sql (581.00 bytes)

GetNames.sql (786.00 bytes)


Caching from a non Web applications

February 6, 2009 08:30 by bryan

Okay you are developing a WinForm application and you are looking at performance, one area is Caching of information, but wait a minute I've been using caching in my web applications for sometime, but how do you do it from a WinForm application as you don't have a host to store your cache.

Would you know it you can use the web cache too, just you have to take a few extra steps to retain your cache, either in memory or in temporary files.

You can use the HttpRequest to store the System.Web.Cache objects in your application, and this works well.

I also came across any Blog, providing another method to Caching, however I have a little concern over this method of caching in files as you are likely to get file locking.

Using System.Web.Caching From The Console Or Windows Forms

I've written my own simple VB.NET application to show it working and just holding the Cache in memory for the life of the application.

WinFormCache.zip (17.73 kb)

Of course you could run a Windows Service which holds all the Cache information, this way it will be available to all your WinForm applications should you require it.


How to create a Carousel in a webpage

December 22, 2008 10:17 by bryan

The latest fad is to create Carousels to display images, and allow for easy navigation.  I have not been able to find any .NET controls to enable you to create a Carousel on a web page.

 

So I set myself the task of generating a web page control to allow for easy, managed code, configuration of a Carousel Control in .NET

First I went on the hunt for a simple javaScript Carousel that I could use, I found a lovely Carousel by Doug Greenall, the information on his blog goes in to great detail of how the Carousel works, but this was not intention to go in to detail about the inner working of a Carousel.

So I downloaded Doug Greenall's Carousel and then went to adapt the javaScript code to create a single DLL Control that could be reused.

The end product is a small DLL that can be dragged and dropped in to your ASP.NET application or Website

Carousel.dll (21.50 kb)

The project solution was generated using Visual Studio 2008 Pro,with a Target Framework of ".NET Framework 2.0"

Carousel.zip (191.73 kb)

 

How to use the Carousel

Okay, so now I've built the Carousel Control, you now want to to know how to use it?

  • First create a new WebSite
  • Add the Carousel.dll or a project reference to your website
  • On the web page register the control (or add it to your web.config)

  • Then add the control to the page, as seen below

 

  • Next in the code behind you need to add to the CarouselDetail collection, which will add the images, links to the Carousel

 

And that is it, the more you add to the CarouselDetail collection the more items will appear on the Carousel.