Click here to Skip to main content
11,482,039 members (67,017 online)
Click here to Skip to main content
Articles » Web Development » ASP.NET » General » Downloads
Add your own
alternative version

MVC Basic Site: Step 2 - Exceptions Management

, 25 Oct 2013 Ms-PL 63.1K 4.5K 129
This second article from the "MVC Basic Site" series presents in details the exceptions management rules and their implementation for an ASP.NET MVC web site, and provides some utile base classes and source code for Logging and Exceptions Management that can be reused.
MvcBasicSiteDatabase.zip
MvcBasicSiteDatabase.bak
MvcBasicSiteSourceCode.zip
MvcBasicSiteSourceCode
MvcBasicSite
CreateEventLogEntry
Properties
MvcBasic.Logic
ClassDiagram1.cd
MvcBasicSiteModel.edmx
Properties
MvcBasicSite
app_code
App_GlobalResources
ClassDiagramUI.cd
Content
Images
dd_arrow.gif
flag_De.png
flag_En.png
flag_Ro.png
HeaderLogo.png
icon-arrow.gif
themes
base
images
ui-bg_flat_0_aaaaaa_40x100.png
ui-bg_flat_75_ffffff_40x100.png
ui-bg_glass_55_fbf9ee_1x400.png
ui-bg_glass_65_ffffff_1x400.png
ui-bg_glass_75_dadada_1x400.png
ui-bg_glass_75_e6e6e6_1x400.png
ui-bg_glass_95_fef1ec_1x400.png
ui-bg_highlight-soft_75_cccccc_1x100.png
ui-icons_222222_256x240.png
ui-icons_2e83ff_256x240.png
ui-icons_454545_256x240.png
ui-icons_888888_256x240.png
ui-icons_cd0a0a_256x240.png
Controllers
Global.asax
Models
MvcBasicSite.csproj.user
Properties
Scripts
Views
Account
Home
Shared
MvcBasicSiteSourceCodeMVC4.zip
ClassDiagram1.cd
MvcBasicSiteModel.edmx
App_Data
ClassDiagramUI.cd
dd_arrow.gif
flag_De.png
flag_En.png
flag_Ro.png
HeaderLogo.png
icon-arrow.gif
animated-overlay.gif
ui-bg_flat_0_aaaaaa_40x100.png
ui-bg_flat_75_ffffff_40x100.png
ui-bg_glass_55_fbf9ee_1x400.png
ui-bg_glass_65_ffffff_1x400.png
ui-bg_glass_75_dadada_1x400.png
ui-bg_glass_75_e6e6e6_1x400.png
ui-bg_glass_95_fef1ec_1x400.png
ui-bg_highlight-soft_75_cccccc_1x100.png
ui-icons_222222_256x240.png
ui-icons_2e83ff_256x240.png
ui-icons_454545_256x240.png
ui-icons_888888_256x240.png
ui-icons_cd0a0a_256x240.png
minified
images
animated-overlay.gif
ui-bg_flat_0_aaaaaa_40x100.png
ui-bg_flat_75_ffffff_40x100.png
ui-bg_glass_55_fbf9ee_1x400.png
ui-bg_glass_65_ffffff_1x400.png
ui-bg_glass_75_dadada_1x400.png
ui-bg_glass_75_e6e6e6_1x400.png
ui-bg_glass_95_fef1ec_1x400.png
ui-bg_highlight-soft_75_cccccc_1x100.png
ui-icons_222222_256x240.png
ui-icons_2e83ff_256x240.png
ui-icons_454545_256x240.png
ui-icons_888888_256x240.png
ui-icons_cd0a0a_256x240.png
Global.asax
MvcBasicSite.csproj.user
#region Copyright (c) 2013 Raul Iloc
/*
{***************************************************************************}
{                                                                           }
{       Copyright (c) 2010  RAUL ILOC (rauliloc@yahoo.com)                  }
{       ALL RIGHTS RESERVED                                                 }
{                                                                           }
{   THE WORK IS PROVIDED UNDER THE TERMS OF THIS CODE PROJECT OPEN LICENSE. }
{   THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW.         }
{   ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE         }
{   OR COPYRIGHT LAW IS PROHIBITED.                                         }
{                                                                           }
{                                                                           }
{  BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HEREIN, YOU ACCEPT AND     }
{  AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. THE AUTHOR GRANTS YOU    }
{  THE RIGHTS CONTAINED HEREIN IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH  }
{  TERMS AND CONDITIONS. IF YOU DO NOT AGREE TO ACCEPT AND BE BOUND BY THE  }
{  TERMS OF THIS LICENSE, YOU CANNOT MAKE ANY USE OF THE WORK.              }
{                                                                           }
{***************************************************************************}
*/
#endregion Copyright (c) 2013 Raul Iloc
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using System.Data;
using System.Data.Entity;
//
using MvcBasicSite.Models;
using MvcBasic.Logic;

namespace MvcBasicSite.Controllers
{
    /// <summary>
    /// Defines the account controller.
    /// </summary>
    public class AccountController : BaseController
    {
        

        /// <summary>
        /// Change the current culture.
        /// </summary>
        /// <param name="culture">The current selected culture.</param>
        /// <returns>The action result.</returns>
        public ActionResult ChangeCurrentCulture(int culture)
        {
            //
            // Change the current culture for this user.
            //
            SiteSession.CurrentUICulture = culture;
            //
            // Cache the new current culture into the user HTTP session. 
            //
            Session["CurrentUICulture"] = culture;
            //
            // Redirect to the same page from where the request was made! 
            //
            return Redirect(Request.UrlReferrer.ToString());
        }

