Using T4 to automatically generate your entities

*** This is a repost of a previous post because of moving to a new blog engine in which some formatting was lost ***

Today I discovered something very interesting, namely how to automatically generate my entity classes (classes that also implement the INotifyPropertyChanged and IDataErrorInfo interfaces) using T4.

T4 is a text generation language built into Visual Studio 2005 and later, normally intended for DSL code generation. But we can also use it for generating any code we would like. I for one, I would like automatic properties to automatically implement INotifyPropertyChanged if the interface is on the class, but of course, life doesn’t work that way *sigh*. The real problem is that for each property you have, part of the implementation needs to raise an event using the property name. When you change the name of the property you also have to change this string, which is error prone…

Instead we can generate code using T4, and to be honest, it isn’t that difficult to use. First of all, go to tangible to download their free T4 intelli-sense tool.

Next add to your project a new text file, naming it Entity.tt (the extension is important!). Now add this content:

<#@ template language="C#" #>
<#@ output extension="cs" #>
<#@ import namespace="System.Collections" #>
<#@ import namespace="System.Collections.Generic" #>
// ---------------------------------
// U2U Sample, use at your own risk!
//        http://www.u2u.be
// ---------------------------------

using System;
using System.ComponentModel;
using System.Collections.Generic;

namespace <#= this.Namespace #> 
{  
  public partial class <#= this.ClassName #> 
    : INotifyPropertyChanged
    , IDataErrorInfo  
  {
    #region Private fields
    <# for (int idx = 0; idx < this.properties.GetLength(0); idx++) { #>    
    private <#= this.properties[idx,0] #> _<#= this.properties[idx,1].ToLower() #>;<# }#>   
    
    #endregion
    
    #region Properties
    <# for (int idx = 0; idx < this.properties.GetLength(0); idx++) { #>    
    public <#= this.properties[idx,0] #> <#= this.properties[idx,1] #>
    {        
      get
      {            
        return _<#= this.properties[idx,1].ToLower() #>;        
      }        
      set        
      {            
        _<#= this.properties[idx,1].ToLower() #> = value;
        OnPropertyChanged("<#= this.properties[idx,1]#>");        
      }   
    }
    <#   }   #>      
    #endregion
    
    #region INotifyPropertyChanged Members   
    
    public event PropertyChangedEventHandler PropertyChanged;
    
    protected virtual void OnPropertyChanged(string propertyName)   
    {       
      if (PropertyChanged != null)           
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));   
    }   
    
    #endregion
    
    #region IDataErrorInfo Members
    
    private string _error = null;
    
    public string Error {
      get
      { 
        return _error; 
      }
      set 
      {
        _error = value;
      }
    }
    
    private Dictionary<string,string> _columnErrors =
      new Dictionary<string,string>();
      
    public string this[string columnName]
    {
      get
      {
        if( _columnErrors != null && _columnErrors.ContainsKey(columnName))
          return _columnErrors[columnName];
        else
          return null;
      }
      set
      {
        if( value != null ) // Insert error
        {
          if( _columnErrors == null )
          {
            _columnErrors = new Dictionary<string,string>();
          }
          _columnErrors[columnName] = value;
        }
        else // Clear error
        {
          _columnErrors.Remove(columnName);
          if (_columnErrors.Count == 0)
          {
            _columnErrors = null;
          }
        }
        // Notify validation that something has changed
        OnPropertyChanged( columnName );
      }
    }
    #endregion
  }
}

<#+    
  string Namespace = "Demo";    
  string ClassName = "DemoClass";    
  string[,] properties = {        
    {"int", "Property1"},        
    {"string", "Property2"}
  };               
#>

Building your project will generate a little DemoClass with these two properties. But that is of course not what you want; so add another file Category.tt:

<#    
  this.Namespace = "U2U.Samples";    
  this.ClassName = "Category";    
  this.properties = new string[,]
  {        
    {"int"   , "CategoryID"}
  , {"string", "CategoryName"}      
  , {"string", "Description"}      
  , {"byte[]", "Picture"}
  }; 
#>

<#@ include file="Entity.tt" #>

Building will now automatically generate a Category.cs file with code like this:

// ---------------------------------
// U2U Sample, use at your own risk!
//        http://www.u2u.be
// ---------------------------------

using System;
using System.ComponentModel;
using System.Collections.Generic;

