Nibble

Contour 3.0 Code First, Member registration, profile, login, change password

The upcoming Contour 3.0 release features a new code first framework that is outlined in this post on umbraco.com

To add some more examples I’ve updated the example with some additional member forms:

Profile form

using System;
using System.Collections.Generic;
using Umbraco.Forms.CodeFirst;
using Umbraco.Forms.Core.Providers.FieldTypes;
using umbraco.cms.businesslogic.member;
 
namespace Contour.CodeFirstExample
{
    [Form("Member/Profile", ShowValidationSummary = true, MessageOnSubmit = "Profile updated!")]
    public class Profile: FormBase
    {
        [Field("Profile", FormFieldsets.Details,
            Mandatory = true,
            DefaultValue = "{member.name}")]
        public string Name { get; set; }
 
        [Field("Profile", FormFieldsets.Details,
            Mandatory = true,
            Regex = @"(\w[-._\w]*\w@\w[-._\w]*\w\.\w{2,3})",
            DefaultValue = "{member.email}")]
        public string Email { get; set; }
 
        [Field("Profile", FormFieldsets.Details,
            Type = typeof(FileUpload),
            DefaultValue = "{member.avatar}")]
        public string Avatar { get; set; }
 
        public override IEnumerable<Exception> Validate()
        {
            var e = new List<Exception>();
 
            var m = Member.GetCurrentMember();
 
            if (m != null)
            {
                if (m.Email != Email)
                {
                    if (Member.GetMemberFromLoginName(Email) != null)
                        e.Add(new Exception("Email already in use"));
                }
            }
 
            return e;
 
        }
 
        public override void Submit()
        {
            var m = Member.GetCurrentMember();
 
            if (m != null)
            {
                m.Email = Email;
                m.LoginName = Email;
                m.Text = Name;
                //asign custom properties
                if (!string.IsNullOrEmpty(Avatar))
                    m.getProperty("avatar").Value = Avatar;
            }
        }
    }
}

 

Change password form

using System;
using System.Collections.Generic;
using Umbraco.Forms.CodeFirst;
using Umbraco.Forms.Core.Providers.FieldTypes;
using umbraco.cms.businesslogic.member;
 
namespace Contour.CodeFirstExample
{
    [Form("Member/Change password", ShowValidationSummary = true, MessageOnSubmit = "Password updated!")]
    public class ChangePassword: FormBase
    {
        [Field("Change password", "",
            Type = typeof(Password),
            Mandatory = true)]
        public string Password { get; set; }
 
        [Field("Change password", "",
            Type = typeof(Password),
            Mandatory = true)]
        public string RepeatPassword { get; set; }
 
        public override IEnumerable<Exception> Validate()
        {
            var e = new List<Exception>();
         
            //makes sure the passwords are identical
            if (Password != RepeatPassword)
                e.Add(new Exception("Passwords must match"));
 
            return e;
        }
 
        public override void Submit()
        {
            var m = Member.GetCurrentMember();
 
            if(m != null)
                m.Password = Password;
        }
    }
}

 

Login form

using System;
using System.Collections.Generic;
using Umbraco.Forms.CodeFirst;
using Umbraco.Forms.Core.Providers.FieldTypes;
using umbraco.cms.businesslogic.member;
 
namespace Contour.CodeFirstExample
{
    [Form("Member/Login", ShowValidationSummary = true, MessageOnSubmit ="You are now logged in")]
    public class Login: FormBase
    {
        [Field("Login", "",
           Mandatory = true,
           Regex = @"(\w[-._\w]*\w@\w[-._\w]*\w\.\w{2,3})")]
        public string Email { get; set; }
 
        [Field("Login", "",
            Type = typeof(Password),
            Mandatory = true)]
        public string Password { get; set; }
 
 
        public override IEnumerable<Exception> Validate()
        {
            var e = new List<Exception>();
 
            if(Member.GetMemberFromLoginName(Email) == null)
                e.Add(new Exception("No member found with that email address"));
            else if (Member.GetMemberFromLoginNameAndPassword(Email, Password) == null)
                e.Add(new Exception("Incorrect password"));
 
            return e;
        }
 
