Click here to Skip to main content
15,860,943 members
Articles / Web Development / ASP.NET

MVC Basic Site: Step 2 - Exceptions Management

Rate me:
Please Sign up or sign in to vote.
4.90/5 (46 votes)
25 Oct 2013Ms-PL16 min read 144.8K   5.4K   135  
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.
#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.Threading;
using System.Globalization;
using System.Web.Mvc;
using System.Web.Security;
//
using MvcBasic.Logic;


namespace MvcBasicSite.Models
{
    /// <summary>
    /// Defines the site session.
    /// </summary>
    /// <remarks>
    /// Used to cache only the needed data for the current user!
    /// </remarks>
    public class SiteSession
    {
        /// <summary>
        /// Gets or sets the user ID.
        /// </summary>
        public int UserID { get; set; }
        /// <summary>
        /// Gets or sets the username.
        /// </summary>
        public string Username { get; set; }
        /// <summary>
        /// Gets or sets the user role.
        /// </summary>
        public UserRoles UserRole { get; set; }
        /// <summary>
        /// Gets or sets the current UI culture.
        /// </summary>
        /// <remarks>
        /// Values meaning: 0 = InvariantCulture (en-US), 1 = ro-RO, 2 = de-DE.
        /// </remarks>
        public static int CurrentUICulture
        {
            get
            {
                if (Thread.CurrentThread.CurrentUICulture.Name == "ro-RO")
                    return 1;
                else if (Thread.CurrentThread.CurrentUICulture.Name == "de-DE")
                    return 2;
                else
                    return 0;
            }
            set
            {
                //
                // Set the thread's CurrentUICulture.
                //
                if (value == 1)
                    Thread.CurrentThread.CurrentUICulture = new CultureInfo("ro-RO");
                else if (value == 2)
                    Thread.CurrentThread.CurrentUICulture = new CultureInfo("de-DE");
                else
                    Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;
                //
                // Set the thread's CurrentCulture the same as CurrentUICulture.
                //
                Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture;
            }
        }

        /// <summary>
        /// Initializes a new instance of the SiteSession class.
        /// </summary>
        /// <param name="db">The data context.</param>
        /// <param name="user">The current user.</param>
        public SiteSession(MvcBasicSiteEntities db, User user)
        {
            this.UserID = user.ID;
            this.Username = user.Username;
            this.UserRole = user.UserRole;
            //
            // TO DO: Cache other user settings!
            //
        }

        /// <summary>
        /// Get countries list ready to be used in UI. 
        /// </summary>
        /// <param name="dataContext">The data context.</param>
        public static List<SelectListItem> GetCountryList()
        {
            List<SelectListItem> list = new List<SelectListItem>();
            //
            using (MvcBasicSiteEntities dataContext = new MvcBasicSiteEntities())
            {
                foreach (Country country in dataContext.Countries)
                {
                    SelectListItem selectItem = new SelectListItem { Text = country.Name, Value = country.ID.ToString() };
                    //
                    list.Add(selectItem);
                }
            }
            //
            return list;
        }

        /// <summary>
        /// Log off the current user.
        /// </summary>
        /// <param name="httpSession">The current HTTP session.</param>
        public static void LogOff(HttpSessionStateBase httpSession)
        {
            //
            // Write in the event log the message about the user's Log Off.
            // Note that could be situations that this code was invoked from "Error" page 
            // after the current user session has expired, or before the user to login!
            //
            SiteSession siteSession = (httpSession["SiteSession"] == null ? null : (SiteSession)httpSession["SiteSession"]);
            if(siteSession != null)
                MvcBasicLog.LogMessage(string.Format("LogOn for user: {0}", siteSession.Username));
            //
            // Log Off the curent user and clear its site session cache.
            //
            FormsAuthentication.SignOut();
            httpSession["SiteSession"] = null;
        }
    }
}

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)


Written By
Romania Romania
I have about 20 years experiences in leading software projects and teams and about 25 years of working experience in software development (SW Developer, SW Lead, SW Architect, SW PM, SW Manager/Group Leader).

Comments and Discussions