namespace U2U.Samples
{
  public partial class Category
    : INotifyPropertyChanged
    , IDataErrorInfo
  {
    #region Private fields

    private int _categoryid;
    private string _categoryname;
    private string _description;
    private byte[] _picture;

    #endregion

    #region Properties

    public int CategoryID
    {
      get
      {
        return _categoryid;
      }
      set
      {
        _categoryid = value;
        OnPropertyChanged("CategoryID");
      }
    }

    public string CategoryName
    {
      get
      {
        return _categoryname;
      }
      set
      {
        _categoryname = value;
        OnPropertyChanged("CategoryName");
      }
    }

    public string Description
    {
      get
      {
        return _description;
      }
      set
      {
        _description = value;
        OnPropertyChanged("Description");
      }
    }

    public byte[] Picture
    {
      get
      {
        return _picture;
      }
      set
      {
        _picture = value;
        OnPropertyChanged("Picture");
      }
    }

    #endregion

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
      if (PropertyChanged != null)
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    #endregion

    #region IDataErrorInfo Members

    private string _error = null;

    public string Error
    {
      get
      {
        return _error;
      }
      set
      {
        _error = value;
      }
    }

    private Dictionary<string, string> _columnErrors =
      new Dictionary<string, string>();

    public string this[string columnName]
    {
      get
      {
        if (_columnErrors != null && _columnErrors.ContainsKey(columnName))
          return _columnErrors[columnName];
        else
          return null;
      }
      set
      {
        if (value != null) // Insert error
        {
          if (_columnErrors == null)
          {
            _columnErrors = new Dictionary<string, string>();
          }
          _columnErrors[columnName] = value;
        }
        else // Clear error
        {
          _columnErrors.Remove(columnName);
          if (_columnErrors.Count == 0)
          {
            _columnErrors = null;
          }
        }
        // Notify validation that something has changed
        OnPropertyChanged(columnName);
      }
    }
    #endregion
  }
}

So to change/add/remove a property, we edit the Category.tt file and all the rest is done automatically.

Now for some feedback, what is your way of implementing IDataErrorInfo?

