The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
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 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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.Profile.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. //// Handle Piwik Tracking if enabled
  59. //Config config = Config.Load();
  60. //if (config.PiwikConfig.Enabled)
  61. //{
  62. // try
  63. // {
  64. // string sub = context.Request.RequestContext.RouteData.Values["sub"].ToString();
  65. // if (string.IsNullOrEmpty(sub))
  66. // {
  67. // sub = context.Request.Url.AbsoluteUri.GetSubdomain();
  68. // }
  69. // string title = config.Title;
  70. // Page page = HttpContext.Current.Handler as Page;
  71. // if (page != null)
  72. // {
  73. // title = page.Title;
  74. // }
  75. // var newContext = ((HttpApplication)sender).Context;
  76. // Tracking.TrackPageView(new HttpRequestWrapper(newContext.Request), title, sub);
  77. // }
  78. // catch (Exception ex)
  79. // {
  80. // }
  81. //}
  82. }
  83. protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
  84. {
  85. if (FormsAuthentication.CookiesSupported == true)
  86. {
  87. if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
  88. {
  89. //let us take out the username now
  90. string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
  91. List<string> roles = new List<string>();
  92. using (TeknikEntities entities = new TeknikEntities())
  93. {
  94. User user = entities.Users.Include("Groups").Include("Groups.Roles").SingleOrDefault(u => u.Username == username);
  95. if (user != null)
  96. {
  97. foreach (Group grp in user.Groups)
  98. {
  99. foreach (Role role in grp.Roles)
  100. {
  101. if (!roles.Contains(role.Name))
  102. {
  103. roles.Add(role.Name);
  104. }
  105. }
  106. }
  107. }
  108. }
  109. //Let us set the Pricipal with our user specific details
  110. HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(
  111. new System.Security.Principal.GenericIdentity(username, "Forms"), roles.ToArray());
  112. }
  113. }
  114. }
  115. protected void Application_Error(object sender, EventArgs e)
  116. {
  117. Exception exception = Server.GetLastError();
  118. Response.Clear();
  119. HttpException httpException = exception as HttpException;
  120. RouteData routeData = new RouteData();
  121. routeData.DataTokens.Add("namespaces", new[] { typeof(ErrorController).Namespace });
  122. routeData.DataTokens.Add("area", "Error");
  123. routeData.Values.Add("controller", "Error");
  124. if (httpException == null)
  125. {
  126. routeData.Values.Add("action", "Exception");
  127. }
  128. else //It's an Http Exception, Let's handle it.
  129. {
  130. switch (httpException.GetHttpCode())
  131. {
  132. case 401:
  133. // Unauthorized.
  134. routeData.Values.Add("action", "Http401");
  135. break;
  136. case 403:
  137. // Forbidden.
  138. routeData.Values.Add("action", "Http403");
  139. break;
  140. case 404:
  141. // Page not found.
  142. routeData.Values.Add("action", "Http404");
  143. break;
  144. case 500:
  145. // Server error.
  146. routeData.Values.Add("action", "Http500");
  147. break;
  148. // Here you can handle Views to other error codes.
  149. // I choose a General error template
  150. default:
  151. routeData.Values.Add("action", "General");
  152. break;
  153. }
  154. }
  155. // Pass exception details to the target error View.
  156. routeData.Values.Add("exception", exception);
  157. // Clear the error on server.
  158. Server.ClearError();
  159. // Avoid IIS7 getting in the middle
  160. Response.TrySkipIisCustomErrors = true;
  161. // If it is an Ajax request, we should respond with Json data, otherwise redirect
  162. if (IsAjaxRequest())
  163. {
  164. string jsonResult = string.Empty;
  165. if (httpException == null)
  166. {
  167. jsonResult = Json.Encode(new { error = new { type = "Exception", message = exception.Message } });
  168. }
  169. else
  170. {
  171. jsonResult = Json.Encode(new { error = new { type = "Http", statuscode = httpException.GetHttpCode(), message = exception.Message } });
  172. }
  173. Response.Write(jsonResult);
  174. }
  175. else
  176. {
  177. // Call target Controller and pass the routeData.
  178. IController errorController = new ErrorController();
  179. errorController.Execute(new RequestContext(
  180. new HttpContextWrapper(Context), routeData));
  181. }
  182. }
  183. //This method checks if we have an AJAX request or not
  184. private bool IsAjaxRequest()
  185. {
  186. //The easy way
  187. bool isAjaxRequest = (Request["X-Requested-With"] == "XMLHttpRequest")
  188. || ((Request.Headers != null)
  189. && (Request.Headers["X-Requested-With"] == "XMLHttpRequest"));
  190. //If we are not sure that we have an AJAX request or that we have to return JSON
  191. //we fall back to Reflection
  192. if (!isAjaxRequest)
  193. {
  194. try
  195. {
  196. //The controller and action
  197. string controllerName = Request.RequestContext.
  198. RouteData.Values["controller"].ToString();
  199. string actionName = Request.RequestContext.
  200. RouteData.Values["action"].ToString();
  201. //We create a controller instance
  202. DefaultControllerFactory controllerFactory = new DefaultControllerFactory();
  203. Controller controller = controllerFactory.CreateController(
  204. Request.RequestContext, controllerName) as Controller;
  205. //We get the controller actions
  206. ReflectedControllerDescriptor controllerDescriptor =
  207. new ReflectedControllerDescriptor(controller.GetType());
  208. ActionDescriptor[] controllerActions =
  209. controllerDescriptor.GetCanonicalActions();
  210. //We search for our action
  211. foreach (ReflectedActionDescriptor actionDescriptor in controllerActions)
  212. {
  213. if (actionDescriptor.ActionName.ToUpper().Equals(actionName.ToUpper()))
  214. {
  215. //If the action returns JsonResult then we have an AJAX request
  216. if (actionDescriptor.MethodInfo.ReturnType
  217. .Equals(typeof(JsonResult)))
  218. return true;
  219. }
  220. }
  221. }
  222. catch
  223. {
  224. }
  225. }
  226. return isAjaxRequest;
  227. }
  228. }
  229. }