Generating C# classes from FpML Schema

By at December 26, 2008 05:26
Filed Under:

This problem recently came up while discussing a project that will use FpML documents. FpML is an evolving standard that aims to be the industry standard protocol for complex financial products. Its an extensive project with a good deal of support from major players and a sharp talent pool behind it.

I’ll try to explain how code generation facilities built into the .Net framework can provide us with a basic usable class library that encapsulates the FpML protocol.

We begin by downloading the relevant schemas from the FpML website (requires free registration) and extracting them to a local folder (C:\FpML).

Then we fire up Visual Studio and create a new Console Application. At this point you maybe wondering if it wouldn’t be simpler to just use XSD.EXE for the code generation. Unfortunately XSD.EXE has difficulty resolving external schemas.

using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Schema;
using System.Xml.Serialization;
using Microsoft.CSharp;

namespace ConsoleApplication1
{
    internal class Program
    {
        public const string rootFolder = @"C:\FpML\xml\";

        private static void Main(string[] args)
        {
            XmlSchema rootSchema = GetSchemaFromFile("fpml-main-4-2.xsd");

            var schemaSet = new List<XmlSchemaExternal>();

            ExtractIncludes(rootSchema, ref schemaSet);

            var schemas = new XmlSchemas { rootSchema };

            schemaSet.ForEach(schemaExternal => schemas.Add(GetSchemaFromFile(schemaExternal.SchemaLocation)));

            schemas.Compile(null, true);

            var xmlSchemaImporter = new XmlSchemaImporter(schemas);

            var codeNamespace = new CodeNamespace("Hosca.FpML4_2");
            var xmlCodeExporter = new XmlCodeExporter(codeNamespace);

            var xmlTypeMappings = new List<XmlTypeMapping>();

            foreach (XmlSchemaType schemaType in rootSchema.SchemaTypes.Values)
                xmlTypeMappings.Add(xmlSchemaImporter.ImportSchemaType(schemaType.QualifiedName));
            foreach (XmlSchemaElement schemaElement in rootSchema.Elements.Values)
                xmlTypeMappings.Add(xmlSchemaImporter.ImportTypeMapping(schemaElement.QualifiedName));

            xmlTypeMappings.ForEach(xmlCodeExporter.ExportTypeMapping);

            CodeGenerator.ValidateIdentifiers(codeNamespace);

            foreach (CodeTypeDeclaration codeTypeDeclaration in codeNamespace.Types)
            {
                for (int i = codeTypeDeclaration.CustomAttributes.Count - 1; i >= 0; i--)
                {
                    CodeAttributeDeclaration cad = codeTypeDeclaration.CustomAttributes[i];
                    if (cad.Name == "System.CodeDom.Compiler.GeneratedCodeAttribute")
                        codeTypeDeclaration.CustomAttributes.RemoveAt(i);
                }
            }

            using (var writer = new StringWriter())
            {
                new CSharpCodeProvider().GenerateCodeFromNamespace(codeNamespace, writer, new CodeGeneratorOptions());

                //Console.WriteLine(writer.GetStringBuilder().ToString());

                File.WriteAllText(Path.Combine(rootFolder, "FpML4_2.Generated.cs"), writer.GetStringBuilder().ToString());
            }

            Console.ReadLine();
        }

        private static XmlSchema GetSchemaFromFile(string fileName)
        {
            using (var fs = new FileStream(Path.Combine(rootFolder, fileName), FileMode.Open))
                return XmlSchema.Read(fs, null);
        }

        private static void ExtractIncludes(XmlSchema xmlSchema, ref List<XmlSchemaExternal> schemaList)
        {
            foreach (XmlSchemaExternal include in xmlSchema.Includes)
            {
                if (!schemaList.Select(s => s.SchemaLocation).Contains(include.SchemaLocation))
                    schemaList.Add(include);

                if (include.Schema == null)
                {
                    XmlSchema schema = GetSchemaFromFile(include.SchemaLocation);

                    ExtractIncludes(schema, ref schemaList);
                }
                else
                    ExtractIncludes(include.Schema, ref schemaList);
            }
        }
    }
}

Running this generates the following code:

FpML4_2.Generated.cs (1.10 mb)

Comments

1/28/2010 10:11:19 PM #