Comments (127) -

  • www.playcasinobonuses.com

    12/20/2009 5:15:36 PM |

    The beauty of these blogging engines and CMS platforms is the lack of limitations and ease of manipulation that allows developers to implement rich content and 'skin' the site in such a way that with very little effort one would never notice what it is making the site tick all without limiting content and effectiveness.

  • short sale listings

    12/22/2009 7:58:09 AM |

    That is some inspirational stuff. Never knew that opinions could be this varied. Thanks for all the enthusiasm to offer such helpful information here.

  • payday loans

    12/22/2009 7:20:08 PM |

    Hmmm interesting stuff

  • portland bankruptcy lawyer

    12/26/2009 1:38:28 PM |

    I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post

  • raw dog food

    12/26/2009 5:24:11 PM |

    Resources like the one you mentioned here will be very useful to me! I will post a link to this page on my blog. I am sure my visitors will find that very useful.

  • lån uten sikkerhet

    12/27/2009 7:13:18 PM |

    Have you ever considered adding more videos to your blog posts to keep the readers more entertained? I mean I just read through the entire article of yours and it was quite good but since I'm more of a visual learner,I found that to be more helpful well let me know how it turns out! I love what you guys are always up too. Such clever work and reporting! Keep up the great works guys I've added you guys to my blogroll. This is a great article thanks for sharing this informative information.. I will visit your blog regularly for some latest post.

  • no loss robot

    12/31/2009 3:24:38 PM |

    There are certainly a lot of details like that to take into consideration. That is a great point to bring up. I offer the thoughts above as general inspiration but clearly there are questions like the one you bring up where the most important thing will be working in honest good faith. I don?t know if best practices have emerged around things like that, but I am sure that your job is clearly identified as a fair game.

  • Refurbished Garmin

    1/3/2010 3:49:33 PM |

    I admire what you have done here. I like the part where you say you are doing this to give back but I would assume by all the comments that this is working for you as well.

  • Las Vegas Photographer

    1/3/2010 5:27:46 PM |

    Howdy, i read your blog occasionally and i own a similar one and i was just wondering if you get a lot of spam comments? If so how do you prevent it, any plugin or anything you can advise? I get so much lately it's driving me mad so any assistance is very much appreciated.

  • bad credit payday loans

    1/22/2010 9:04:54 PM |

    Work is not man's punishment. It is his reward and his strength and his pleasure.

  • payday loans

    1/25/2010 2:05:07 PM |

    He who angers you conquers you.

  • bad credit loans

    1/25/2010 2:05:51 PM |

    Success is simple. Do what's right, the right way, at the right time.

  • colon cleanse

    2/9/2010 9:08:53 AM |

    Choose a job you love, and you will never have to work a day in your life.

  • stock loan

    2/26/2010 6:58:36 AM |

    Just wanted to give you a shout from the valley of the sun, great information. Much appreciated.

  • Ida Pesnell

    11/29/2013 11:18:01 AM |

    a bit, but other than that, this is

  • Great dog

    1/21/2014 5:22:27 AM |

    my female lab made the list with Roxy, my mastiff made it with Sam, but my pittie's name is Zeke.(not on the list)                                  Reply

  • Great dog

    1/21/2014 5:37:27 AM |

    my dog has been rescued i tease & say he is a retired actor.; he came into my life day after valentines day sooo his name is Valentino he is a minipin with much energy & so full of life what a personality he has, At night he pats my butt as we walk to the door go out for the night.

  • Information about animals

    1/21/2014 6:58:33 AM |

    i have a maltese her name is muffin her origanl name was munchkin

  • xbox live gratuit

    2/8/2014 11:45:49 PM |

    found your site on del.icio.us today and really liked it.. i bookmarked it and will be back to check it out some more later ..

  • xbox live gratuit

    2/8/2014 11:56:04 PM |

    I just hope to have understood this the way it was meant

  • xbox live gratuit

    2/8/2014 11:56:27 PM |

    I wasn't aware of the many ripples and depth to this story until I surfed here through Google! Great job.

  • xbox live gratuit

    2/8/2014 11:56:32 PM |

    This is genius. Thanks for putting this together. I can’t wait to install it.

  • Fidel

    2/28/2014 3:50:18 AM |

    Have you ever considered adding more videos to your blog posts to keep the readers more entertained? I mean I just read through the entire article of yours and it was quite good but since I'm more of a visual learner,I found that to be more helpful well let me know how it turns out! I love what you guys are always up too. Such clever work and reporting! Keep up the great works guys I've added you guys to my blogroll. This is a great article thanks for sharing this informative information.. I will visit your blog regularly for some latest post.

  • Lyle

    2/28/2014 7:31:25 AM |

    Couldn?t 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 for sharing!

  • Georgann

    2/28/2014 8:08:53 AM |

    Have you ever considered adding more videos to your blog posts to keep the readers more entertained? I mean I just read through the entire article of yours and it was quite good but since I'm more of a visual learner,I found that to be more helpful well let me know how it turns out! I love what you guys are always up too. Such clever work and reporting! Keep up the great works guys I've added you guys to my blogroll. This is a great article thanks for sharing this informative information.. I will visit your blog regularly for some latest post.

  • Rosalind

    2/28/2014 9:52:42 AM |

    Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with more information? It is extremely helpful for me.

  • Kris Norcia

    3/12/2014 3:24:05 AM |

    best payday loans uk <a href="http://www.aroorc.org";>payday loans pnline </a>

  • Phone Numbers

    3/17/2014 8:33:13 PM |

    The Numbers Helpline has sourced 1000's of customer service contact <a href="www.numbershelpline.co.uk/.../";>Phone numbers</a> in the UK. We know how hard it can be to find those <a href="www.numbershelpline.co.uk/.../";>Phonenumbers</a> at times that why we have made a directory with them all in one place so you will never have waste long periods of time looking for a customer service contact <a href="www.numbershelpline.co.uk/.../";>Phonenumbers</a> again.

  • Phone Numbers

    3/20/2014 9:43:03 PM |

    The Numbers Helpline has sourced 1000's of customer service contact <a href="www.numbershelpline.co.uk/.../";>Phone numbers</a> in the UK. We know how hard it can be to find those <a href="www.numbershelpline.co.uk/.../";>Phonenumbers</a> at times that why we have made a directory with them all in one place so you will never have waste long periods of time looking for a customer service contact <a href="www.numbershelpline.co.uk/.../";>Phonenumbers</a> again.

  • Phone Numbers

    3/21/2014 1:12:20 AM |

    The Numbers Helpline has sourced 1000's of customer service contact <a href="www.numbershelpline.co.uk/.../";>Phone numbers</a> in the UK. We know how hard it can be to find those <a href="www.numbershelpline.co.uk/.../";>Phonenumbers</a> at times that why we have made a directory with them all in one place so you will never have waste long periods of time looking for a customer service contact <a href="www.numbershelpline.co.uk/.../";>Phonenumbers</a> again.

  • Phone Numbers

    3/25/2014 10:12:48 PM |

    The Numbers Helpline has sourced 1000's of customer service contact <a href="www.numbershelpline.co.uk/.../";>Phone numbers</a> in the UK. We know how hard it can be to find those <a href="www.numbershelpline.co.uk/.../";>Phonenumbers</a> at times that why we have made a directory with them all in one place so you will never have waste long periods of time looking for a customer service contact <a href="www.numbershelpline.co.uk/.../";>Phonenumbers</a> again.

  • Phone Numbers

    4/3/2014 9:19:53 PM |

    The Numbers Helpline has sourced 1000's of customer service contact <a href="www.numbershelpline.co.uk/.../";>Phone numbers</a> in the UK. We know how hard it can be to find those <a href="www.numbershelpline.co.uk/.../";>Phonenumbers</a> at times that why we have made a directory with them all in one place so you will never have waste long periods of time looking for a customer service contact <a href="www.numbershelpline.co.uk/.../";>Phonenumbers</a> again.

  • Phone Numbers

    4/6/2014 8:58:12 PM |

    The Numbers Helpline has sourced 1000's of customer service contact <a href="www.numbershelpline.co.uk/.../";>Phone numbers</a> in the UK. We know how hard it can be to find those <a href="www.numbershelpline.co.uk/.../";>Phonenumbers</a> at times that why we have made a directory with them all in one place so you will never have waste long periods of time looking for a customer service contact <a href="www.numbershelpline.co.uk/.../";>Phonenumbers</a> again.

  • Phone Numbers

    4/10/2014 8:36:43 PM |

    The Numbers Helpline has sourced 1000's of customer service contact <a href="www.numbershelpline.co.uk/.../";>Phone numbers</a> in the UK. We know how hard it can be to find those <a href="www.numbershelpline.co.uk/.../";>Phonenumbers</a> at times that why we have made a directory with them all in one place so you will never have waste long periods of time looking for a customer service contact <a href="www.numbershelpline.co.uk/.../";>Phonenumbers</a> again.

  • final cut studio 7

    4/10/2014 9:42:52 PM |

    Hands down, Apple's app store wins by a mile. It's a huge selection of all sorts of apps vs a rather sad selection of a handful for Zune. Microsoft has plans, especially in the realm of games, but I'm not sure I'd want to bet on the future if this aspect is important to you. The iPod is a much better choice in that case.

  • Phone Numbers

    4/14/2014 7:19:43 PM |

    The Numbers Helpline has sourced 1000's of customer service contact <a href="www.numbershelpline.co.uk/.../";>Phone numbers</a> in the UK. We know how hard it can be to find those <a href="www.numbershelpline.co.uk/.../";>Phonenumbers</a> at times that why we have made a directory with them all in one place so you will never have waste long periods of time looking for a customer service contact <a href="www.numbershelpline.co.uk/.../";>Phonenumbers</a> again.

  • Phone Numbers

    4/15/2014 10:17:46 PM |

    The Numbers Helpline has sourced 1000's of customer service contact <a href="www.numbershelpline.co.uk/.../";>Phone numbers</a> in the UK. We know how hard it can be to find those <a href="www.numbershelpline.co.uk/.../";>Phonenumbers</a> at times that why we have made a directory with them all in one place so you will never have waste long periods of time looking for a customer service contact <a href="www.numbershelpline.co.uk/.../";>Phonenumbers</a> again.

  • Phone Numbers

    4/16/2014 11:32:23 PM |

    The Numbers Helpline has sourced 1000's of customer service contact <a href="www.numbershelpline.co.uk/.../";>Phone numbers</a> in the UK. We know how hard it can be to find those <a href="www.numbershelpline.co.uk/.../";>Phonenumbers</a> at times that why we have made a directory with them all in one place so you will never have waste long periods of time looking for a customer service contact <a href="www.numbershelpline.co.uk/.../";>Phonenumbers</a> again.

  • Harry Peters

    4/17/2014 4:30:20 PM |

    Love your enemies. It makes them so damned mad. ~ P.D. East

  • Earl Peters

    4/17/2014 4:38:07 PM |

    If you can smile when things go wrong, you have someone in mind to blame!

  • Phone Numbers

    4/21/2014 11:06:36 PM |

    The Numbers Helpline has sourced 1000's of customer service contact <a href="www.numbershelpline.co.uk/.../";>Phone numbers</a> in the UK. We know how hard it can be to find those <a href="www.numbershelpline.co.uk/.../";>Phonenumbers</a> at times that why we have made a directory with them all in one place so you will never have waste long periods of time looking for a customer service contact <a href="www.numbershelpline.co.uk/.../";>Phonenumbers</a> again.

  • windows 7

    4/25/2014 6:46:55 PM |

    Thank You For Sharing This Very Enlightening Blog Post Keep Up The Great Work!! I Posted A Link To My Activate Windows 7 Ultimate 64 Bit Post To Show You How To Activate Windows 7 Ultimate 64 Bit! Enjoy!

  • Phone Numbers

    4/27/2014 10:53:52 PM |

    The Numbers Helpline has sourced 1000's of customer service contact <a href="www.numbershelpline.co.uk/.../";>Phone numbers</a> in the UK. We know how hard it can be to find those <a href="www.numbershelpline.co.uk/.../";>Phonenumbers</a> at times that why we have made a directory with them all in one place so you will never have waste long periods of time looking for a customer service contact <a href="www.numbershelpline.co.uk/.../";>Phonenumbers</a> again.

  • Phone Numbers

    4/28/2014 8:39:26 PM |

    The Numbers Helpline has sourced 1000's of customer service contact <a href="www.numbershelpline.co.uk/.../";>Phone numbers</a> in the UK. We know how hard it can be to find those <a href="www.numbershelpline.co.uk/.../";>Phonenumbers</a> at times that why we have made a directory with them all in one place so you will never have waste long periods of time looking for a customer service contact <a href="www.numbershelpline.co.uk/.../";>Phonenumbers</a> again.

  • windows 7 ultimate loader 64 bit free download

    4/29/2014 2:47:40 AM |

    Hey Thank You For Sharing This Very Useful Weblog Post Keep Up The Good Work!!! I Left A Backlink To My Activate Windows 7 Ultimate 32 Bit Guide To Share With You How To Activate Windows 7 Enjoy!

  • Carroll B. Merriman

    5/5/2014 1:45:51 AM |

    I simply want to mention I'm new to blogs and definitely enjoyed you're web-site. More than likely I’m likely to bookmark your blog post . You really have exceptional well written articles. Thanks a lot for revealing your web site.

  • Nakisha Pannone

    5/6/2014 6:17:38 PM |

    Very good quality material and style for the price. Nice fit. Nice look. I Probably will buy more soon.

  • Louann Correo

    5/8/2014 4:33:47 AM |

    Hey it seems to be great content also share up this awesome from my side. <a href=”http://mothersdaywishes2014.in/”>Mothers Day 2014</a>

  • Carolin Blanc

    5/8/2014 4:36:17 AM |

    Hey it seems to be great content also share up this awesome from my side. <a href=”http://mothersday2014poemssongs.in/”>Mothers Day 2014</a>

  • Raul Coty

    5/11/2014 12:21:48 PM |

    I've Checked out many sites for Adult Images and videos and www.supersmash.co is the only site I can say Has some of the most unique photos you wouldent find anywhere else. Big Booties, Titties, and Sexy girls. I recommend this site to anyone trying to furfill their arousement. www.supersmash.co

  • Wilford Mclawhorn

    5/11/2014 12:22:39 PM |

    I've Checked out many sites for Adult Images and videos and www.supersmash.co is the only site I can say Has some of the most unique photos you wouldent find anywhere else. Big Booties, Titties, and Sexy girls. I recommend this site to anyone trying to furfill their arousement. www.supersmash.co

  • activate windows

    5/11/2014 7:36:06 PM |

    Hello Thank You For Creating This Really Enlightening Weblog Post Keep Up The Amazing Work!! I Posted A Back Link To My Activate Windows Guide To Share With You How To Activate Windows Enjoy!

  • Phone Numbers

    5/15/2014 11:21:08 PM |

    The Numbers Helpline has sourced 1000's of customer service contact <a href="www.numbershelpline.co.uk/.../";>Phone numbers</a> in the UK. We know how hard it can be to find those <a href="www.numbershelpline.co.uk/.../";>Phonenumbers</a> at times that why we have made a directory with them all in one place so you will never have waste long periods of time looking for a customer service contact <a href="www.numbershelpline.co.uk/.../";>Phonenumbers</a> again.

  • Leana Mennella

    5/16/2014 2:15:42 AM |

    I liked up to you will receive carried out proper here. The cartoon is attractive, your authored subject matter stylish. nonetheless, you command get got an shakiness over that you would like be delivering the following. ill for sure come further before again as precisely the same nearly a lot frequently inside case you shield this increase.

  • activate windows 7 ultimate 64

    5/16/2014 7:54:19 PM |

    Hey Thank Ya For Creating And Sharing The Very Educational Post Keep Up The Amazing Work!! I Left A Backlink To My Activate Windows 7 Ultimate 64 Bit Posts To Share With You How You Can Activate Windows 7 Ultimate! Check Out My How To Install Microsoft Windows 7 Guides Site. Enjoy!!!

  • Luigi Fulk

    5/17/2014 12:03:43 PM |

    I simply want to mention I am just new to blogging and site-building and truly enjoyed your blog. Probably I’m planning to bookmark your blog post . You actually have superb articles. Thanks a bunch for sharing your website.

  • Dorathy Krout

    5/18/2014 12:20:39 AM |

    Oh my goodness! Impressive article dude! Thanks, However I am going through issues with your RSS. I don't understand the reason why I can't join it. Is there anybody getting identical RSS issues? Anybody who knows the answer can you kindly respond? Thanks!!|

  • Cornelius Tatel

    5/18/2014 7:13:50 PM |

    Hi, i believe that i noticed you visited my weblog thus i came to go back the choose?.I'm attempting to to find things to improve my website!I assume its good enough to use a few of your concepts!!|

  • Richelle Deshon

    5/18/2014 9:34:51 PM |

    I was reading some of your blog posts on this website and I believe this internet site is real informative! Continue posting.

  • http://www.pe7s1zer45m9aoet.com

    5/20/2014 12:45:48 AM |

    article very puissant ! @ 3'f6gh it's very difficult to find another site best because.

  • Luigi Fulk

    5/25/2014 3:54:15 PM |

    I just want to mention I am newbie to blogging and site-building and truly liked your web page. Most likely I’m planning to bookmark your site . You certainly come with amazing articles and reviews. Many thanks for revealing your web-site.

  • climatisation

    6/2/2014 3:28:56 AM |

    Adorable allure de détailler le paragraphe, mais fastidieux pour prendre des données en ce qui concerne ma présentation du sujet , que je vais présenter a l’école .

  • Mitzi Arend  

    6/5/2014 3:36:20 AM |

    great site love the content

  • girls online shopping

    6/11/2014 4:10:40 AM |

    Dating girls once was so  problematic,  however at this moment everything has changed with the addition of online dating! Date tons of girls and enjoy!! --> http://datesexyhotbitches.blogspot.com/

  • Whitley

    6/13/2014 4:04:27 PM |

    Hi check out this site for the lowest cost of medications and  you don't even need a prescription http://healingherbservices.com

  • Luigi Fulk

    6/19/2014 11:34:41 PM |

    I simply want to say I am new to blogging and honestly savored this web page. Very likely I’m likely to bookmark your blog . You definitely come with really good articles. Bless you for revealing your blog.

  • steam shower tub

    6/27/2014 7:02:48 PM |

    Adore this blogging site, amazing work

  • see here now

    7/3/2014 8:06:11 PM |

    I simply want to tell you that I'm very new to weblog and really loved this website. Almost certainly I’m want to bookmark your blog . You definitely come with superb articles and reviews. Thanks a lot for sharing with us your blog site.

  • corner steam shower

    7/10/2014 5:23:16 AM |

    awesome suggestions right here , really recommended

  • steam shower sauna

    7/13/2014 10:24:19 PM |

    great information on this page , truly beneficial

  • steam shower benefits

    7/14/2014 9:35:36 PM |

    Fabulous read, keep up the awesome work

  • steam shower unit

    7/17/2014 9:17:01 PM |

    Adore this blogging site, amazing work

  • steam showers for less

    7/18/2014 11:46:16 PM |

    awesome blog site site you possess, will most likely arrive back again

  • Eddy Adamczyk

    7/19/2014 7:34:10 AM |

    "Enw:" "Mail (will not be published)" "Gwefan" "(gofynnol)"

  • Ching Jetton

    7/19/2014 7:34:26 AM |

    "Nôlnodiad" "Rho sylw"

  • Loree Esparsen

    7/19/2014 7:34:28 AM |

    "powered by croogo" "Add New comment"

  • Fredrick Iriarte

    7/19/2014 7:34:51 AM |

    "Powered by Movable Type" "You may use HTML tags for style"

  • Barry Deibert

    7/19/2014 7:36:48 AM |

    "Jejak balik" "Tinggalkan komen"

  • Jeramy Slavis

    7/19/2014 7:37:08 AM |

    "Béré pairan" "Can aya pairan."

  • Annett Debuhr

    7/19/2014 7:37:21 AM |

    "There are no comments yet. Be the first and leave a response!"

  • Harmony Bhattacharya

    7/19/2014 7:37:24 AM |

    "powered by byteflow" "You can use Markdown here"

  • Debra Hollopeter

    7/19/2014 7:57:12 AM |

    "powered by flatpress" "Fill out the form below to add" -eliminate -abuses

  • Blair Kessans

    7/19/2014 8:02:10 AM |

    "Béré pairan" "Can aya pairan."

  • Loree Esparsen

    7/19/2014 8:02:49 AM |

    "Muhokamada qatnashing"

  • Aundrea Dinsdale

    7/19/2014 8:03:00 AM |

    "Write post with name/password" URI "Non-public"

  • Synthia Nattiah

    7/19/2014 8:41:17 AM |

    "Skriv en kommentar" "Endnu ingen kommentarer."

  • Brain Wisdom

    7/19/2014 8:41:42 AM |

    "powered by Mephisto" "a response" -"are closed for" Email Address Website

  • Tosha Salsa

    7/19/2014 8:41:44 AM |

    "Nama:" "Surat (tidak akan dipublikasikan)" "Situs web" "(wajib)"

  • Dorothy Gerking

    7/19/2014 8:41:51 AM |

    "Enw:" "Mail (will not be published)" "Gwefan" "(gofynnol)"

  • Errol Walwyn

    7/19/2014 11:25:57 PM |

    "Einen Kommentar hinterlassen"

  • Andrew Gislason

    7/19/2014 11:26:03 PM |

    "Post a Comment" "Enter Word Verification in box below"

  • Claud Jiminez

    7/19/2014 11:29:04 PM |

    "Speak Your Mind" Website

  • Tonita Dose

    7/19/2014 11:29:10 PM |

    "This site uses KeywordLuv."

  • Emma Delegeane

    7/19/2014 11:29:52 PM |

    "You can leave a response, or trackback from your own site."

  • Michael Pruyne

    7/19/2014 11:55:46 PM |

    "Skriv en kommentar" "Endnu ingen kommentarer."

  • Jeremy Rakestrow

    7/20/2014 12:06:40 AM |

    "%EB%B9%84%EB%B0%80%EA%B8%80" "%ED%99%88%ED%8E%98%EC%9D%B4%EC%A7%80" "%EC%9D%B4%EB%A6%84/%EB%B9%84%EB%B0%80%EB%B2%88%ED%98%B8%EB%A1%9C+%EA%B8%80%EC%93%B0%EA%B8%B0"

  • Blair Kessans

    7/20/2014 1:11:17 AM |

    inurl:?p=*&option=com_wordpress&Itemid=*

  • Ivory Cheatem

    7/20/2014 1:11:51 AM |

    "Leave a comment" "No comments yet."

  • Kristi Annala

    7/20/2014 1:11:58 AM |

    "Lacak balik" "Tinggalkan komentar"

  • Valentin Guile

    7/20/2014 1:12:04 AM |

    "Dejar un comentario"

  • steam shower cabins

    7/20/2014 2:57:39 AM |

    amazing suggestions on this site , really beneficial

  • steam shower sauna

    7/20/2014 9:21:42 PM |

    seriously fantastic blog site absolutely love the suggestions on this site

  • steam shower cubicle

    7/22/2014 10:55:34 PM |

    nice blog site you have got, will most likely come back again

  • Singgasana Hotels & Resorts pilihan akomodasi terbaik di Indonesia

    7/26/2014 10:35:36 AM |

    Thank You For Sharing This Very Enlightening Blog Post Keep Up The Great Work!! I

  • steam shower uk

    7/28/2014 2:11:48 AM |

    Truly Love this blogging site, good work

  • read the full info here

    8/5/2014 3:22:42 AM |

    certainly like your web site however you need to test the spelling on quite a few of your posts. Many of them are rife with spelling issues and I in finding it very troublesome to inform the truth then again I¡¦ll certainly come again again.

  • Link

    8/5/2014 4:43:14 PM |

    Qué suerte la mía. Muy buena info y encontré tu sitio por casualidad. Lo tengo guardado como favorito! Gracias... Besos

  • steam shower cubicle

    8/5/2014 11:12:16 PM |

    awesome suggestions on this page , really helpful

  • Fae M. Vivanco

    8/6/2014 11:57:00 AM |

    Pretty nice post. I simply stumbled upon your blog and wished to mention that I?ve truly loved browsing your blog posts. After all I will be subscribing in your rss feed and I?m hoping you write again soon!

  • torrentleech invite

    8/7/2014 12:50:26 AM |

    You have  noted  very interesting points ! ps nice    internet site .

  • Noah Arunachalam

    8/7/2014 1:07:15 AM |

    Pretty element of content. I just stumbled upon your blog and in accession capital to assert that I get in fact loved account your blog posts. Any way I will be subscribing in your augment or even I fulfillment you get admission to consistently fast.

  • home steam shower cabin

    8/10/2014 10:47:00 PM |

    great content on this page , truly helpful

  • DEBORA Laurence

    8/11/2014 9:46:36 AM |

    ELIHES,Transport de voyageur & vtc elihes.com/, Chauffeur privé sur paris et région parisienne.

  • Web Design

    8/11/2014 2:21:50 PM |

    The new Zune browser is surprisingly good, but not as good as the iPod's. It works well, but isn't as fast as Safari, and has a clunkier interface. If you occasionally plan on using the web browser that's not an issue, but if you're planning to browse the web alot from your PMP then the iPod's larger screen and better browser may be important.

  • DEBORA Laurence

    8/11/2014 8:57:10 PM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/16/2014 4:54:40 AM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • steam showers

    8/16/2014 10:14:08 AM |

    awesome blog site site you possess, will most likely arrive back again

  • steam shower sauna

    8/19/2014 5:19:07 PM |

    Truly Love this blogging site, good work

  • dirty computers

    8/22/2014 1:40:16 AM |

    Hello Just discovered Your webpage On Google Search. Nice Posts On This Web Site!

  • DEBORA Laurence

    8/24/2014 1:15:09 AM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 1:40:13 AM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 1:44:38 AM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 2:08:44 AM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 2:35:36 AM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 2:38:14 AM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 5:03:34 AM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 5:24:19 AM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 5:26:40 AM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 5:52:36 AM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 6:33:40 AM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 7:00:18 AM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 7:00:57 AM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 7:28:50 AM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 7:51:00 AM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 8:23:42 AM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 9:07:17 AM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 10:07:17 AM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 10:09:18 AM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 10:19:18 AM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 10:28:08 AM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 11:22:33 AM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 11:33:46 AM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 11:39:43 AM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 1:16:19 PM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 1:43:55 PM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 2:04:03 PM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 3:50:06 PM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 3:57:25 PM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 4:01:24 PM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 4:12:28 PM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 4:38:50 PM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 4:44:01 PM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 4:47:41 PM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 5:04:56 PM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 5:37:23 PM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 5:37:33 PM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 5:52:24 PM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 6:12:13 PM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 6:17:43 PM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 7:12:18 PM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 7:50:19 PM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 8:50:10 PM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 9:01:52 PM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 9:42:34 PM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 10:05:16 PM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/24/2014 10:39:13 PM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/25/2014 12:06:03 AM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/25/2014 12:25:17 AM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/25/2014 1:05:03 AM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/25/2014 1:11:19 AM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/25/2014 1:22:17 AM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/25/2014 3:12:51 AM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

  • DEBORA Laurence

    8/25/2014 3:58:28 AM |

    annuaires-gratuit.com/ vous propose de créer gratuitement un annuaire de sites internet pour un bon référencement.

