Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3785822
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 19, 20262026-05-19T11:35:16+00:00 2026-05-19T11:35:16+00:00

UPDATE – Due to lack of explanation from my side, I’ve rewritten the post.

  • 0

UPDATE – Due to lack of explanation from my side, I’ve rewritten the post.

What do you think about using Code Contracts to throw exceptions on invalid input?
(I’m coding against a contract for my Service which requires the UserName not to be null or contain whitespaces)

MembershipServiceContracts.cs – Located in the service layer in a subfolder

[ContractClassFor(typeof (IMemberShipService))]
internal abstract class MemberShipServiceContracts : IMemberShipService
{
    #region IMemberShipService Members

    public MembershipCreateStatus CreateUser(string userName, string password, string email)
    {
        Contract.Requires(!String.IsNullOrWhiteSpace(userName), "Test");
        Contract.Requires(!String.IsNullOrWhiteSpace(password));
        Contract.Requires(!String.IsNullOrWhiteSpace(email));

        return default(MembershipCreateStatus);
    }

    #endregion

}

MembershipService.cs – Located in my service layer

[ContractClass(typeof (MemberShipServiceContracts))]
public interface IMemberShipService
{
    MembershipCreateStatus CreateUser(string userName, string password, string email);
}

public class MemberShipService : IMemberShipService
{
    private readonly MembershipProvider _provider;

    public MemberShipService()
        : this(null)
    { }

    public MemberShipService(MembershipProvider provider)
    {
        _provider = provider ?? Membership.Provider;
    }

    #region IMemberShipService Members

    public MembershipCreateStatus CreateUser(string userName, string password, string email)
    {
        MembershipCreateStatus status;
        _provider.CreateUser(userName, password, email, null, null, true, null, out status);

        return status;
    }

    #endregion
}

AccountController.cs – located at the UI layer

Now this is the interesting part…

Should I use:

    [Authorize(Roles = "Developer")]
    [HttpPost]
    public ActionResult Create(CreateUserViewModel model)
    {
        if (!String.IsNullOrEmpty(model.UserName))
        {
            throw new ArgumentException("UserName May not be null or contain only white spaces.", model.UserName);
        }

        if (!String.IsNullOrEmpty(model.Password))
        {
            throw new ArgumentException("Password May not be null or contain only white spaces", model.Password);
        }

        if (!String.IsNullOrEmpty(model.Email))
        {
            throw new ArgumentException("Email May not be null or contain only white spaces", model.Email);
        }

        if (!ModelState.IsValid)
        {
            return Json("Model validation failed");
        }

        MembershipCreateStatus newUser = _memberShipService.CreateUser(model.UserName, model.Password,
                model.Email);

        return Json(newUser != MembershipCreateStatus.Success ? "Failed" : "Success");
    }

or:

[Authorize(Roles = "Developer")]
[HttpPost]
public ActionResult Create(CreateUserViewModel model)
{
    Contract.Requires<ArgumentException>(!String.IsNullOrWhiteSpace(model.UserName),
            "UserName May not be null or contain only white spaces.");

    Contract.Requires<ArgumentException>(!String.IsNullOrWhiteSpace(model.Password),
            "Password May not be null or contain only white spaces");

    Contract.Requires<ArgumentException>(!String.IsNullOrWhiteSpace(model.Email),
            "Email May not be null or contain only white spaces");

    if (!ModelState.IsValid)
    {
        return Json("Model validation failed");
    }

    MembershipCreateStatus newUser = _memberShipService.CreateUser(model.UserName, model.Password,
            model.Email);

    return Json(newUser != MembershipCreateStatus.Success ? "Failed" : "Success");
}

to throw the an exception if the code contracts for the CreateUser() method isnt fulfilled?

Thanks in advance.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-19T11:35:17+00:00Added an answer on May 19, 2026 at 11:35 am

    A failure in a Code Contract indicates that your code has a serious bug that should be fixed. It doesn’t replace validation of user input. Rather, you would first validate your user input, then attempt to process the data if determined to be valid (otherwise prompt the user to re-enter). If you then don’t satisfy the target contract with your valid data, then an uncatchable exception will be thrown as you pretty obviously have a bug.

    I hoped it would be a silver bullet but quickly realised I still needed my validation. After that, I grew to really love the way code contracts will replace all of my usual guard code.

    Think of all the times you would get a NullReferenceException (too many for me!). Code Contracts can take that pain all away.

    R.

    P.s. Also, don’t use contracts to validate security-sensitive data as code contracts can be turned off at runtime…

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

UPDATE: Solution at bottom. I recently switched from using a set up such as
UPDATE May this post be helpful for coders using RichTextBoxes. The Match is correct
UPDATE: It looks like my 13.0.1 is calling code from this diffed CharMatcher. http://code.google.com/p/guava-libraries/source/diff?spec=svn69ad96b719d7cd3d872a948d7454f17b816a21c2&r=464b0cfab7c3b6713c35e6f3ae7426542668c77b&format=side&path=/guava/src/com/google/common/base/CharMatcher.java
Update : This is no longer an issue from C# 6, which has introduced
UPDATE TABLE1 set TABLE1.col1 = TABLE2.col1 FROM TABLE2 INNER JOIN TABLE3 ON COL2 =
Update Table1 set name = (select top 1 a.col from Table2 a where Table1.num
UPDATE: Sorry I was wrong with my assumption of the problem. Its due to
UPDATE: Sorry, forgot to include some of the code (face-palm). I included it in
Update (on top because the post is so long) Alright. New developments. When I
UPDATE 9/12/2012: I shared my code with a co-worker and everything worked fine for

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.