        /// <summary>
        /// Activate Log-On page.
        /// </summary>
        /// <returns>The view.</returns>
        public ViewResult LogOn()
        {
            //
            // Create the model.
            //
            LogOnModel model = new LogOnModel();
            model.Username = string.Empty;
            model.Password = string.Empty;
            //
            // Activate the view.
            //
            return View(model);
        }

        /// <summary>
        /// Validate the user login data.
        /// </summary>
        /// <param name="model">The Log-On model.</param>
        /// <returns>The view result.</returns>
        [HttpPost]
        public ActionResult LogOn(LogOnModel model)
        {
            if (ModelState.IsValid)
            {
                //
                // Verify the user name and password.
                //
                User user = _db.Users.FirstOrDefault(item => item.Username.ToLower() == model.Username.ToLower() && item.Password == model.Password);
                if (user == null)
                {
                    ModelState.AddModelError("", Resources.Resource.LogOnErrorMessage);
                    //
                    return View(model);
                }
                else
                {
                    //
                    // User logined succesfully ==> create a new site session!
                    //
                    FormsAuthentication.SetAuthCookie(model.Username, false);
                    //
                    SiteSession siteSession = new SiteSession(_db, user);
                    Session["SiteSession"] = siteSession; // Cache the user login data!
                    //
                    // Log a message about the user LogOn.
                    //
                    MvcBasicLog.LogMessage(string.Format("LogOn for user: {0}", siteSession.Username));
                    //
                    // Redirect to Home page.
                    //
                    return RedirectToAction("Index", "Home");
                }
            }
            //
            // If we got this far, something failed, redisplay form!
            //
            return View(model);
        }
        
        /// <summary>
        /// Log off.
        /// </summary>
        /// <returns>The action result.</returns>
        [Authorize]
        public ActionResult LogOff()
        {
            SiteSession.LogOff(this.Session);
            //
            return RedirectToAction("Index", "Home");
        }

        /// <summary>
        /// Get the register page.
        /// </summary>
        /// <remarks>
        /// GET: /Account/Register
        /// </remarks>
        /// <returns>The action result.</returns>
        public ActionResult Register()
        {
            User registerUser = new User();
            registerUser.Address = new Address();
            //
            return View(registerUser);
        }

        /// <summary>
        /// Register the user data.
        /// </summary>
        /// <remarks>
        /// POST: /Account/Register
        /// </remarks>
        /// <param name="model">The model.</param>
        /// <returns>The view result.</returns>
        [HttpPost]
        public ViewResult Register(User model, Address modelAddress)
        {
            if (ModelState.IsValid)
            {
                //
                // Verify if exists other user with the same username.
                //
                User existUser = _db.Users.FirstOrDefault(item => item.Username.ToLower() == model.Username.ToLower());
                if (existUser == null)
                {
                    //
                    // Save the user data.
                    //
                    MvcBasic.Logic.User user = new MvcBasic.Logic.User();
                    user.Username = model.Username;
                    user.Password = model.Password;
                    user.UserRole = UserRoles.SimpleUser;
                    user.Email = model.Email;
                    //
                    if (modelAddress.CountryID <= 0)
                        modelAddress.CountryID = null;
                    //
                    user.Address = modelAddress;
                    //
                    _db.Users.AddObject(user);
                    _db.SaveChanges(); 
                    //
                    // Go to RegisterFinalized page!
                    //
                    return View("RegisterFinalized");
                }
                else
                {
                    //
                    // Exists other user with the same username, so show the error message.
                    //
                    ModelState.AddModelError("", Resources.Resource.RegisterInvalidUsername);
                    model.Address = modelAddress;
                    //
                    return View(model);
                }
            }
            //
            // If we got this far, something failed, redisplay form!
            //
            model.Address = modelAddress;
            //
            return View(model);
        }

        /// <summary>
        /// Cancel the user registration.
        /// </summary>
        /// <remarks>
        /// GET: /Account/CancelRegister
        /// </remarks>
        /// <returns>The action result.</returns>
        public ActionResult CancelRegister()
        {
            return RedirectToAction("LogOn");
        }

        /// <summary>
        /// Activate "My Account" page.
        /// </summary>
        /// <returns>The action result.</returns>
        [Authorize]
        public ActionResult MyAccount()
        {
            // TO DO!
            return View();
        }

        /// <summary>
        /// Test an error.
        /// </summary>
        /// <returns>The action result.</returns>
        public ActionResult TestExpectedException()
        {
            SiteSession siteSession = this.CurrentSiteSession;
            //
            try
            {
                //
                // Invoke a method that could generate an exception!
                //
                int count = MvcBasic.Logic.User.GetNormalSearchCount(siteSession.UserID, new object[] { "al*", "231" });
                //
                // TO DO!
                //...

            }
            catch (MvcBasicException ex)
            {
                MvcBasicLog.LogException(ex);
                ModelState.AddModelError("", Resources.Resource.ErrorLoadingData);
            }
            //
            // Stay in "MyAcount" page.
            //
            return View("MyAccount");
        }

        /// <summary>
        /// Test an unhandled exception.
        /// </summary>
        /// <returns>The action result.</returns>
        public ActionResult TestUnhandledException()
        {
            //
            // Next line of code will try to open an view that does not exist ==> Exception.
            //
            return View();
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)

Share

About the Author

Raul Iloc
Program Manager SOFTVISION
Romania Romania
I am Project Manager with about 19 years working experience in software development and about 14 years as Project Manager and Architect.
Follow on   LinkedIn

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150520.1 | Last Updated 25 Oct 2013
Article Copyright 2013 by Raul Iloc
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid