The next generation of the Teknik Services. Written in ASP.NET. Fork for blog tags.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Global.asax.cs 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. using System.Web.Optimization;
  7. using System.Web.Routing;
  8. using Teknik.Models;
  9. using System.Data.Entity;
  10. using System.Web.Security;
  11. using Teknik.Migrations;
  12. using System.Data.Entity.Migrations;
  13. using Teknik.Areas.Users.Models;
  14. using System.ComponentModel;
  15. using Teknik.Areas.Error.Controllers;
  16. using System.Web.Helpers;
  17. using System.Diagnostics;
  18. using System.Collections.Specialized;
  19. using Teknik.Configuration;
  20. using Piwik.Tracker;
  21. using System.Web.UI;
  22. using Teknik.Helpers;
  23. namespace Teknik
  24. {
  25. public class MvcApplication : System.Web.HttpApplication
  26. {
  27. protected void Application_Start()
  28. {
  29. ViewEngines.Engines.Clear();
  30. ViewEngines.Engines.Add(new CustomRazorViewEngine());
  31. Database.SetInitializer(new MigrateDatabaseToLatestVersion<TeknikEntities, Migrations.Configuration>());
  32. AreaRegistration.RegisterAllAreas();
  33. FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
  34. RouteConfig.RegisterRoutes(RouteTable.Routes);
  35. BundleConfig.RegisterBundles(BundleTable.Bundles);
  36. }
  37. protected void Application_BeginRequest(object sender, EventArgs e)
  38. {
  39. HttpContext context = HttpContext.Current;
  40. var stopwatch = new Stopwatch();
  41. HttpContext.Current.Items["Stopwatch"] = stopwatch;
  42. stopwatch.Start();
  43. }
  44. protected void Application_EndRequest(object sender, EventArgs e)
  45. {
  46. HttpContext context = HttpContext.Current;
  47. Stopwatch stopwatch = (Stopwatch)context.Items["Stopwatch"];
  48. stopwatch.Stop();
  49. TimeSpan ts = stopwatch.Elapsed;
  50. string elapsedTime = String.Format("{0} seconds", ts.TotalSeconds);
  51. context.Response.AppendHeader("GenerationTime", elapsedTime);
  52. // Allow this domain
  53. string origin = context.Request.Headers.Get("Origin");
  54. if (!string.IsNullOrEmpty(origin) && !Request.IsLocal)
  55. {
  56. context.Response.AppendHeader("Access-Control-Allow-Origin", origin);
  57. }
  58. }
  59. protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
  60. {
  61. if (FormsAuthentication.CookiesSupported == true)
  62. {
  63. if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
  64. {
  65. //let us take out the username now
  66. string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
  67. List<string> roles = new List<string>();
  68. using (TeknikEntities entities = new TeknikEntities())
  69. {
  70. User user = entities.Users.SingleOrDefault(u => u.Username == username);
  71. if (user != null)
  72. {
  73. foreach (Group grp in user.Groups)
  74. {
  75. foreach (Role role in grp.Roles)
  76. {
  77. if (!roles.Contains(role.Name))
  78. {
  79. roles.Add(role.Name);
  80. }
  81. }
  82. }
  83. }
  84. }
  85. //Let us set the Pricipal with our user specific details
  86. HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(
  87. new System.Security.Principal.GenericIdentity(username, "Forms"), roles.ToArray());
  88. }
  89. }
  90. }
  91. protected void Application_Error(object sender, EventArgs e)
  92. {
  93. Exception exception = Server.GetLastError();
  94. Response.Clear();
  95. HttpException httpException = exception as HttpException;
  96. RouteData routeData = new RouteData();
  97. routeData.DataTokens.Add("namespaces", new[] { typeof(ErrorController).Namespace });
  98. routeData.DataTokens.Add("area", "Error");
  99. routeData.Values.Add("controller", "Error");
  100. if (httpException == null)
  101. {
  102. routeData.Values.Add("action", "Exception");
  103. }
  104. else //It's an Http Exception, Let's handle it.
  105. {
  106. switch (httpException.GetHttpCode())
  107. {
  108. case 401:
  109. // Unauthorized.
  110. routeData.Values.Add("action", "Http401");
  111. break;
  112. case 403:
  113. // Forbidden.
  114. routeData.Values.Add("action", "Http403");
  115. break;
  116. case 404:
  117. // Page not found.
  118. routeData.Values.Add("action", "Http404");
  119. break;
  120. case 500:
  121. // Server error.
  122. routeData.Values.Add("action", "Http500");
  123. break;
  124. // Here you can handle Views to other error codes.
  125. // I choose a General error template
  126. default:
  127. routeData.Values.Add("action", "General");
  128. break;
  129. }
  130. }
  131. // Pass exception details to the target error View.
  132. routeData.Values.Add("exception", exception);
  133. // Clear the error on server.
  134. Server.ClearError();
  135. // Avoid IIS7 getting in the middle
  136. Response.TrySkipIisCustomErrors = true;
  137. // If it is an Ajax request, we should respond with Json data, otherwise redirect
  138. if (IsAjaxRequest())
  139. {
  140. string jsonResult = string.Empty;
  141. if (httpException == null)
  142. {
  143. jsonResult = Json.Encode(new { error = new { type = "Exception", message = exception.Message } });
  144. }
  145. else
  146. {
  147. jsonResult = Json.Encode(new { error = new { type = "Http", statuscode = httpException.GetHttpCode(), message = exception.Message } });
  148. }
  149. Response.Write(jsonResult);
  150. }
  151. else
  152. {
  153. // Call target Controller and pass the routeData.
  154. IController errorController = new ErrorController();
  155. errorController.Execute(new RequestContext(
  156. new HttpContextWrapper(Context), routeData));
  157. }
  158. }
  159. //This method checks if we have an AJAX request or not
  160. private bool IsAjaxRequest()
  161. {
  162. //The easy way
  163. bool isAjaxRequest = (Request["X-Requested-With"] == "XMLHttpRequest")
  164. || ((Request.Headers != null)
  165. && (Request.Headers["X-Requested-With"] == "XMLHttpRequest"));
  166. //If we are not sure that we have an AJAX request or that we have to return JSON
  167. //we fall back to Reflection
  168. if (!isAjaxRequest)
  169. {
  170. try
  171. {
  172. //The controller and action
  173. string controllerName = Request.RequestContext.
  174. RouteData.Values["controller"].ToString();
  175. string actionName = Request.RequestContext.
  176. RouteData.Values["action"].ToString();
  177. //We create a controller instance
  178. DefaultControllerFactory controllerFactory = new DefaultControllerFactory();
  179. Controller controller = controllerFactory.CreateController(
  180. Request.RequestContext, controllerName) as Controller;
  181. //We get the controller actions
  182. ReflectedControllerDescriptor controllerDescriptor =
  183. new ReflectedControllerDescriptor(controller.GetType());
  184. ActionDescriptor[] controllerActions =
  185. controllerDescriptor.GetCanonicalActions();
  186. //We search for our action
  187. foreach (ReflectedActionDescriptor actionDescriptor in controllerActions)
  188. {
  189. if (actionDescriptor.ActionName.ToUpper().Equals(actionName.ToUpper()))
  190. {
  191. //If the action returns JsonResult then we have an AJAX request
  192. if (actionDescriptor.MethodInfo.ReturnType
  193. .Equals(typeof(JsonResult)))
  194. return true;
  195. }
  196. }
  197. }
  198. catch
  199. {
  200. }
  201. }
  202. return isAjaxRequest;
  203. }
  204. }
  205. }