James McMorrough

That has got to be one of the most amazing bits of code I've ever encountered.

James McMorrough United Kingdom | Reply

2/4/2010 7:06:20 PM #

xbox купить

hat has got to be one of the most amazing bits of code I've ever encountered.

xbox купить Russia | Reply

2/18/2010 11:15:58 PM #

this website

This was a really great post to read! I thoroughly enjoyed it. Maybe when I get a chance to return I'll read some more.

this website New Zealand | Reply

2/19/2010 2:15:45 AM #

Bo Yu

Hi, Erhan:

I used your program to generate C# classes but I still got a lot of problems when deserialize from XML to C# objects. Some sample errors here:
Unable to generate a temporary class (result=1).
error CS0030: Cannot convert type 'FpML.RoutingId[]' to 'FpML.RoutingId'
error CS0030: Cannot convert type 'FpML.SettlementPeriodsReference[]' to 'FpML.SettlementPeriodsReference'
error CS0030: Cannot convert type 'FpML.SettlementPeriodsReference[]' to 'FpML.SettlementPeriodsReference'
error CS0029: Cannot implicitly convert type 'FpML.RoutingId' to 'FpML.RoutingId[]'
error CS0029: Cannot implicitly convert type 'FpML.SettlementPeriodsReference' to 'FpML.SettlementPeriodsReference[]'
error CS0029: Cannot implicitly convert type 'FpML.SettlementPeriodsReference' to 'FpML.SettlementPeriodsReference[]'

Do you have any solutions for this kind of problems. I know a guy stated if I put all the schema files into one single one the problem would go away even using XSD.exe.

Any help is highly appreciated.

Bo Yu United States | Reply

4/29/2010 4:02:14 AM #

ehosca

i've since moved on to using LinqToXSD to generate classes from FpML.

ehosca United States | Reply

2/22/2010 1:25:51 AM #

Kris

This worked like a charm. Very nice.

Kris United States | Reply

2/26/2010 4:25:22 PM #

Fatcow Coupon

Should I get a Virtual Private Server? Currently I am using ixwebhosting but they keep shutting me down due to high server load. Im getting about 3,000 UV a day. What brand should I get?

Fatcow Coupon United States | Reply

3/2/2010 2:01:38 PM #

wow mobiles

WoW Mobile is awesome! I get free mobile service with t-mobile because I refered 3 people to wow. You can too!

wow mobiles United States | Reply

3/2/2010 4:13:21 PM #

wow mobiles

WoW Mobile is awesome! I get free mobile service with t-mobile because I refered 3 people to wow. You can too!

wow mobiles United States | Reply

3/3/2010 2:59:14 AM #

Bobby

Hey there, are you having issues with your hosting? I needed to refresh the page about four times to your site load. You might want to change hosts, or could the problem be from me?

-Bobby

Bobby United States | Reply

3/5/2010 1:09:02 AM #

Vedeževanje preko interneta

Amazing blog! Its not frequently that I comment but I felt you deserve it

Vedeževanje preko interneta Slovenia | Reply

3/9/2010 1:10:58 AM #

pingback

Pingback from mdavey.wordpress.com

F#: Modelling An IRS Trade Using FpML 5.0 « Tales from a Trading Desk

mdavey.wordpress.com | Reply

3/13/2010 11:21:26 PM #

Surls

Shame on you for creating another terrific post! Awesome stuff, keep up the good work. I see a lot of potential! I wonder if you are an active user with any social networking sites like Digg or Stumble Upon?

Surls United States | Reply

3/14/2010 7:19:05 AM #

general electric cooktop

Hvala vam za dobar post puno hvala

general electric cooktop United States | Reply

3/17/2010 7:37:07 AM #

Tagesgeldkonto

Do not limit yourself. Lots of  authors limit themselves to what they think they can do. Keep in mind that you can go as far as your mind will let you.

Tagesgeldkonto Germany | Reply

3/20/2010 11:36:41 PM #

cheap prom Dresses

. Keep in mind that you can go as far as your mind will let you.

cheap prom Dresses People's Republic of China | Reply

3/22/2010 6:06:03 AM #

kmhugyhv

ub nb uiby uniouyv bnmiunib
<a href="http://werewr.com">werwer</a>

