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 6.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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. AntiForgeryConfig.RequireSsl = true;
  34. FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
  35. RouteConfig.RegisterRoutes(RouteTable.Routes);
  36. BundleConfig.RegisterBundles(BundleTable.Bundles);
  37. }
  38. protected void Application_BeginRequest(object sender, EventArgs e)
  39. {
  40. // Start the generation time stopwatcher
  41. var stopwatch = new Stopwatch();
  42. HttpContext.Current.Items["Stopwatch"] = stopwatch;
  43. stopwatch.Start();
  44. }
  45. protected void Application_EndRequest(object sender, EventArgs e)
  46. {
  47. HttpContext context = HttpContext.Current;
  48. // Set the generation time in the header
  49. Stopwatch stopwatch = (Stopwatch)context.Items["Stopwatch"];
  50. stopwatch.Stop();
  51. TimeSpan ts = stopwatch.Elapsed;
  52. string elapsedTime = String.Format("{0} seconds", ts.TotalSeconds);
  53. context.Response.AppendHeader("GenerationTime", elapsedTime);
  54. // Allow this domain, or everything if local
  55. string origin = (Request.IsLocal) ? "*" : context.Request.Headers.Get("Origin");
  56. if (!string.IsNullOrEmpty(origin))
  57. {
  58. context.Response.AppendHeader("Access-Control-Allow-Origin", origin);
  59. }
  60. }
  61. protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
  62. {
  63. if (FormsAuthentication.CookiesSupported == true)
  64. {
  65. if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
  66. {
  67. //let us take out the username now
  68. string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
  69. List<string> roles = new List<string>();
  70. using (TeknikEntities entities = new TeknikEntities())
  71. {
  72. User user = entities.Users.SingleOrDefault(u => u.Username == username);
  73. if (user != null)
  74. {
  75. foreach (Group grp in user.Groups)
  76. {
  77. foreach (Role role in grp.Roles)
  78. {
  79. if (!roles.Contains(role.Name))
  80. {
  81. roles.Add(role.Name);
  82. }
  83. }
  84. }
  85. }
  86. }
  87. //Let us set the Pricipal with our user specific details
  88. HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(
  89. new System.Security.Principal.GenericIdentity(username, "Forms"), roles.ToArray());
  90. }
  91. }
  92. }
  93. protected void Application_Error(object sender, EventArgs e)
  94. {
  95. Exception exception = Server.GetLastError();
  96. Response.Clear();
  97. HttpException httpException = exception as HttpException;
  98. RouteData routeData = new RouteData();
  99. routeData.DataTokens.Add("namespaces", new[] { typeof(ErrorController).Namespace });
  100. routeData.DataTokens.Add("area", "Error");
  101. routeData.Values.Add("controller", "Error");
  102. if (httpException == null)
  103. {
  104. routeData.Values.Add("action", "Exception");
  105. }
  106. else //It's an Http Exception, Let's handle it.
  107. {
  108. switch (httpException.GetHttpCode())
  109. {
  110. case 401:
  111. // Unauthorized.
  112. routeData.Values.Add("action", "Http401");
  113. break;
  114. case 403:
  115. // Forbidden.
  116. routeData.Values.Add("action", "Http403");
  117. break;
  118. case 404:
  119. // Page not found.
  120. routeData.Values.Add("action", "Http404");
  121. break;
  122. case 500:
  123. // Server error.
  124. routeData.Values.Add("action", "Http500");
  125. break;
  126. // Here you can handle Views to other error codes.
  127. // I choose a General error template
  128. default:
  129. routeData.Values.Add("action", "General");
  130. break;
  131. }
  132. }
  133. // Pass exception details to the target error View.
  134. routeData.Values.Add("exception", exception);
  135. // Clear the error on server.
  136. Server.ClearError();
  137. // Avoid IIS7 getting in the middle
  138. Response.TrySkipIisCustomErrors = true;
  139. // If it is an Ajax request, we should respond with Json data, otherwise redirect
  140. if (new HttpRequestWrapper(Request).IsAjaxRequest())
  141. {
  142. string jsonResult = string.Empty;
  143. if (httpException == null)
  144. {
  145. jsonResult = Json.Encode(new { error = new { type = "Exception", message = exception.GetFullMessage(true) } });
  146. }
  147. else
  148. {
  149. jsonResult = Json.Encode(new { error = new { type = "Http", statuscode = httpException.GetHttpCode(), message = exception.GetFullMessage(true) } });
  150. }
  151. Response.Write(jsonResult);
  152. }
  153. else
  154. {
  155. // Call target Controller and pass the routeData.
  156. IController errorController = new ErrorController();
  157. errorController.Execute(new RequestContext(
  158. new HttpContextWrapper(Context), routeData));
  159. }
  160. }
  161. }
  162. }