Loading

An auto-hyperlinking RichTextBlock for Windows 8.1 Store apps

Diederik Krols

The XAML Brewer

An auto-hyperlinking RichTextBlock for Windows 8.1 Store apps

This article shows how to let a XAML RichTextBlock control detect URLs and email addresses in its raw text, and show these as hyperlinks. The code only applies to Windows 8.1 because I’m using the brand new Hyperlink control. Here’s a screenshot of the attached sample app. There’s a regular textbox on top in which you can type whatever you like, the ‘Assign’ button sends your text to the pimped RichTextBlock at the bottom. This will transform all URLs and email addresses from the raw text into an operational hyperlink:

Unfortunately, the RichTextBlock control lives in a sealed class, so putting the logic in a child class was not an option. So I decided to go for an attached property called “RawText”:

/// <summary>
/// Ads auto-hyperlinking to a RichTextBlock control.
/// </summary>
public static class HyperlinkExtensions
{
    /// <summary>
    /// The raw text property.
    /// </summary>
    public static readonly DependencyProperty RawTextProperty =
        DependencyProperty.RegisterAttached("RawText", typeof(string), typeof(RichTextBlock), new PropertyMetadata("", OnRawTextChanged));

    /// <summary>
    /// Gets the raw text.
    /// </summary>
    public static string GetRawText(DependencyObject obj)
    {
        return (string)obj.GetValue(RawTextProperty);
    }