kmhugyhv United States | Reply

3/22/2010 6:06:58 AM #

kmhugyhv

http://www.wer.wr.com

kmhugyhv United States | Reply

3/23/2010 4:43:51 PM #

book summaries

Microsoft Invented really object oriented Language which is easy to handle more flexibility.

book summaries United States | Reply

3/25/2010 10:02:23 PM #

Hardware Reviews

Considerably, the post is really the sweetest on this notable topic. I concur with your conclusions and will eagerly look forward to your  forthcoming updates. Saying thanks will not just be sufficient, for the great lucidity in your writing. I will directly grab your rss feed to stay privy of any updates. Authentic work and much success in your business efforts!

Hardware Reviews Lithuania | Reply

3/30/2010 10:36:02 PM #

High School Fundraiser


You got so many points here,This is such a great resource that you are providing and you give it away for free.Useful information like this one must be kept and maintained so I will put this one on my bookmark list! Thanks for this wonderful post and hoping to post more of this!

High School Fundraiser United States | Reply

3/31/2010 5:13:54 PM #

GRANITE COUNTERTOPS MN

FpML concept of protocol i didn't know so thanks for sharing information

GRANITE COUNTERTOPS MN United States | Reply

4/2/2010 1:23:18 PM #

Brice Klemencic

Nice post, thanks for posting. You've inspired me to get up off the couch!(And that's no small feat!)

Brice Klemencic United States | Reply

4/4/2010 7:23:56 PM #

GRANITE COUNTERTOPS MN

I didn't get this FmPL but i want to details

GRANITE COUNTERTOPS MN United States | Reply

4/6/2010 7:51:29 PM #

essay editing

Hello, I'm interested in being a blogger. But, most people are discouraging me. Is it a lot of work to maintain a blog?

essay editing United States | Reply

4/9/2010 11:27:38 PM #

rumba vacuum cleaner

Hello! I'm in a hurry today.I found this blog while searching for articles to help me compose a report, and found this article to be very interesting. I like it's originality. I've bookmarked your website, and will come back in the weekend to examine more.

rumba vacuum cleaner United States | Reply

4/10/2010 10:56:58 PM #

rid of bed bugs

Thank you for your post. I am researching this subject for a report, and your information is exactly what I've required.

rid of bed bugs United States | Reply

4/13/2010 6:33:08 AM #

world of warcraft easter eggs

Love the Site. I want to start one soon and I want to make it look like this one.

world of warcraft easter eggs United States | Reply

4/13/2010 6:44:56 AM #

business office supply

Great article. I wish I could write so well.

business office supply United States | Reply

4/13/2010 7:52:48 AM #

steel lawn chairs

Wow, I have a blog too but I can't write as well as you do. Good stuff.

steel lawn chairs United States | Reply

4/19/2010 9:20:22 AM #

Liza Tramble

This is so great that I had to comment. I'm usually just a lurker, taking in knowledge and nodding my head in quiet approval at the good stuff.....this required written props. Theory rocks...thanks. Smile

Liza Tramble United States | Reply

4/19/2010 10:30:07 AM #

Darla Picketts

Nice to be visiting your site again, it has been almost a year for me. Anyway, this is the article that i've been searching for so long. I need this article to end my paper in the school, and it has same topic as your article. Thanks, excellent share.

Darla Picketts United States | Reply

4/24/2010 6:58:02 AM #

sample essays

Great web site, thanks for the information.

sample essays United States | Reply

4/25/2010 1:58:17 AM #

matt carter

When ever I come across something like this I have to ask myself, an I in the wrong business? Great!

matt carter Slovakia | Reply

4/27/2010 1:45:53 PM #

Get ripped body

Couldnt be written any better. Reading this post reminds me of my old room mate! He always kept talking about this. I will forward this article to him. Pretty sure he will have a good read. Thanks again for sharing this free online

Get ripped body United States | Reply

5/4/2010 11:37:36 AM #

bus hire

Hey, I reckon your website is decent, I located it in Bing and I'll bookmark it!
Herschel Tenore in  Delaware.

bus hire United States | Reply

5/10/2010 12:04:16 PM #

pingback

Pingback from condosencinitas.com

san diego car insurance

condosencinitas.com | Reply

5/15/2010 3:57:59 AM #

celebrity fashion

I need to extend security in BE just a little. I need to make a user registration form and disable comments for non-registered users. Has anyone done this? What difficulties might arise?

celebrity fashion United Kingdom | Reply

5/17/2010 5:36:12 PM #

Alfredo Monsivais

Hi, Cool blog. I've been looking for work in community services for age and found just reading some stuff here really great. I'm in Australia and i guess the market here is smaller than a lot of other places. I did find one site jobcommunity.com.au which was helpful. They are currently doing an update at the momemnet. people should check them out. Thanks again for the informative read and I look forward to coming back soon.

Alfredo Monsivais Australia | Reply

5/17/2010 5:37:57 PM #

Cheryll Busacca

Thanks for such a cool blog. Working in community services kind of sucks sometimes. I hate finding sites that just have zero info, jobcommunity in Australia i like the only one i've really visited that is any good.

Cheryll Busacca Australia | Reply

5/19/2010 8:39:55 PM #

Post Free Ads | Property For Sale

The posts so far have been great - hoping for some more.

Post Free Ads | Property For Sale India | Reply

5/21/2010 10:26:44 PM #

cause and effect essay topics

It goes like this, a client seeks for a keyword on Google. You make published an article which targets this word and have subjected it to a internet site which Google likes. The customer finds your article on page one, reads it, clicks on your website link,

cause and effect essay topics United States | Reply

5/26/2010 10:59:28 AM #

Fap Turbo Expert Guide

A whole lot of good quality responses thus far. I genuinely enjoy that absolutely everyone seems well-versed in their replies and continues the dialogue productive.

Fap Turbo Expert Guide United States | Reply

5/26/2010 6:16:23 PM #

Packers and movers in pune

many thanks for this worthwhile information I have post a link on my site so my readers can benefit from it too.

Packers and movers in pune India | Reply

5/30/2010 11:32:07 AM #

Brian Edmonston

Thanks for posting!

Brian Edmonston United States | Reply

5/31/2010 3:27:08 AM #

Simon Reeve

Can't complain about what I've got, but i guess you're right, keep writing ;)

Simon Reeve United States | Reply

6/3/2010 11:27:11 PM #

gucci bags

Please, can you PM me and tell me few more thinks about this, I am really fan of your blog...gets

gucci bags United States | Reply

6/6/2010 5:41:05 AM #

Free Xbox Points

Greetings from New Hampshire!  Just came across your posts.  Actually visited your article, I'll pass it along! 3Smile  Have a good day!

Free Xbox Points United States | Reply

6/9/2010 8:27:04 AM #

Dick Todhunter

Some parts of this post are cut off in Safari browser

Dick Todhunter United States | Reply

6/9/2010 10:07:46 AM #

Cuc Brierly

Viral marketing or viral advertising is a marketing strategy that use pre-existing social networks that is to increase a promotion to the some potential customer and to increase the awareness of the brand.

Cuc Brierly United States | Reply

6/11/2010 6:20:21 AM #

Day Trade Forex

Thanks so much putting together this blog. It's packed with great information.  This one is going into my bookmarks.

Day Trade Forex United States | Reply

6/12/2010 10:50:04 AM #

limo hire

Hello, I think the story is lovely, I located it in Bing and I'll be back soon!
Caren Leverentz surfing in  Louisiana.

limo hire United States | Reply

6/14/2010 1:36:03 AM #

hellowallet

Some parts of this post are cut off in Chrome browser

hellowallet United States | Reply

6/16/2010 12:14:41 AM #

Perla Naraine

Hey, Admin, I am starting my own blog, I was wondering which blog platform you are using? Sorry for the noob question and thanks for you help in advance Smile  
BR

Perla Naraine United States | Reply

6/17/2010 8:58:56 PM #

glass etching cream

Hi! I saw your blog at Google and have learned a lot from it. Thank you very much for the useful and detailed posts. Will be coming back soon.

glass etching cream United States | Reply

6/18/2010 5:46:34 AM #

starcraft 2 beta

Any of you guys play PC Games?  If so I don't suppose any of you have been looking into Blizzard's new RTS?

starcraft 2 beta United States | Reply

