PageRenderTime 46ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/WP7.1/BabelCam/C#/BabelCam.Web/Global.asax.cs

#
C# | 204 lines | 156 code | 30 blank | 18 comment | 23 complexity | 01db644cd0394323c2b8c3f290e42747 MD5 | raw file
  1. // ----------------------------------------------------------------------------------
  2. // Microsoft Developer & Platform Evangelism
  3. //
  4. // Copyright (c) Microsoft Corporation. All rights reserved.
  5. //
  6. // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
  7. // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES
  8. // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
  9. // ----------------------------------------------------------------------------------
  10. // The example companies, organizations, products, domain names,
  11. // e-mail addresses, logos, people, places, and events depicted
  12. // herein are fictitious. No association with any real company,
  13. // organization, product, domain name, email address, logo, person,
  14. // places, or events is intended or should be inferred.
  15. // ----------------------------------------------------------------------------------
  16. namespace Microsoft.Samples.BabelCam.Web
  17. {
  18. using System;
  19. using System.Globalization;
  20. using System.Linq;
  21. using System.Web;
  22. using System.Web.Mvc;
  23. using System.Web.Routing;
  24. using System.Web.Security;
  25. using Microsoft.Samples.BabelCam.Infrastructure.Helpers;
  26. using Microsoft.Samples.BabelCam.Web.Controllers;
  27. using Microsoft.Samples.BabelCam.Web.Helpers;
  28. using Microsoft.Samples.BabelCam.Web.Services;
  29. using Microsoft.WindowsAzure;
  30. using Microsoft.WindowsAzure.ServiceRuntime;
  31. public class MvcApplication : System.Web.HttpApplication
  32. {
  33. private const int DefaultHttpsPort = 443;
  34. private const int DefaultHttpPort = 10080;
  35. private const string PortErrorMessage = @"The Web role was started in a wrong port.
  36. For this sample application to work correctly, please make sure that it is running in port {0}.
  37. Please review the Troubleshooting section of the sample documentation for instructions on how to do this.";
  38. private static bool securityInitialized = false;
  39. public static void RegisterGlobalFilters(GlobalFilterCollection filters)
  40. {
  41. filters.Add(new HandleErrorAttribute());
  42. }
  43. public static void RegisterRoutes(RouteCollection routes)
  44. {
  45. routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
  46. routes.MapRoute(
  47. "Default",
  48. "{controller}/{action}/{id}",
  49. new { controller = "Home", action = "Index", id = (string)null },
  50. new { controller = new ListConstraint(ListConstraintType.Exclude, "RegistrationService", "SharedAccessSignatureService", "PushNotificationService") });
  51. }
  52. protected void Application_Start()
  53. {
  54. // This code sets up a handler to update CloudStorageAccount instances when their corresponding
  55. // configuration settings change in the service configuration file.
  56. CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
  57. {
  58. // Provide the configSetter with the initial value.
  59. configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
  60. });
  61. AreaRegistration.RegisterAllAreas();
  62. RegisterGlobalFilters(GlobalFilters.Filters);
  63. RegisterRoutes(RouteTable.Routes);
  64. RouteTable.Routes.AddWcfServiceRoute<RegistrationService>("RegistrationService");
  65. RouteTable.Routes.AddWcfServiceRoute<SharedAccessSignatureService>("SharedAccessSignatureService");
  66. RouteTable.Routes.AddWcfServiceRoute<SamplePushUserRegistrationService>("PushNotificationService");
  67. var account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
  68. CloudStorageInitializer.InitializeCloudStorage(account);
  69. }
  70. protected void Session_Start(object sender, EventArgs e)
  71. {
  72. if (!securityInitialized)
  73. {
  74. InitializeSecurity();
  75. securityInitialized = true;
  76. }
  77. }
  78. protected void Application_BeginRequest(object sender, EventArgs e)
  79. {
  80. if (this.ShouldRedirectToHttps())
  81. {
  82. this.RedirectScheme(this.Context.Request.Url, "https");
  83. }
  84. else if (this.ShouldRedirectToHttp())
  85. {
  86. this.RedirectScheme(this.Context.Request.Url, "http");
  87. }
  88. if (!this.IsPortNumberOK() && !IsAllowedContent(this.Context.Request.Path))
  89. {
  90. this.CreateWrongPortException();
  91. }
  92. }
  93. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "This method initializes the Web Application.")]
  94. private static void InitializeSecurity()
  95. {
  96. var adminUser = Membership.FindUsersByName("admin").Cast<MembershipUser>().FirstOrDefault();
  97. if (adminUser == null)
  98. {
  99. adminUser = Membership.CreateUser("admin", "Passw0rd!", "admin@wp7cloudapp.com");
  100. }
  101. var adminUserId = adminUser.ProviderUserKey.ToString();
  102. IUserPrivilegesRepository userPrivilegesRepository = new UserTablesServiceContext();
  103. userPrivilegesRepository.AddPrivilegeToUser(adminUserId, PrivilegeConstants.AdminPrivilege);
  104. userPrivilegesRepository.AddPublicPrivilege(string.Format(CultureInfo.InvariantCulture, "{0}{1}", ConfigReader.GetConfigValue("RequestQueueName"), PrivilegeConstants.PublicQueuePrivilegeSuffix));
  105. }
  106. private static bool IsAllowedContent(string path)
  107. {
  108. return path.EndsWith("/Error", StringComparison.OrdinalIgnoreCase)
  109. || path.StartsWith("/Content", StringComparison.OrdinalIgnoreCase)
  110. || path.StartsWith("/Scripts", StringComparison.OrdinalIgnoreCase);
  111. }
  112. private void RedirectScheme(Uri originalUri, string intendedScheme)
  113. {
  114. int portNumber = 0;
  115. if (intendedScheme.Equals("https", StringComparison.OrdinalIgnoreCase))
  116. {
  117. portNumber = DefaultHttpsPort;
  118. }
  119. else if (intendedScheme.Equals("http", StringComparison.OrdinalIgnoreCase))
  120. {
  121. portNumber = DefaultHttpPort;
  122. }
  123. var redirectUrl = string.Format(
  124. CultureInfo.InvariantCulture,
  125. "{0}://{1}:{2}{3}",
  126. intendedScheme,
  127. originalUri.Host,
  128. portNumber,
  129. originalUri.PathAndQuery);
  130. this.Response.Redirect(redirectUrl, true);
  131. }
  132. private bool ShouldRedirectToHttp()
  133. {
  134. return this.Request.IsSecureConnection && this.Context.Request.Url.ToString().EndsWith(".cer", StringComparison.OrdinalIgnoreCase);
  135. }
  136. private bool ShouldRedirectToHttps()
  137. {
  138. return !this.Request.IsSecureConnection && !this.Context.Request.Url.ToString().EndsWith(".cer", StringComparison.OrdinalIgnoreCase);
  139. }
  140. private void CreateWrongPortException()
  141. {
  142. var exception = new RoleInWrongPortException(string.Format(CultureInfo.InvariantCulture, PortErrorMessage, DefaultHttpsPort));
  143. var routeData = new RouteData();
  144. routeData.Values.Add("Controller", "Error");
  145. routeData.Values.Add("Action", "Index");
  146. routeData.Values.Add("Error", exception);
  147. using (var errorController = new ErrorController())
  148. {
  149. ((IController)errorController).Execute(new RequestContext(new HttpContextWrapper(this.Context), routeData));
  150. }
  151. this.Context.Response.End();
  152. }
  153. private bool IsPortNumberOK()
  154. {
  155. var scheme = this.Context.Request.Url.Scheme;
  156. var portNumber = 0;
  157. if (scheme.Equals("https"))
  158. {
  159. portNumber = DefaultHttpsPort;
  160. }
  161. else if (scheme.Equals("http"))
  162. {
  163. portNumber = DefaultHttpPort;
  164. }
  165. var hostAddress = this.Context.Request.Headers["Host"] ?? string.Empty;
  166. var portPosition = hostAddress.IndexOf(":", StringComparison.OrdinalIgnoreCase);
  167. if (portPosition > 0)
  168. {
  169. int.TryParse(hostAddress.Substring(portPosition + 1), out portNumber);
  170. }
  171. return (portNumber == DefaultHttpsPort) || ((portNumber == DefaultHttpPort) && Context.Request.Url.ToString().EndsWith(".cer", StringComparison.OrdinalIgnoreCase));
  172. }
  173. }
  174. }