    /// <summary>
    /// Sets the raw text.
    /// </summary>
    public static void SetRawText(DependencyObject obj, string value)
    {
        obj.SetValue(RawTextProperty, value);
    }

    /// <summary>
    /// Called when raw text changed.
    /// </summary>
    private static void OnRawTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        // Transformation logic ...
    }
}

In that same class I also defined an extension method that allows you to easily assign the raw text to the control:

/// <summary>
/// Sets the raw text.
/// </summary>
/// <remarks>Extension method.</remarks>
public static void AssignRawText(this RichTextBlock rtb, string value)
{
    rtb.SetValue(RawTextProperty, value);
}

Strangely, I could not name this extension method SetRawText(), because the C# compiler considered it a duplicate of the setter for the attached property. [Yes, I realize that it *is* a duplicate. But in Windows 8.0 I could get away with this, and that makes it ‘strangely’...]

You can assign the property in C#:

this.OutputBox.AssignRawText(this.InputBox.Text);

... or in XAML:

<RichTextBlock x:Name="OutputBox" hyper:HyperlinkExtensions.RawText="Your raw text here." />

The ‘hyperlinkables’ are detected by a regular expression that I found over here. The URLs and email addresses are added as Hyperlink to the Inlines collection of a Paragraph in the Block collection of the RichTextBlock. The rest of the raw text is added as plain Run instances.

