Source

main-vinayFork / Source / WebClient / Web.Client / Global.asax.cs

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using DataUp.Web.BizLogic;
using DataUp.Web.Client.Controllers;
using DataUp.Web.Common;
using DataUp.Web.DataLayer;
using Microsoft.Practices.Unity;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.ServiceRuntime;

namespace DataUp.Web.Client
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        private static UnityContainer container;

        /// <summary>
        /// Gets the parent unity container.
        /// </summary>
        public static UnityContainer ParentUnityContainer
        {
            get
            {
                return container;
            }
        }

        protected void Application_Start()
        {
            CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSettingPublisher) =>
            {
                configSettingPublisher(ConfigReader<string>.GetSetting(configName));
            });

            AreaRegistration.RegisterAllAreas();
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
            RegisterUnityContainer();
        }

        protected void Application_Error(object sender, EventArgs e)
        {
            var httpContext = ((MvcApplication)sender).Context;
            var currentController = " ";
            var currentAction = " ";
            var currentRouteData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));
            if (currentRouteData != null)
            {
                if (currentRouteData.Values["controller"] != null && !String.IsNullOrEmpty(currentRouteData.Values["controller"].ToString()))
                {
                    currentController = currentRouteData.Values["controller"].ToString();
                }
                if (currentRouteData.Values["action"] != null && !String.IsNullOrEmpty(currentRouteData.Values["action"].ToString()))
                {
                    currentAction = currentRouteData.Values["action"].ToString();
                }
            }
            var ex = Server.GetLastError();
            if (RoleEnvironment.IsAvailable)
            {
                Trace.TraceInformation(string.Format("Error details : Controller Name : {0}, Action :{1}, Exception Message {2} and Stack Trace {3}", currentController, currentAction, ex.Message, ex.StackTrace));
            }
            else
            {
                LogErrorToFile(ex);
            }
            var controller = new ErrorController();
            var routeData = new RouteData();
            httpContext.ClearError();
            httpContext.Response.Clear();
            httpContext.Response.StatusCode = ex is HttpException ? ((HttpException)ex).GetHttpCode() : 500;
            httpContext.Response.TrySkipIisCustomErrors = true;
            routeData.Values["controller"] = "Error";
            routeData.Values["action"] = "Index";
            controller.ViewData.Model = new HandleErrorInfo(ex, currentController, currentAction);
            ((IController)controller).Execute(new RequestContext(new HttpContextWrapper(httpContext), routeData));
        }

        /// <summary>
        /// Application Initialize 
        /// </summary>
        public override void Init()
        {
            this.EndRequest += this.EndRequestHandler;
            base.Init();
        }

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        }

        /// <summary>
        /// Creates an instance of UnityContainer and registers the instances which needs to be injected
        /// to Controllers/Views/Services, etc.
        /// </summary>
        private static void RegisterUnityContainer()
        {
            container = new UnityContainer();

            container.RegisterType<DataUpEntities>(
                    new PerRequestLifetimeManager(), new InjectionConstructor(ConfigReader<string>.GetSetting("DataUpEntities")));

            RegisterRepositories(container);
            RegisterServices(container);

            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
        }

        /// <summary>
        /// Registers the required repositories which is required for all the controllers.
        /// </summary>
        /// <param name="container">Instance of unity container</param>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "TODO: Need to refractor.")]
        private static void RegisterRepositories(UnityContainer container)
        {
            if (container != null)
            {
                container.RegisterType<IBlobDataRepository, BlobDataRepository>(new ContainerControlledLifetimeManager());
                container.RegisterType<IDocumentStoreRepository, DocumentStoreRepository>(new PerRequestLifetimeManager());
                container.RegisterType<IUserRepository, UserRepository>(new PerRequestLifetimeManager());
            }
        }

        /// <summary>
        /// Registers the required services which is required for all the controllers.
        /// </summary>
        /// <param name="container">Instance of unity container</param>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
        private static void RegisterServices(UnityContainer container)
        {
            if (container != null)
            {
                container.RegisterType<IBlobService, BlobService>(new ContainerControlledLifetimeManager());
                container.RegisterType<IProfileService, ProfileService>(new PerRequestLifetimeManager());
                container.RegisterType<IUploadService, UploadService>(new PerRequestLifetimeManager());
                container.RegisterType<IDocumentService, DocumentService>(new PerRequestLifetimeManager());
                container.RegisterType<IExcelService, ExcelService>(new PerRequestLifetimeManager());
                container.RegisterType<IRepositoryService, RepositoryService>(new PerRequestLifetimeManager());
            }
        }

        /// <summary>
        /// End request handler
        /// </summary>
        /// <param name="sender">sender object</param>
        /// <param name="e">event arguments</param>
        private void EndRequestHandler(object sender, EventArgs e)
        {
            // This is a workaround since subscribing to HttpContext.Current.ApplicationInstance.EndRequest 
            // from HttpContext.Current.ApplicationInstance.BeginRequest does not work. 
            IEnumerable<PerRequestLifetimeManager> perRequestManagers =
                container.Registrations
                    .Select(r => r.LifetimeManager)
                    .OfType<PerRequestLifetimeManager>()
                    .ToArray();

            foreach (var manager in perRequestManagers)
            {
                manager.Dispose();
            }
        }

        /// <summary>
        /// Method to write the log file to the base directory
        /// </summary>
        /// <param name="objException">exception object</param>
        private void LogErrorToFile(Exception objException)
        {
            string strException = string.Empty;
            try
            {
                StreamWriter sw = new StreamWriter(GetLogFilePath(), true);
                sw.WriteLine("Source        : " + objException.Source.ToString().Trim());
                sw.WriteLine("Method        : " + objException.TargetSite.Name.ToString());
                sw.WriteLine("Date        : " + DateTime.Now.ToShortDateString());
                sw.WriteLine("Time        : " + DateTime.Now.ToShortTimeString());                
                sw.WriteLine("Error        : " + objException.Message.ToString().Trim());
                sw.WriteLine("Stack Trace    : " + objException.StackTrace.ToString().Trim());
                sw.WriteLine("^^-------------------------------------------------------------------^^");
                sw.Flush();
                sw.Close();
            }
            catch (Exception ex)
            {
             EventLog.WriteEntry("Error in writting Error Log file,details is "+ ex.Message,"DataUp", EventLogEntryType.Error);   
            }
        }

        /// <summary>
        /// Method to get the log file path
        /// </summary>
        /// <returns></returns>
        private static string GetLogFilePath()
        {
            try
            {
                // get the base directory
                string baseDir = AppDomain.CurrentDomain.BaseDirectory + "Logs";
                                
                //create a text file
                
                if (!Directory.Exists(baseDir))
                       Directory.CreateDirectory(baseDir);

                // search the file below the current directory
                string retFilePath = baseDir + "//" + "Error_" + DateTime.Today.Date.ToShortDateString().Replace("/","_") + ".txt";

                // if exists, return the path
                if (File.Exists(retFilePath) == true)
                    return retFilePath;
                    FileStream fs = new FileStream(retFilePath,
                          FileMode.OpenOrCreate, FileAccess.ReadWrite);
                    fs.Close();
                
                return retFilePath;
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }
    }
}