Blogs

Gary's Blog

  • JSON Serialisation with XPO and JSON.Net

    JSON, or javaScript Object Notation, is a lightweight, data interchange format, it also seems to have become the defacto standard for serialising and deserialising information when talking to web based APIs such as Twitter and Foursquare.

    So far so good, but here’s the thing, I DON’T CARE! When I’m using the API of a web based service I’m doing so because I’m trying to solve a business problem. In the case of Twitter, I might want to know who is talking about me and my product, and what are they saying. I may also want to save that data away in a database for future analysis. That’s the problem I want to solve, so I don’t care about JSON and don’t care about the database.

    Luckily DevEpress’ ethos is to remove the pain of boilerplate or plumbing code from you and so we can use XPO and a third party JSON library, in this case JSON.net, to allow us to concentrate on the problem in hand. So, because as developers we’re doers and not talkers, let’s stop talking about it and have a demonstration.

    Let’s suppose we want to get a feel for the “word on the ground” from the current BUILD conference, Twitter is the natural place to look. There is a search API we can use so let’s try it out:

       1: static void Main(string[] args)
       2: {
       3:     string jsonString = 
       4:         new WebClient().DownloadString(
       5:             @"http://search.twitter.com/search.json?q=bldwin");
       6: }

    Here we are using the Twitter API to search on the hashtag for BUILD. Putting in a breakpoint and inspecting the return shows what we get back from Twitter:

    image

    Yeah, ewww, I don’t want to have to deal with that. Time to recruit JSON.Net. Download the binary and reference it in you project and now we can turn the JSON into object, ‘cos we love objects, right?

    Okay, so the first thing we have to do is to create an object for JSON.Net to deserialise this stuff into. Let’s do the simplest thing that works. Looking at the JSON above we can see that there is a wrapper object that contains the results. Let’s deal with that first. For reasons that’ll I’ll get into further on, we are going to be interested in the next_page property, so let’s build an object that can store that. Something like this…

       1: namespace XPO_JSON_Blog
       2: {
       3:     public class ResultsWrapper
       4:     {
       5:         public string Next_Page { get; set; }
       6:     }
       7: }

    Now, we can go ahead and deserialise the JSON, to this object, using JSON.Net…

       1: using System;
       2: using System.Collections.Generic;
       3: using System.Linq;
       4: using System.Text;
       5: using System.Net;
       6: using Newtonsoft.Json;
       7:  
       8: namespace XPO_JSON_Blog
       9: {
      10:     class Program
      11:     {
      12:         static void Main(string[] args)
      13:         {
      14:             string jsonString = 
      15:                 new WebClient().DownloadString(
      16:                     @"http://search.twitter.com/search.json?q=bldwin");
      17:  
      18:             ResultsWrapper rw = 
      19:                 JsonConvert.DeserializeObject<ResultsWrapper>(jsonString);
      20:         }
      21:     }
      22: }

    That was pretty simple. Now if we put in a breakpoint and inspect the “rw” variable, we can see the following…

    image

    That’s better, now we are dealing with .Net objects in our .Net application, so we are happier. We can also see that we have this Next_Page property, what’s all that about? Well it turns out that Twitter isn’t going to give us all the Tweets at once, we’re going to get them in pages of 15 (by default) and we’ll also get the query string to execute to get the next page. Meh, that sounds like a faff.

    There are a few things we have to do here. Firstly, we need to store the Tweets, after all that is the problem we are trying to solve, and to do that, first thing we need is an object to deserialise them into. For the purposes of this post, we’ll assume we are only interested in the sender of the Tweet, the date it was sent and it’s contents. So the object will look like this…

       1: public class Tweet
       2: {
       3:     public DateTime Created_At { get; set; }
       4:     public string From_User { get; set; }
       5:     public string Text { get; set; }
       6: }

    Oh, we mustn’t forget to add the collection of Tweet objects to the wrapper object so the deserialisation will work properly…

       1: public class ResultsWrapper
       2: {
       3:     public string Next_Page { get; set; }
       4:     public Tweet[] Results { get; set; }
       5: }

    Having done that, we need to make a few changes to our code. We need to add the “rpp=100” property to the querystring, that will tell Twitter to give us 100 Tweets at a time, instead of the default 15, that way we’ll need to make fewer calls. Then we need to separate the URL from the querystring, so that we can substitute the second and subsequent strings we’ll get from Twitter. After that we’ll need a function, which we can call recursively, to fetch the pages and some local storage for our Tweets. Phew, that’s quite a few changes, but really only a few lines of code. When we’ve done all that, our code will look like this…

       1: class Program
       2: {
       3:     private static List<Tweet> Tweets = new List<Tweet>();
       4:  
       5:     static void Main(string[] args)
       6:     {
       7:         string url = @"http://search.twitter.com/search.json";
       8:         string queryString = @"?q=bldwin&rpp=100";
       9:         FetchData(url, queryString);
      10:     }
      11:  
      12:     private static void FetchData(string url, string queryString)
      13:     {
      14:         string jsonString =
      15:             new WebClient().DownloadString(url + queryString);
      16:  
      17:         ResultsWrapper rw =
      18:             JsonConvert.DeserializeObject<ResultsWrapper>(jsonString);
      19:  
      20:         Tweets.AddRange(rw.Results);
      21:  
      22:         if (!String.IsNullOrEmpty(rw.Next_Page))
      23:             FetchData(url, rw.Next_Page);
      24:     }
      25: }

    Now, let’s see what we get if we pop in a breakpoint and inspect the “Tweets” variable…

    image

    Good! We’ve got a .Net object, with the properties we’re interested in, and we’ve abstracted away the JSON that we don’t want to deal with. Now onto the database!

    Just as with the JSON, we want to abstract away the database, so we don’t have to worry about it and the easiest way to do that is to use XPO. Before we can start though we need to add references to the DevExpress.Xpo and DevExpress.Data libraries.

    Having done that we can continue to add support for XPO to our objects. First, we’ll inherit from XpObject, and we’ll add the constructor taking a Session, or a derived class. then we’ll decorate the required properties with the size attribute, just to ensure there’s enough storage for them on the database. Here’s the Tweet class after we’ve done that…

       1: public class Tweet: XPObject
       2: {
       3:     public Tweet(Session session): base(session){}
       4:         
       5:     public DateTime Created_At { get; set; }
       6:     public string From_User { get; set; }
       7:  
       8:     [Size(140)]
       9:     public string Text { get; set; }
      10: }

    And that’s all we have to do to add XPO support to our project, pretty simple eh? Sadly, we’re not done just yet though, because things are a little more complicated on the JSON.Net end. You see we have to construct our XPO derived classes using a Session but, by default, JSON.Net has no idea how to do that so we have to give it a little hint, and we do that in the shape of a CustomerCreationConverter, in fact, we need one for each of our objects. The one for the Tweet object looks like this…

       1: public class TweetConverter : CustomCreationConverter<Tweet>
       2: {
       3:     private UnitOfWork uow;
       4:     public TweetConverter(UnitOfWork uow)
       5:     {
       6:         this.uow = uow;
       7:     }
       8:  
       9:     public override Tweet Create(Type objectType)
      10:     {
      11:         return new Tweet(uow);
      12:     }
      13: }

    And of course we need one for the ResultsWrapper class too.

    Now all we have to do is to amend our application to use the new converters and a UnitOfWork…

       1: private static void FetchData(string url, string queryString, UnitOfWork uow)
       2: {
       3:     UnitOfWork theUnitOfWork;
       4:     if (uow == null)
       5:     {
       6:         theUnitOfWork = new UnitOfWork();
       7:         theUnitOfWork.ConnectionString = 
       8:             "Data Source=.;Initial Catalog=BlogPostDB;Integrated Security=SSPI;";
       9:     }
      10:     else {theUnitOfWork = uow; }
      11:  
      12:     string jsonString =
      13:             new WebClient().DownloadString(url + queryString);
      14:  
      15:     ResultsWrapper rw =
      16:         JsonConvert.DeserializeObject<ResultsWrapper>(jsonString,
      17:             new JsonConverter[]{
      18:                 new ResultsWrapperConverter(theUnitOfWork),
      19:                 new TweetConverter(theUnitOfWork)
      20:             });
      21:  
      22:     Tweets.AddRange(rw.Results);
      23:  
      24:     if (!String.IsNullOrEmpty(rw.Next_Page))
      25:         FetchData(url, rw.Next_Page, theUnitOfWork);
      26:  
      27:     theUnitOfWork.CommitChanges();
      28: }
     
    There’s just one more thing we should do before we run our application and that is put in a little protection around the API call. We don’t really need to do much in this demonstration, we’ll just say, hey if the Twitter API returns any kind of error then we’ll just just finish there and store what we have. Something really simple like this will suffice…
     
       1: private static void FetchData(string url, string queryString, UnitOfWork uow)
       2: {
       3:     UnitOfWork theUnitOfWork;
       4:     if (uow == null)
       5:     {
       6:         theUnitOfWork = new UnitOfWork();
       7:         theUnitOfWork.ConnectionString = 
       8:             "Data Source=.;Initial Catalog=BlogPostDB;Integrated Security=SSPI;";
       9:     }
      10:     else {theUnitOfWork = uow; }
      11:  
      12:     string jsonString;
      13:     try
      14:     {
      15:         jsonString =
      16:             new WebClient().DownloadString(url + queryString);
      17:     }
      18:     catch (WebException we){return;}
      19:  
      20:     ResultsWrapper rw =
      21:         JsonConvert.DeserializeObject<ResultsWrapper>(jsonString,
      22:             new JsonConverter[]{
      23:                 new ResultsWrapperConverter(theUnitOfWork),
      24:                 new TweetConverter(theUnitOfWork)
      25:             });
      26:  
      27:     Tweets.AddRange(rw.Results);
      28:  
      29:     if (!String.IsNullOrEmpty(rw.Next_Page))
      30:         FetchData(url, rw.Next_Page, theUnitOfWork);
      31:  
      32:     theUnitOfWork.CommitChanges();
      33: }

    Then we can run our application and store the search results in the database…

    image

    Of course, once we have them in the database we can hook up DevExpress Analytics and create some interesting visualisations. Hmm, now there’s an idea for my next post, ‘til then, happy coding! Smile

    Update: @snowcode has been in touch to say instead of hand cranking your own classes you can use json2Csharp. Beware though that Json2CSharp won’t generate classes that are not in the original return from the API. For example, if your original return does not contain a Geo object then no Geo class will be generated. Subsequently, the Geo object will not then be deserialised even if future returns do contain a Geo object.

  • XAF–Ask the Team Webinar Today!

    Yes folks, it’s that time of the month again! The time where all you good XAF programmers out there can role up to our webinar and ask me and the team any question about XAF that’s on your mind. Details of this month’s webinar can be found here, where you’ll get country specific details as to the timing.

    As an extra special treat this evening, our brand new XAF evangelist, Tolis, will be joining us. Tolis has a wealth of real life experience using XAF, and so this is a perfect opportunity to ask him questions about using XAF in the wild, as opposed to specific feature questions. Of course, you are still welcome to ask those too!

    Anyway, the team and I are really looking forward to speaking to you this evening, so pop along and register now!

    ‘til this evening then, happy XAF’ing! Smile

  • Attending DDD Scotland 7 May 2010

    DDD Scotland LogoThis Saturday I’m off to DDD Scotland, one of the DDD regional events, where I’ll be presenting a session on Asymptotes and Algorithms.

    The line up for this event is very good, with a lot of great speakers giving interesting titled talks. If you are going to be at the event, don’t forget to say ‘hi’, I don’t bite and I like to chat with as many geeks as I can – I’ll be the guy wearing the DevExpress T – Shirt.

    If you can’t make it to the event (it’s been fully booked for a few weeks now) but you are going to be in the area, then pop along to the Ramada Jarvis hotel at 201 Ingram Street, Glasgow, where you’ll find us all hanging out in the bar of an evening. Feel free to swing by and say ‘hello’, who knows, I may even buy you a beer.

    I’ll blog a full account of the conference on Sunday, ‘til then, happy coding! Smile

  • XAF is on The Move And so am I

    But don’t worry because neither of us are going very far. Firstly, and most importantly, where is the XAF content going? Well, as you’ll know by now, we were lucky enough to hire Tolis as a new evangelist on the frameworks team. Obviously he’ll be blogging about XAF and, equally obviously, he won’t be publishing those posts on my blog. So we took the decision to move all XAF content (from this point forward) back to the XAF blog, where it used to live before I joined DevExpress. Just to be clear then, from now on, all the XAF related blog posts will be found at the following URL:

    http://community.devexpress.com/blogs/eaf/default.aspx

    So that takes care of XAF, but what about me? Well, as I said, I’m not going far. I’ll be sticking around to help Tolis settle in, and also to co-host the XAF webinars with him and anything else he needs as he finds his feet with the company, with the products, and with you horrible lot. Smile

    Other than that, I’ll be taking over the role of Developer Evangelist at DevExpress. What will that mean? Well, in the main, it will mean that my duties will expand to cover all product areas within DevExpress. I’ll be getting out and about as much as possible and meeting as many of you as I can, whilst showing off whatever part of the DevExpress product line is of most interest to you. I’ll also be keeping my ear to the ground, to find out about the next hot topics, and making sure you know how to use our products with them. I’ll also be making videos and doing webinars with you as I show off what’s new and cool out there. So sit back, relax and enjoy the ride, it’s sure to be a blast.

    Well that’s all for this post, so until next time, happy… err… well I’m not too sure really. Dang, looks like I need a new sign off! Smile

  • Sql Bits 8 – ‘Beside the Seaside’

    SQLBits LogoApril 7 – 9 saw us make the trip down to sunny Brighton for SQL Bits, Europe’s largest SQL Server conference. The weather was amazing and the glorious sunshine added to the holiday atmosphere at the conference (the odd ice-cream on the beach didn’t hurt either Smile).

    Of course we weren’t there to have fun, but to work (honest gov’), and I delivered a session on ways to mitigate against the the ORM / Relational impedance. I’ll turn this into a blog post in the next couple of days so you can all enjoy part of the conference – if not the glorious weather. Being the conference it is, SQL Bits attracts the best speakers in the SQL field from all over the world, including the SQL Customer Advisory Team, who did a keynote session and a panel discussion session. Both of these sessions were highly informative and greatly appreciated by the audience. Other speakers attended from countries as far afield as the US, Australia, Holland and Israel.

    Like all conferences, SQL Bits isn’t all about the sessions, but is an opportunity to catch up with old friends and to have a bit of fun. In my case I ran into Phil Winstanley who’ve I not spoken to since he joined Microsoft. Other attendees were able to relax and play around on the Xbox that Microsoft were kind enough to bring down to the event.

    Between the great content and the great atmosphere, Sql Bits is one of the “must go to” conferences in the UK, so make sure I see you there next time, and if I do, don’t forget to say ‘hi’! Smile

  • XAF–Domain Components How-to Implement an Address in a Business Entity

    This post may be outdated. For the latest Domain Components concepts and examples refer to the current online documentation.

    Addresses are funny things aren’t they? If you own the the Address class, and you are writing it for your own application then they are easy things to handle. Each address object is a composition of a number of string types containing the information you require for your application. Simple and straight forward. Of course, as soon as you try to write a reusable interface library, things start to get a little more complicated, so let’s take a look at how we did it.

    First, let’s start with  an IBaseAddress component:

    public interface IBaseAddress
    {
        string DisplayName { get; set; }
    }

    Having this base class for addresses we can now go on to define an IAddressable interface, which entities that require to have one, or more, addresses can use – things like Contacts, Orders, Shipping Notes etc. We can define our IAddressable interface like so:

    [DomainComponent]
    public interface IAddressable
    {
        [DevExpress.ExpressApp.DC.Aggregated]
        [VisibleInListView(false)]
        IBaseAddress PrimaryAddress { get; set; }
    
        [CreateInstance]
        IBaseAddress CreateAddress();
    }

    And we can use it, wherever we need to, like this:

    public interface ICRMContact : IContact, IAddressable, ...
    public interface ICRMAccount : IAccount, IAddressable, ...
    public interface ICRMLead : ILead, IAddressable, ...

    In this interface, there are two significant parts: the PrimaryAddress member, which is aggregated, and it brings in the minimum information of an addresses – the primary address.
    The second significant part is the CreateAddress method that is marked with the CreateInstance attribute. This method is used as a factory method to create an entity that is registered for the IBaseAddress domain component. This method is autogenerated and will work when one entity in the application implements the IBaseAddress interface. In other cases, you need to implement it manually and you’ll have to specify which entity should be created, in this method, when it is called:

    [DomainLogic(typeof(IAddressable))] 
    public class AddressableLogic { 
        public static void AfterConstruction(IAddressable addressable) { 
            if(addressable.PrimaryAddress == null) { 
                addressable.PrimaryAddress = addressable.CreateAddress(); 
            } 
    }

    Now our implementation is far from perfect. Using a string makes it hard to process the address by address part, to filter by a city for example. It is also impossible to guarantee any strict form of address format, which your application may need to do. Providing default lists, say of cities or of US states, is also difficult to do.

    So, let’s improve things by defining a generic address component in our library, this component can be substituted with your own implementation should you need something more specific.

    Our IGenericAddress component will look like this:

    [DomainComponent]
    public interface IGenericAddress : IBaseAddress
    {
        string Street1 { get; set; }
        string Street2 { get; set; }
        string City { get; set; }
        string State { get; set; }
        string Zip { get; set; }
        string Country { get; set; }
    }

    Here you will notice that the single string DisplayName has been broken down into several string members, and is constructed from these parts when any of them is modified:

    [DomainLogic(typeof(IGenericAddress))] 
    public class GenericAddressLogic { 
    private static void UpdateDisplayName(IGenericAddress address) { 
    address.DisplayName = string.Format("{0} {1} {2} {3} {4} {5}", address.Street2, address.Street1, address.City, address.State, 
    address.Zip, address.Country); 
    } 
    public static void AfterChange_Street1(IGenericAddress address) { 
    UpdateDisplayName(address); 
    } 
    public static void AfterChange_City(IGenericAddress address) { 
    UpdateDisplayName(address); 
    } 
    ...

    With this approach, it is possible for you to introduce any other Address implementation into any library component that contains the IBaseAddress member.

    On the Order UI in our XCRM demo application, the address UI looks like this:

    XCRM Order Address

    Well that’s all for this post, until next time, happy XAF’ing! Smile

  • XAF - Domain Components How-to: Implement Notes Functionality in a Business Entity

    This post may be outdated. For the latest Domain Components concepts and examples refer to the current online documentation.

    Notes, every business needs them. Every person in the company who has contact with a customer has to be able to record that fact in a CRM system. The last thing you want to do is to be a salesmen phoning a customer, in the hope of getting a large order, only to discover that the last contact the customer had with your company was to complain bitterly about the shoddy service he just received. If there was a note in the system to that fact, then you could either phone once it’s been resolved, or you could change your sales tactic.

    Of course, saying you need notes is one thing, actually implementing it is quite another, especially if your class hierarchy already exists. You have to introduce the Note type, you have to create a member on the business objects to hold that new type, and most painful of all, you have to make room on the UI for the new note type. All and all you are in a world of pain. Now XAF can help you with the UI stuff, it will scaffold an appropriate UI for your types, but that still doesn’t save you from the pain of all the changes you have to make to your types.

    Well enter Domain Components to save the day! The Domain Component technology will do all that hard work for you. First, let’s declare an INote interface:

    [DomainComponent]
    [XafDefaultProperty("Title")]
    public interface INote {
        [RuleRequiredField(NoteValidationRules.NoteTitleIsRequired, DefaultContexts.Save)]
        [FieldSize(255)]
        string Title { get; set; }
    
        [FieldSize(4000)]
        string Description { get; set; }
        
        IPersistentFileData Attachment { get; set; }
    }

    As you can see it has a mandatory title property, so that you can name your note something meaningful, a description field, big enough to hold a reasonable sized note, and a field to hold an attachment, in case you wish to append a file to the note. Oh, and here’s the NoteValidationRules class that we’ve used in the RuleRequiredField:

    public class NoteValidationRules {
        public const string NoteTitleIsRequired = "NoteTitleIsRequired";
    }

    This pattern let’s us extend this behaviour, if we need to, at a later date.

    So far so good, but it’s not really useful to have one note attached to a business class, what we really need is a notes collection, so let’s go ahead and define something to hold a collection of notes:

    [DomainComponent]
    public interface INotes {
        [DevExpress.ExpressApp.DC.Aggregated]
        IList<INote> Notes { get; }
    }

    This notes interface that we’ve just created is a pluggable part of the notes extension and now we can use it wherever we wish:

    public interface ICRMActivity : IActivity, INotes ...
    public interface ICRMContact : IContact, INotes, ...
    public interface ICRMInvoice : IInvoice, INotes, ...

    And so on and so forth.

    So, as you can see, Domain Components, have saved us an awful lot of work when it comes to adding this notes functionality. After it has been added to the Contact, the UI looks like this:

    Notes on the Contact UI

    And it looks like this, when added to the Invoice:

    Notes on the Invoice UI

    As you can see, in this post, I have not covered testing, neither unit testing, with something like NUnit, nor functional testing with EasyTest. I didn’t add the testing stuff in as I thought it might complicate matters, but if you feel that it wouldn’t and you’d like to see testing covered in this series, then let me know in the comments and I’ll add it to the next one.

    Well, that’s all for this post, until next time, happy XAF’ing! Smile

  • Data Layer – 11.1 Sneak Peek – Custom Functions Part 2

    In a previous blog post I showed you how to use custom functions everywhere you could use a CriteriaOperator. In this post, I’m going to show you how to use custom functions in LINQ to XPO.

    There are two interfaces that support this functionality, they are:

    1. ICustomFunctionOperatorQueryable – which provides information about the method that will be associated with the custom function.
    2. ICustomCriteriaOperatorQueryable – which provides information about the method that will be associated with custom criteria, and implements the behaviour to convert a LINQ expression to a CriteriaOperator.

    Right, let’s write some code! To start with let’s open the project, from the previous post, in Visual Studio 2008 or greater, set target framework to 3.5 or greater and add a reference to the DevExpress.Xpo.v11.1.Linq assembly.

    Next, in the MyConcatFunction class, add the implementation of ICustomFunctionOperatorQueryable

    using DevExpress.Xpo.Helpers;
    //...
    public class MyConcatFunction : ICustomFunctionOperatorBrowsable, 
        ICustomFunctionOperatorFormattable, 
        ICustomFunctionOperatorQueryable 
    {
        //The method name must be the same as the function name,
        //but it doesn't have to be in the same class
        public static string MyConcat(string string0, string string1, string string2, string string3) {
            return string.Concat(string0, string1, string2, string3);
        }
        #region ICustomFunctionOperatorQueryable Members
         
        public System.Reflection.MethodInfo GetMethodInfo() {
            return typeof(MyConcatFunction).GetMethod("MyConcat");
        }
        #endregion
    }

    Finally we will drop another GridControl (imaginatively called GridControl2 Smile) onto the form and add the following code to the form constructor:

    var linqResult = from p in new XPQuery<Person>(Session.DefaultSession)
                     select new
                     {
                         p.FirstName,
                         p.LastName,
                         NameLinqToXpo =
                             MyConcatFunction.MyConcat(p.FirstName,
                             " ", 
                             p.LastName, 
                             " (Linq To Xpo)")
                     };
    gridControl2.DataSource = linqResult.ToList();

    Having done that, running the application will give us this result:

    Example Form showing custome functions in LINQ to XPO

    That’s all for this short post, until next time, happy coding! Smile

  • Developer Express at DevWeek in the UK

    IMG_2104DevWeek is the UK’s largest developer focussed conference with some of the most respected speakers in the world in attendance. Running from the 14th-18 of March the conference combines pre-conference and post-conference workshops with days of sessions in between. This year’s sessions covered topics like: MVC, Azure, C# deep dives and Sharepoint. I’m sure you’ll agree there was enough there for every technical taste.

    Of course Developer Express was there in full force. We were exhibiting at the conference, which enabled me to meet a large number of DevExpress customers as well as those of you who are thinking about becoming customers. I had some great conversations at the booth on a number of great topics, including the future of WPF and Silverlight, so nothing too controversial then Winking smile. I also demonstrated a lot of great DevExpress technology to attendees, including some of our new Silverlight stuff as well as my own first love, XAF.

    Not only were we exhibiting but I was lucky enough to be asked to present a session on NoSQL this year. The session was standing room only as I covered the different types of NoSQL databases, before covering a range of scenarios and recommending a particular type of NoSQL database for each. I finished up with an deep dive into a use case showing how a company pulled themselves out of a situation, which could have easily cost the them their existence, with the use of a NoSQL database. The session itself was standing room only and those in attendance asked some really thought provoking questions and sparked some great conversations, some of which were carried on back at the booth, when some of the attendees sought me out for a follow up chat.

    Making the most of our time in London, we finished up with a great mixer event. I had a lot of fun and met a lot of interesting people and had some great conversations. Rachel has more details of this event on her blog, so pop across there and check out what a great time everyone had.

    All and all I think DevWeek is one of the best conferences in the UK and I look forward to returning next year with the DevExpress team.

  • Data Layer – 11.1 Sneak Peek – Custom Functions Part 1

    One of the exciting changes that we are looking forward to shipping in 11.1, is the global registration of custom functions. Once registered, a custom function can be used where ever CriteriaOperators are processed, as well as being available in all Expression Editors.

    So how does it work? Simply, a custom function is a class which implements several interfaces:

    1. ICustomFunctionOperator – is responsible for base functionality such as function name, result type and client implementation of the function.
    2. ICustomFunctionOperatorFormattable – is responsible for the formatting (implementation) of the function on the server (database) side.
    3. ICustomFunctionOperatorBrowsable - provides additional information for Expression Editors such as function category, function description, argument count etc.

    ICustomFunctionOperatorFormattable and ICustomFunctionOperatorBrowsable inherit from ICustomFunctionOperator. So, if you implement either of first two interfaces, there is no need to implement the last.

    Knowing this, let’s write our own custom function to handle concatenation, let’s call it “MyConcat”

    using DevExpress.Data.Filtering;
    using DevExpress.Xpo.DB;
    using System.Resources;
    using CustomFunctionsExample.Properties;
    
    public class MyConcatFunction : ICustomFunctionOperatorBrowsable, 
    ICustomFunctionOperatorFormattable { const string FunctionName = "MyConcat"; #region ICustomFunctionOperatorBrowsable Members static readonly MyConcatFunction instance = new MyConcatFunction(); public static void Register() { CriteriaOperator.RegisterCustomFunction(instance); } public static bool Unregister() { return CriteriaOperator.UnregisterCustomFunction(instance); } public FunctionCategory Category { get { return FunctionCategory.Text; } } public string Description { get { return Resources.MyConcatDescription; } } public bool IsValidOperandCount(int count) { // At least two operands must be specified. return count > 1; } public bool IsValidOperandType(int operandIndex, int operandCount, Type type) { // All operands should be strings. return type == typeof(string); } public int MaxOperandCount { //Accepts an infinite number of operands. get { return -1; } } public int MinOperandCount { // At least two operands must be specified. get { return 2; } } #endregion #region ICustomFunctionOperator Members // Evaluates the function on the client. public object Evaluate(params object[] operands) { StringBuilder result = new StringBuilder(); foreach(string operand in operands) { result.Append(operand); } return result.ToString(); } public string Name { get { return FunctionName; } } public Type ResultType(params Type[] operands) { foreach(Type operand in operands) { if(operand != typeof(string)) return typeof(object); } return typeof(string); } #endregion #region ICustomFunctionOperatorFormattable Members // The function's expression to be evaluated on the server. public string Format(Type providerType, params string[] operands) { // This example implements the function for MS Access databases only. if(providerType == typeof(AccessConnectionProvider)) { StringBuilder result = new StringBuilder(); result.Append("("); for(int i = 0; i < operands.Length; i++) { if(i > 0) result.Append(" + "); result.AppendFormat("({0})", operands[i]); } result.Append(")"); return result.ToString(); } throw new NotSupportedException(providerType.FullName); } }

    In the code above the Register and Unregister methods simplify the global registration process of our custom function whilst the Description property of the MyConcatFunction class returns a description for our custom function, which we fetch from our resources. This example implements formatting for MS Access only.

    Having done this, let’s write a Person persistent class:

    Next let's write the persistent class Person.

    using DevExpress.Xpo;
    public class Person: XPBaseObject {
        int oid;
        [Key(true)]
        public int Oid {
            get { return oid; }
            set { SetPropertyValue<int>("Oid", ref oid, value); }
        }
        string firstName;
        public string FirstName {
            get { return firstName; }
            set { SetPropertyValue<string>("FirstName", ref firstName, value); }
        }
        string lastName;
        public string LastName {
            get { return lastName; }
            set { SetPropertyValue<string>("LastName", ref lastName, value); }
        }
        //Using our custom function in PersistentAlias
        [PersistentAlias("MyConcat(FirstName, ' ', LastName, ' 1')")]
        public string Name {
            get { return (string)EvaluateAlias("Name"); }
        }
        public Person(Session session) : base(session) { }
    }

    As you can see, in the Name property, we are using our new custom function in the same way as we would use a built-in function.

    Next, we’ll add function registration into the Main method of the Program class:

    [STAThread]
    static void Main() {
        MyConcatFunction.Register();
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }

    Now, let’s create a new form and drop the GridControl(gridControl1), Session(session1)and XPView(xpView1) components onto it, then set the Session property of the xpView1 to session1. After that we will add properties (Name - Property accordingly) to xpView1 as shown below:

    • FirstName - [FirstName]
    • LastName - [LastName]
    • NamePersistentAlias - [Name]
    • NameViewProperty - MyConcat([FirstName], ' ', [LastName], ' 2')

    ViewProperty Collection Editor

    Here we use the MyConcat function in the ViewProperty.

    Now let’s select xpView1 as a data source of the gridControl1 component, run the designer for gridControl1 and add a column with following properties:

    • Caption = Name (Unbound Expression)
    • FieldName = name of the column
    • ShowUnboundExpressionMenu = True
    • UnboundExpression = [MyConcat]([FirstName], ' ', [LastName], ' 3')
    • UnboundType = String

    Finally add the following code into the form constructor:

    string[][] names = new string[][] {
        new string[] { "John", "Smith" },
        new string[] { "Fred", "Scott" },
        new string[] { "James", "King" }
    };
    
    using(UnitOfWork uow = new UnitOfWork()) {
        XPCollection<Person> persons = new XPCollection<Person>(uow);
        uow.Delete(persons);
        uow.CommitChanges();
    }
    
    using(UnitOfWork uow = new UnitOfWork()) {
        for(int i = 0; i < names.Length; i++) {
            Person person = new Person(uow);
            person.FirstName = names[i][0];
            person.LastName = names[i][1];
        }
        uow.CommitChanges();
    }

    Then run the application to see the results:

    Sample App

    Now that the application is running, you can select the function, from the list within the Unbound Expression Editor. To invoke this editor, click the corresponding item in the context menu for the "Name (UnboundExpression)" column.

    Expression Editor

    As you can see, our new function is listed!

    Well that’s all for this post, ‘til next time happy coding! Smile

Next page »
LIVE CHAT

Chat is one of the many ways you can contact members of the DevExpress Team.
We are available Monday-Friday between 7:30am and 4:30pm Pacific Time.

If you need additional product information, write to us at info@devexpress.com or call us at +1 (818) 844-3383

FOLLOW US

DevExpress engineers feature-complete Presentation Controls, IDE Productivity Tools, Business Application Frameworks, and Reporting Systems for Visual Studio, along with high-performance HTML JS Mobile Frameworks for developers targeting iOS, Android and Windows Phone. Whether using WPF, Silverlight, ASP.NET, WinForms, HTML5 or Windows 8, DevExpress tools help you build and deliver your best in the shortest time possible.

Your Privacy - Legal Statements

Copyright © 1998-2013 Developer Express Inc.
ALL RIGHTS RESERVED
All trademarks or registered trademarks
are property of their respective owners