        public override void Submit()
        {
           var m = Member.GetMemberFromLoginNameAndPassword(Email, Password);
           if (m != null)
               Member.AddMemberToCache(m);
        }
    }
}

 

Registration form

using System;
using System.Collections.Generic;
using Umbraco.Forms.CodeFirst;
using umbraco.cms.businesslogic.member;
using umbraco.BusinessLogic;
using Umbraco.Forms.Core.Providers.FieldTypes;
 
namespace Contour.CodeFirstExample
{
    
    public enum FormPages
    {
        Registration
    }
 
    public enum FormFieldsets
    {
        Details
    }
 
    [Form("Member/Registration", ShowValidationSummary = true, MessageOnSubmit="You are now registered!")]
    public class Registration: FormBase
    {
        public const string MemberTypeAlias = "Member";
        public const string MemberGroupName = "Authenticated";
 
        [Field(FormPages.Registration,FormFieldsets.Details,
            Mandatory= true)]
        public string Name { get; set; }
 
        [Field(FormPages.Registration, FormFieldsets.Details,
            Mandatory = true,
            Regex = @"(\w[-._\w]*\w@\w[-._\w]*\w\.\w{2,3})")]
        public string Email { get; set; }
 
        [Field(FormPages.Registration, FormFieldsets.Details, 
            Type = typeof(Password),
            Mandatory = true)]
        public string Password { get; set; }
 
        [Field(FormPages.Registration, FormFieldsets.Details, 
            Type = typeof(Password),
            Mandatory = true)]
        public string RepeatPassword { get; set; }
 
        [Field(FormPages.Registration, FormFieldsets.Details, 
            Type = typeof(FileUpload))]
        public string Avatar { get; set; }
 
        public override IEnumerable<Exception> Validate()
        {
            var e = new List<Exception>();
            //checks if email isn’t in use
            if(Member.GetMemberFromLoginName(Email) != null)
                e.Add(new Exception("Email already in use"));
            //makes sure the passwords are identical
            if (Password != RepeatPassword)
                e.Add(new Exception("Passwords must match"));
 
            return e;
        }
        public override void Submit()
        {
            //get a membertype by its alias
            var mt = MemberType.GetByAlias(MemberTypeAlias); //needs to be an existing membertype
            //get the user(0)
            var user = new User(0);
            //create a new member with Member.MakeNew
            var member = Member.MakeNew(Name, mt, user);
            //assign email, password and loginname
            member.Email = Email;
            member.Password = Password;
            member.LoginName = Email;
            //asign custom properties
            if(!string.IsNullOrEmpty(Avatar))
                member.getProperty("avatar").Value = Avatar;
            //asssign a group, get the group by name, and assign its Id
            var group = MemberGroup.GetByName(MemberGroupName); //needs to be an existing MemberGroup
            member.AddGroup(group.Id);
            //generate the member xml with .XmlGenerate
            member.XmlGenerate(new System.Xml.XmlDocument());
            //add the member to the website cache to log the member in
            Member.AddMemberToCache(member);
            
        }
    }
}

The code assumes there is a membertype called Member with a additional property with the alias avatar and a membergroup called Authenticated

For more member properties the code needs to be updated…

After deploying you should end up with the following forms

image

Full sourcecode is available here