6/18/2010 6:19:43 PM #

Bea Pechon

Here is the 2nd occasion I have come across your blog post in the last couple weeks.  Looks like I should bookmark it.

Bea Pechon United States | Reply

6/21/2010 9:06:00 PM #

packers and movers india

Nice your Posting...
    Thank You........

packers and movers india India | Reply

6/21/2010 9:15:01 PM #

movers and packers in pune

Great post. I like it.

movers and packers in pune India | Reply

6/22/2010 8:28:19 AM #

starcraft 2 beta

Any of you play Starcraft?

starcraft 2 beta United States | Reply

6/22/2010 8:41:17 AM #

starcraft 2 beta

You guys play RTS?

starcraft 2 beta United States | Reply

6/22/2010 8:53:57 AM #

starcraft 2 beta

You guys play RTS?

starcraft 2 beta United States | Reply

6/22/2010 3:04:52 PM #

Social Security Disability

Found a wonderful firm named Freedom Disability. They can assist you to apply for and win social security disability benefitswith the social security administration.

Social Security Disability United States | Reply

6/24/2010 8:40:16 AM #

Watch UFC 116

I hope they do Liddell Ortiz 3 soon... right now, I can't wait to watch UFC 116!

Watch UFC 116 United States | Reply

6/24/2010 5:29:26 PM #

Custom desktop computers

Had i not stumbled onto this blog, I wouldn't know what i know now. I'm definitely bookmarking this for future reference and sharing it with my friends. Thanks so much for the info here.

Custom desktop computers United States | Reply

6/24/2010 6:34:06 PM #

Refurbished gaming computers

Another great article once again. I love your writing style and how you present your information. You truly are a favourite of mine to read. Keep up the way you do! Thanks!

Refurbished gaming computers United States | Reply

6/25/2010 5:36:18 PM #

Buy computer systems

I wish i could write the way you do sometimes. I'm definitely going to take pointers on how you write and apply it to my own =p. Thanks for all your hard work!

Buy computer systems United States | Reply

6/27/2010 3:52:27 AM #

IT consulting

Thanks for sharing the information.It is definitely going to help me some time.

IT consulting United States | Reply

6/28/2010 2:31:08 AM #

toy drums

Thanks for the info. The web is so full of crap it is becoming difficult to find exactly what you're looking for nowadays. Do you have an RSS feed on this website?

toy drums United States | Reply

6/28/2010 2:50:02 PM #

setiri

I see you are using linq to xsd now, but did you also try xsd2code?

setiri United States | Reply

6/29/2010 3:32:48 AM #

starcraft 2 beta

Any of you play Starcraft?

starcraft 2 beta United States | Reply

6/29/2010 4:06:55 AM #

starcraft 2 beta

Any of you play Starcraft?

starcraft 2 beta United States | Reply

6/30/2010 12:35:22 AM #

Doretta Crosman

Really so nice post.I am always so interested about beauty related niches and now found a new great source for this. Thanks

Doretta Crosman United States | Reply

6/30/2010 1:02:07 AM #

Aleida Dreith

Found your site on yahoo today and really liked it.. I bookmarked it and will be back to check it out some more later.

Aleida Dreith United States | Reply

7/2/2010 6:27:29 AM #

Corene Rodrigez

I've been looking for more information on these types of coupons for some time now.

Corene Rodrigez United States | Reply

7/3/2010 5:29:24 AM #

göğüs estetiği

is there any one who knows any source about this subject in other languages?

göğüs estetiği United States | Reply

7/3/2010 5:41:25 AM #

göğüs estetiği

is there any one who knows any source about this subject in other languages?

göğüs estetiği United States | Reply

7/3/2010 7:06:43 AM #

göğüs estetiği

is there any one who knows any source about this subject in other languages?

göğüs estetiği United States | Reply

7/3/2010 8:51:35 AM #

Shizuko Stormes

Many bloggers are great leader; especially lead their own blog to become the most popular blog in the world. I wonder what you think about this. Many successful bloggers created or made jobs for other people. It is wise idea, I think. We agree that you can become this too. By commenting on your blog, I trust you because I had “blog-walked” to your blog intensively, especially see and check your analysis. It is fantastic! Wonderful thought that you gave to other readers, share the biggest idea, unique thought, and then debate them. For me as learner, it is the most important thing to you and us. I have spent many times, from time to come, and I am sure this is the right time to me to recruit you as a writer, hope you are responsible to your future job. Great time to comment on this page, I am looking forward to chatting or email with you