What I like about the regex is that it also detects the URLs without a protocol (like www.u2uconsult.com). These look nice in the text, but for the NavigateUri property of the Hyperlink, it’s better to add the protocol.

Here’s the full transformation logic:

/// <summary>
/// Called when raw text changed.
/// </summary>
private static void OnRawTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    RichTextBlock rtb = (RichTextBlock)d;
    if (rtb != null)
    {
        // Working variables.
        string result = string.Empty;
        int index = 0;
        Paragraph par = new Paragraph();
        string text;
        Run run;
        Hyperlink link;
        string source = e.NewValue.ToString();

        // Regex initialization.
        string pattern = @"((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\jQuery15206922996124803609_1383046336084(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)";
        Regex regex = new Regex(pattern);
        var matches = regex.Matches(source);

        foreach (Match match in matches)
        {
            // Add text before match.
            int matchIndex = match.Index;
            text = source.Substring(index, matchIndex - index);
            run = new Run();
            run.Text = text;
            par.Inlines.Add(run);

            // Add match as hyperlink.
            string hyper = match.Value;
            link = new Hyperlink();
            run = new Run();
            run.Text = hyper;
            link.Inlines.Add(run);

            // Complete link if necessary.
            if (!hyper.Contains("@") && !hyper.StartsWith("http"))
            {
                hyper = @"http://" + hyper;
            }

            if (hyper.Contains("@") && !hyper.StartsWith("mailto"))
            {
                hyper = @"mailto://" + hyper;
            }
                    
            link.NavigateUri = new Uri(hyper);
            par.Inlines.Add(link);

            index = matchIndex + match.Length;
        }

        // Add text after last match.
        text = source.Substring(index, source.Length - index);
        run = new Run();
        run.Text = text;
        par.Inlines.Add(run);

        // Update RichTextBlock content.
        rtb.Blocks.Clear();
        rtb.Blocks.Add(par);
    }
}

Here’s how the sample app looks like when I tapped the URL link:


... and the e-mail address:

Here’s the sample app. It was written in the VS2013 preview for the Windows 8.1 preview: U2UC.WinRT.HyperlinkBox.zip (148.67 kb)

Enjoy!
Diederik

Comments (2) -

  • Manie Jergens

    2/7/2014 12:20:27 AM |

    hey there, your site is cheap. We do thank you for work

  • Ruben

    4/2/2014 8:17:29 PM |

    Great post. However, the "jQuery15206922996124803609_1383046336084"-part of your regex caused problems when I tried it. I used the expression from the source you mentioned and it worked like a charm.

Comments are closed