71 Comments so far

  1. Shannon on November 30th, 2012

    With this solution would you not then be storing all you users password in plain text?

  2. Tim Geyssens on November 30th, 2012

    @Shannon nope

  3. martin on December 4th, 2012

    Is it possible to use this pattern with custom fieldtypes like the re-captcha in contour contrib? Or is it limited only to core fieldtypes?

  4. Tim Geyssens on December 6th, 2012

    @martin yup custom fieldtypes is also possible, add reference and then set the type on the field attribute :)

  5. Ash on December 7th, 2012

    Is it possible to enable conditions or the additional settings on the fields?
    If yes how would we do it?

  6. Tim Geyssens on December 21st, 2012
  7. Maxime on February 4th, 2013

    How can we add more fields? I try to apply for iwin and have to copy code

  8. Will on February 4th, 2013

    hey,

    Is it possible to create form steps using the code first approach?

    Thanks, will

  9. Tim Geyssens on April 9th, 2013

    @Will yeah if you have different page names in the field attributes

  10. Pete Duncasnon on April 15th, 2013

    Hey Tim,

    We’ve had a nasty time getting this working on a recent project trying to get login, signup etc working. Feels like we are going against the grain. Where best to send feedback, quirks and issues for this sort of stuff so others don’t get as stuck?

    Cheers

    Pete

  11. Dan on August 2nd, 2013

    I’m using Umbraco 6.0.5 and Contour 3.0.12 and the reg form works fine except no custom properties are being saved. Help!

  12. Gavin on November 8th, 2013

    For the Login the Password and UserName is being stored in clear text in the UFRecordDataString table. Is there anyway to prevent this ?

    I’ve tried the option StoreRecordsLocally=false but that does seem to effect it.

    Thanks,
    Gavin

  13. Dan Evans on January 8th, 2014

    Hi Tim

    These forms are great, however all users login info (passwords in particular) are saved in Contour in plain text. Is there an easy way to stop Contour saving this information as it’s a bit of a security risk.

    Thanks

    Dan

  14. Tim Geyssens on January 8th, 2014

    @Dan, yeah you can specify to not store locally on the form attribute

  15. permissibleordi40.snappages.com on February 17th, 2014

    Ј’ai poiօnt fin de lire toutefois je repasserai ce soir

  16. soin visage on February 18th, 2014

    Thanks a lot about that!

  17. gommage visage on February 18th, 2014

    Continue!!

  18. localiser iphone on February 19th, 2014

    Localiser iphone est maintenant possible!!

  19. chiptuning on March 28th, 2014

    Spot on with this write-up, I actually think this web site needs a lot more attention.
    I’ll probably be back again to see more, thanks for the
    information!

  20. Jacob Polden on April 24th, 2014

    For some reason only one of my contour forms renders correctly at a time. If I restart the app pool they alternate consistently, even the count of field sets changes in the database. They are two different classes in the same namespace and compiled into one dll. Is that okay or should I be breaking up each form into a separate dll?

  21. Mei on April 28th, 2014

    Hey! Would you mind if I share your blog with my
    facebook group? There’s a lot of folks that I think would really enjoy
    your content. Please let me know. Cheers

  22. Iոcroyablement intéressant, je pense que ce poste devrait
    iոtéresser une pօte

  23. As a Newbie, I am continuously browsing online for articles that can aid me.
    Thank you

  24. www.bloglines.com on May 16th, 2014

    I every time emailed this blog post page to all my friends, since if like to read it afterward my friends will too.

  25. Aaron on May 18th, 2014

    Definitely believe that which you said. Your favorite reason seemed
    to be on the net the simplest thing to be aware of.

    I say to you, I certainly get annoyed while people think about worries that they plainly don’t know about.

    You managed to hit the nail upon the top as well as defined
    out the whole thing without having side-effects ,
    people can take a signal. Will likely be back to
    get more. Thanks

  26. Aundrea on May 19th, 2014

    Hello! I’ve been following your blog for a while now and finally got the courage
    to go ahead and give you a shout out from Dallas
    Texas! Just wanted to tell you keep up the fantastic job!

  27. cigarette electronique on May 22nd, 2014

    Hi, i feel that i saw you visited my blog so i got here to go back the prefer?.I’m attempting to find things to enhance my web site!I suppose its adequate to use some of your ideas!!

    my web page cigarette electronique

  28. travel sites for cruises on May 23rd, 2014

    Does your website have a contact page? I’m having trouble locating it but, I’d like to send you
    an email. I’ve got some suggestions for your blog you might be interested
    in hearing. Either way, great website and I look forward to seeing it expand over time.

  29. Justin on May 23rd, 2014

    I’m not sure where you’re getting your information, but good topic.

    I needs to spend some time learning much
    more or understanding more. Thanks for excellent info I was looking
    for this info for my mission.

  30. travelzoo promo code on May 24th, 2014

    That is a great tip especially to those
    new to the blogosphere. Simple but very precise info…
    Appreciate your sharing this one. A must read post!

  31. scarpe christian louboutin on May 28th, 2014

    It’s perfect time to make some plans for the future and it’s
    time to be happy. I’ve read this post and if I could
    I wish to suggest you few interesting things or suggestions.

    Perhaps you can write next articles referring to this article.
    I want to read even more things about it!

  32. inhalt website on May 29th, 2014

    Nice blog here! Also your site loads up very fast! What web host are you
    using? Can I get your affiliate link to your host?
    I wish my website loaded upp as fast as yours lol

  33. Celia on May 30th, 2014

    An intriguing discussion is worth comment. I believe that you need to publish more about this issue, it may not be a taboo matter but usually people don’t discuss
    these topics. To the next! Kind regards!!

  34. star ceiling on May 31st, 2014

    Hello, I do think your web site could possibly be having browser
    compatibility issues. When I take a look at your site in Safari, it looks fine however, when opening in Internet Explorer, it has some
    overlapping issues. I merely wanted to provide you with a quick
    heads up! Apart from that, great website!

  35. cheap celine bags for women on May 31st, 2014

    cheap celine bags for women
    You made some good points there. I looked on the net for additional information about the issue and found
    most individuals will go along with your views on this web site.

  36. gratis Chatten on June 3rd, 2014

    Not all webcam models were working in nightclubs, bars or strip clubs as many might
    think. Video chatting allows you to see facial expressions
    and physically see each other and your surroundings.
    Hangouts is video chatting on social networking done right and offers
    quick-streaming live chat, works great with Google+’s Circles feature which allows communicating with specific groups of friends, supports multi-chat, and even switches
    between different friends — depending on who is talking at
    the time.

    Review my web-site … gratis Chatten

  37. chatten met vreemden on June 3rd, 2014

    The app supports i - OS4 multitasking, which keeps connections to chat
    rooms open for 10 minutes after the app goes
    into the background. Touring with Morgan
    Page we’re kind of just all working stuff together right now.

    Ever see NFL players beat their chest like a gorilla after they just made a good play.

    Look at my site - chatten met vreemden

  38. rockwell trading on June 4th, 2014

    I loved as much as you’ll receive carried out right here.

    The sketch is tasteful, your authored material stylish. nonetheless, you command
    get bought an nervousness over that you wish be delivering the following.

    unwell unquestionably come further formerly again since exactly
    the same nearly very often inside case you shield this increase.

  39. travelocity car rental on June 4th, 2014

    Thanks for finally writing about > Contour 3.0 Code First, Member registration, profile,
    login, change password - Tim Geyssens, Umbraco developer < Liked it!

  40. m.facebook.com on June 4th, 2014

    In the identical sense, business owners would be wise to give
    their workers something to unite under. She invites that you visit her site where she’s going
    to share a proven method to start an business online.
    ” The company sees innovation as one of its core organizational competencies.

    Here is my blog post :: m.facebook.com

  41. zero dog waste bags on June 5th, 2014

    I like what you guys are up too. This sort of clever work and reporting!
    Keep up the fantastic works guys I’ve incorporated you guys to our blogroll.

  42. watch dogs on June 6th, 2014

    Definitely believe that that you said. Your favorite reason seemed to be at the web the simplest thing to be mindful of.
    I say to you, I certainly get annoyed while other folks consider concerns that they plainly don’t know about.
    You controlled to hit the nail upon the highest and outlined out the entire thing without having side-effects , people
    can take a signal. Will likely be again to get more.

    Thanks

  43. gym cables on June 10th, 2014

    Wow that was strange. I just wrote an really long comment but after I clicked submit my comment didn’t show up.

    Grrrr… well I’m not writing all that over again. Anyways, just wanted to say
    wonderful blog!

  44. api Php sms gratuit on June 10th, 2014

    I always spent my half an hour to read this webpage’s
    articles or reviews every day along with a cup of coffee.

  45. cowboy hats on June 14th, 2014

    Just desire to say your article is as astounding. The clearness in your post is simply excellent
    and i could assume you are an expert on this subject.
    Well with your permission allow me to grab your feed to keep updated with forthcoming
    post. Thanks a million and please carry on the enjoyable work.

  46. league Of legends cheat on June 14th, 2014

    Good day! Do you know if they make any plugins to protect
    against hackers? I’m kinda paranoid about losing everything I’ve worked hard on. Any recommendations?

  47. Buy Vintage on June 15th, 2014

    You really make it appear so easy along with your presentation however I find this topic to be really one thing that I think
    I might by no means understand. It sort of feels too
    complicated and extremely wide for me. I am taking a look ahead
    for your subsequent post, I’ll try to get the hang of it!

  48. Micheline on June 17th, 2014

    Every weekend i used to visit this web site, as i wish for
    enjoyment, since this this web page conations genuinely pleasant funny stuff too.

  49. Hi there! I could have sworn I’ve been to this website
    before but after checking through some of the post I realized it’s new to me.
    Nonetheless, I’m definitely glad I found it and I’ll be bookmarking
    and checking back frequently!

  50. bot dofus fiable on June 19th, 2014

    Until these files are hosted somewhere not called
    Lycos, I won’t care enough to see if they are good or not.
    Pay to play (P2P) gives you the ability to go wherever you want on the entire map, fight whatever monsters you want, and have pets, mounts
    and join armies. I’ve been hooked on it ever since, spending at least an hour
    each day running around in a virtual world with a pink haired cat-like person.

    Feel free to visit my webpage … bot dofus fiable

  51. Benny on June 25th, 2014

    Today, I went to the beach with my children. I found a sea
    shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She
    placed the shell to her ear and screamed. There was a hermit crab
    inside and it pinched her ear. She never wants to
    go back! LoL I know this is completely off topic but I had to tell someone!

  52. wifi hacking software on June 29th, 2014

    Pretty nice post. I just stumbled upon your blog and wanted to say that I have truly loved
    surfing around your weblog posts. After all I will be subscribing to your feed and
    I am hoping you write again soon!

    Feel free to surf to my web-site: wifi hacking software

  53. olympic marathon run on June 29th, 2014

    Hmm is anyone else experiencing problems with the pictures on this blog loading?

    I’m trying to determine if its a problem on my end or if it’s the blog.
    Any feed-back would be greatly appreciated.

  54. max1cheap on July 2nd, 2014

    It’s in fact very complex in this active life to listen news on Television, therefore I only use world wide web
    for that purpose, and obtain the hottest information.

  55. diatomaceous earth lungs on July 3rd, 2014

    After I originally commented I seem to have clicked the -Notify me when new comments are added- checkbox and now every
    time a comment is added I recieve four emails with the
    exact same comment. There has to be an easy method you can remove me from that service?
    Kudos!

  56. arizona auto title loan on July 5th, 2014

    Thanks for your marvelous posting! I really enjoyed reading it, you might be a
    great author.I will make sure to bookmark your blog and will often come back in the foreseeable future.
    I want to encourage continue your great job, have a nice evening!

  57. escuchar musica duranguense on July 6th, 2014

    Hi there! Do you know if they make any plugins to protect against hackers?
    I’m kinda paranoid about losing everything I’ve worked hard on. Any recommendations?

  58. Chaturbate Hack on July 7th, 2014

    This kind of first step is absolutely not
    to remove your own porn and feel you have flipped a new leaf.
    The very first portion of porn dependancy
    recovery is likewise not in relation to taking steps to never view adult again. There are many guidelines which might be employed to really get rid of porn from your life —
    but the primary you need to do will be overcome something.

    Here is my weblog Chaturbate Hack

  59. pest control training on July 7th, 2014

    ‘ The scrubby, sandy soil between Sydney and Botany Bay was ideal for rabbit
    farming. Moments later on even strength at 15:39, Chris Mc -
    Carthy scored from the same spot with assists going to Blake Doering and Nick Brunteau.
    Moles lives underground in their holes throughout
    the year.

  60. best adidas basketball shoes on July 9th, 2014

    One of the worst problems a player can face is an injury such
    as a sprained ankle, which can take you out of play for a whole season. If you have a player
    that is more of a role player then have them set multiple screens in a possession and try to force
    switches or help situations that will lead to open shots for other players.

    If a daytime camp is one’s top pick, they need to think about transportation, and location of the camp.

  61. arthrose der schulter on July 9th, 2014

    Although studies suggest that potatoes, eggplant and other plants in the nightshade family, as
    well as dairy products, are beneficial for those of
    us with arthritis, they have been known to trigger inflammation in some
    people. I was able to type sooner than I was able to write.
    It is evident that these kinds of medications could be hazardous.

  62. summoners war sky Arena cheats on July 10th, 2014

    Starting with either a Sapphire Crystal or Ruby
    Crystal is a good choice, but Fiddlesticks can work well with a Doran’s Ring or an Elixir of Brilliance and potions -
    his drain is simply that good. Empowered Battle Roar heal
    changed to 20 + (10 x level) amplified by a 1% per 1% of Rengar’s missing health
    (from 40 + (20 x level) health). When playing in windowed mode, players can now interact with the game
    even while the options menu is open While playing in windowed mode your mouse
    cursor will be constrained to the game window regardless if the options menu is open or not Pressing F9 (default hotkey) releases the mouse from the
    game window so you can interact with your desktop or other applications.

  63. Thank you a bunch for sharing this with all folks you really recognise
    what you are talking approximately! Bookmarked. Please additionally visit my
    site =). We can have a link trade arrangement between us

    Look at my webpage; jak narysowac bukiet kwiatow w wazonie

  64. Trucks on July 12th, 2014

    Thanks designed for sharing such a pleasant idea, article is good, thats why i have read it fully

  65. www.dge.ntou.edu.tw on July 16th, 2014

    My developer is trying to convince me to move to .net from PHP.
    I have always disliked the idea because of the expenses. But he’s tryiong none the
    less. I’ve been using WordPress on various websites for about a year and
    am worried about switching to another platform. I have heard very good things about blogengine.net.
    Is there a way I can transfer all my wordpress posts into it?
    Any help would be really appreciated!

    Review my web site: Tienda Nike Air Max (http://www.dge.ntou.edu.tw)

  66. best selling ranch house plans on July 19th, 2014

    At this moment I am going to do my breakfast,
    after having my breakfast coming yet again to read other news.

    Have a look at my web page … best selling ranch house plans

  67. It’s awesome to pay a visit this website and reading the views of all mates on the topic of this article, while
    I am also zealous of getting know-how.

  68. Chen on July 21st, 2014

    Hi Tim,

    Does the above code examples work in Umbraco 7? Thank you.

    Chen

  69. Duty of Heroes Hack on July 24th, 2014

    The main gain to jailbreaking an i - Phone five
    is the ability to turn it right into a Wi-Fi hotspot.
    Analysts and pundits were off the mark with that prediction, as instead Apple chose to release the i - Phone 5C as a replacement for the i
    - Phone 5, which in the past the company would have continued to sell at a $99 price point
    on contract. One of the best features found in the device is its 8 megapixel camera that further comes
    blessed with useful options.

    Check out my blog post Duty of Heroes Hack

  70. zelený čaj hubnutí on July 25th, 2014

    Do you mind if I quote a couple of your posts as long as I
    provide credit annd sources bawck to your webpage? My website iss
    in the very same niche as yours and my users would truly benefit from some of the
    information you provide here. Please let me know if this alright with you.

    Cheers!

  71. elittárs on July 28th, 2014

    Good day! I know this iis kind oof off topic but I was wondering
    if you knew where I could find a captcha plugin for my comment form?
    I’m using the same blog platform as yours and I’m having trouble finding one?
    Thanks a lot!

Leave a Reply