MVC / Validating an email address with DataAnnotation

If you’re using MVC and want to capture an email address, there is a great built-in way to validate the address. When creating your model, add the [EmailAddress] DataAnnotation like below.

 [Required]
 [EmailAddress]
 [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 3)]
 [DataType(DataType.EmailAddress)]
 [Display(Name = "Email Address")]
 public string Email { get; set; }

Then you can add to your view:

 <li>
 <%: Html.LabelFor(m => m.Email) %>
 <%: Html.TextBoxFor(m => m.Email) %>
 </li>

And if you enter an invalid email you’ll get the error:

Invalid Email Address

MVC / Validating an email address with DataAnnotation

Adding a forgot password / reset function to MVC c#

If you’re using any of the out-of-the-box mvc template projects (Visual Studio 2012 / c#), they do a great job with including functionality for user membership including log in, register and change password. However it does seem to be missing a ‘forgot password’ or ‘reset password’ function. Below is how you can quickly add this functionality by modifying the existing controllers and views:

1. Add a new view (I’m calling mine ResetPass) under the Views > Account folder:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ledme2.Models.LoginModel>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Reset Pass
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <hgroup class="title">
        <h1>Reset Your Password</h1>
    </hgroup>

    <section id="loginForm">
        <h2>Enter the username you wish to reset. An email will be sent with your password and the new password will expire in 3 hours.</h2>
        <% using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl }))
           { %>
        <%: Html.AntiForgeryToken() %>
        <%: Html.ValidationSummary(true) %>

        <fieldset>
            <legend>Enter the username you wish to reset. An email will be sent with your password and the new password will expire in 3 hours.</legend>
            <ol>
                <li>
                    <%: Html.LabelFor(m => m.UserName) %>
                    <%: Html.TextBoxFor(m => m.UserName) %>
                    <%: Html.ValidationMessageFor(m => m.UserName) %>
                </li>
            </ol>
            <input type="submit" value="Reset" />
        </fieldset>

        <% } %>

        <% if (ViewData["msg"] != null)
           { %>
        <%: ViewData["msg"] %>
        <% } %>
    </section>
</asp:Content>

<asp:Content ID="Content3" ContentPlaceHolderID="FeaturedContent" runat="server">
</asp:Content>

<asp:Content ID="Content4" ContentPlaceHolderID="ScriptsSection" runat="server">
</asp:Content>

2. Add these two methods to the AccountController.cs (I’ve left out the code w/ the email function, feel free to add your own):

 [AllowAnonymous]
        public ActionResult ResetPass(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult ResetPass(LoginModel model, string returnUrl)
        {
            if (WebSecurity.UserExists(model.UserName))
            {
                string ptoken = WebSecurity.GeneratePasswordResetToken(model.UserName, 190);
                //change to be as secure as you choose
                string tmpPass = Membership.GeneratePassword(10, 4);
                WebSecurity.ResetPassword(ptoken, tmpPass);
                //add your own email logic here
                ViewData["msg"] = "Your new password is: " + tmpPass;
                return View(model);
            }
            else
            {
                ModelState.AddModelError("", "The user name wasn't found.");
            }

            return View(model);
        }

3. Add this code to the Login.aspx view:

<p>
            <%: Html.ActionLink("Reset", "ResetPass") %> your forgotten passord?

</p>

4. Now you should get this result on the login page:

forgot1

And when clicked:
forgot2

Adding a forgot password / reset function to MVC c#

MVC 4: Code First Migrations with SQL Server – Creating & Updating the DB Schema

Creating and keeping a database schema up to date using asp.Net & MVC 4 in Visual Studio (2010 in the below process) is quite easy and efficient.

Below are some basic steps to get you going.

Step 1. Create a local or remote SQL Server db (I’m using SQL Server 2008 Developer – locally) using SQL Management Studio. Don’t create any tables, etc., just the database.

Step 2. Update the web.config file in your root folder with a connection string for the database you just created. Below is mine:

 <connectionStrings>
    <add name="sampleDBContext" 
connectionString="Data Source=.\;Initial Catalog=sampleDB;Integrated Security=SSPI" 
providerName="System.Data.SqlClient" />
  </connectionStrings>

It’s important to have the connection string name match the name of the class of your DbSet, below is my dbcontext class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace SampleApp.Models
{
    public class sampleDBContext : DbContext
    {
        public DbSet<simpleTable> simpleTable{ get; set; }

    }
}

Step 3. In the Package Manager Console (in Visual Studio), run this command to enable migrations (at the “PM>” prompt):

Enable-Migrations -ContextTypeName SampleApp.Models.sampleDBContext

You should get this result:

Code First Migrations enabled for project SampleApp.

Step 4. At this point, the database hasn’t been updated. To update and create your tables, let’s first create a migration. In the Package Manager Console, run this command to create a migration (at the “PM>” prompt):

Add-Migration InitialMig

(If you were to open the .cs file just created in your migrations folder, you’ll see the create / update commands it will run.)

Step 5. Finally, to actually update the database, run:

Update-Database

(at the “PM>” prompt). You’ll see some messages like:

Applying code-based migrations: [201209122019596_InitialMig].
Applying code-based migration: 201209122019596_InitialMig.
Running Seed method.

Now if you look in at your database in SQL Management Studio, you’ll see your changes!

Going forward: go ahead and make changes to your models, you’ll just want to run the “Add-Migration” command, with a new migration name. ie: Add-Migration Mig2 and then run Update-Database to apply the changes. Simple!

MVC 4: Code First Migrations with SQL Server – Creating & Updating the DB Schema