Shizuko Stormes United States | Reply

7/4/2010 10:20:45 AM #

italian masks

What are you indicating, man? I understand everyones got their own thoughts and opinions, but really? Listen, your weblog is neat. I like the effort you put into it, especially with the vids and the pics. But, come on. Theres gotta be a better way to say this, a way that doesnt make it seem like everybody here is stupid!

italian masks United States | Reply

7/7/2010 10:01:25 AM #

Tanja Briere

Hmm strange this post is totaly irrelevant to the search question  I entered in bing but it was listed on the 1st page.

Tanja Briere Sri Lanka | Reply

7/7/2010 2:52:37 PM #

copper outdoor thermometer

Move out of your comfort zone. You can only grow if you are willing to feel awkward and uncomfortable when you try something new Brian Tracy

copper outdoor thermometer United States | Reply

7/8/2010 6:31:17 PM #

Towing in Smyrnadustin7patel@yahoo.co.uk

This is really great info. Thank you for sharing it with us!

Towing in Smyrnadustin7patel@yahoo.co.uk United States | Reply

7/15/2010 4:09:20 PM #

nike rift

Thanks for posting!

nike rift People's Republic of China | Reply

7/21/2010 9:18:06 AM #

Plastic Membership Cards

I agree with most comments aired above.Thanks

Plastic Membership Cards Australia | Reply

8/9/2010 7:33:43 AM #

Maurine Baumohl

this is just what I was in need of

Maurine Baumohl Japan | Reply

8/10/2010 3:20:23 PM #

Mackenzie Pohler

Helpful site, where did u invent some the knowledge with this posting? I am pleased I discovered it though, ill be checking back soon to see what new articles you have.

Mackenzie Pohler Nigeria | Reply

8/11/2010 6:11:39 AM #

first page of google

hi thank you for this wonderful informative blog

first page of google United States | Reply

8/15/2010 12:46:04 PM #

restaurant city guide

Hey, I just found this article through Yahoo. I enjoy the take cerified by the article. I'm going to subscribe to your feeds aiming to read again. Please if you guys can stop by my website, HackingEdge.com.

restaurant city guide United States | Reply

8/16/2010 6:36:44 AM #

internet income

I don’t agree with most folks here; I started reading this blog post I couldn't stop until I was done, although it wasn't just what I had been searching for, was still a fantastic read though. I will instantly take your blog feed to maintain in touch of any updates.

internet income United States | Reply

8/24/2010 7:11:06 PM #

Jokei

Very nice piece of code. One problem though:

I tried to run this on a different set of schemas, and it didn't work. The problem was that some of the referenced schemas was in sub-directories, and they in turn referenced schemas with a relative path from their location.
This didn't work with your code Frown

I fixed it by making the global "rootFolder" to a parameter in the recursive function and storing absolute paths for all schemas in schemaLocation. This seemed to work, although I'm not certain about possible side effects of setting the schemaLocation myself...

Jokei Sweden | Reply

9/3/2010 1:53:09 AM #

Vehicle Tracking System

Move out of your comfort zone. You can only grow if you are willing to feel awkward and uncomfortable when you try something new Brian Tracy

Vehicle Tracking System United States | Reply

9/4/2010 11:28:23 PM #

TJ

Thanks for the information, it was very helpful.

Regards,
TJ

TJ Lao P.D.R. | Reply

9/5/2010 8:07:22 PM #

Michael from Zero Friction Marketing Review

Promoting CPA offers for me has been one of my best ways to earn money online.  I think this works great for me because I find it easier to convince someone to take a free trial or submit their name and e-mail, rather than actually trying to get them to purchase a product.  While the payout per conversion might be lower with free offers, conversion rates are usually much higher so this offsets the difference.  While pay per sale offers from Clickbank might be a temptation for new marketers, I would strongly suggest starting with promoting free offers, and after gaining internet and affiliate marketing experience, then move to paid offers.

Michael from Zero Friction Marketing Review United States | Reply

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading