PageRenderTime 42ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/WP7.1/Templates/C#/WPCloud.Mem/WindowsPhoneCloud.Web/Global.asax.cs

#
C# | 282 lines | 222 code | 40 blank | 20 comment | 25 complexity | 43b4217ecb6e1d671ef5eabf9618c129 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.WindowsPhoneCloud.Web
  17. {
  18. using System;
  19. using System.Data.Entity;
  20. using System.Globalization;
  21. using System.Linq;
  22. using System.Web;
  23. using System.Web.Mvc;
  24. using System.Web.Routing;
  25. using System.Web.Security;
  26. using Microsoft.Samples.WindowsPhoneCloud.Web.Controllers;
  27. using Microsoft.Samples.WindowsPhoneCloud.Web.Infrastructure;
  28. using Microsoft.Samples.WindowsPhoneCloud.Web.Models;
  29. using Microsoft.Samples.WindowsPhoneCloud.Web.Services;
  30. using Microsoft.WindowsAzure;
  31. using Microsoft.WindowsAzure.ServiceRuntime;
  32. using Microsoft.WindowsAzure.StorageClient;
  33. public class MvcApplication : System.Web.HttpApplication
  34. {
  35. private const int DefaultHttpsPort = 443;
  36. private const int DefaultHttpPort = 10080;
  37. private const string PortErrorMessage = @"The Web role was started in a wrong port.
  38. For this sample application to work correctly, please make sure that it is running in port {0}.
  39. Please review the Troubleshooting section of the sample documentation for instructions on how to do this.";
  40. private static bool securityInitialized = false;
  41. public static void RegisterGlobalFilters(GlobalFilterCollection filters)
  42. {
  43. filters.Add(new HandleErrorAttribute());
  44. }
  45. public static void RegisterRoutes(RouteCollection routes)
  46. {
  47. routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
  48. routes.MapRoute(
  49. "Default",
  50. "{controller}/{action}/{id}",
  51. new { controller = "Home", action = "Index", id = (string)null },
  52. new { controller = new ListConstraint(ListConstraintType.Exclude, "AuthenticationService", "SharedAccessSignatureService", "PushNotificationService", "SqlAzureSampleODataService") });
  53. }
  54. protected void Application_Start()
  55. {
  56. // This code sets up a handler to update CloudStorageAccount instances when their corresponding.
  57. // configuration settings change in the service configuration file.
  58. CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
  59. {
  60. // Provide the configSetter with the initial value.
  61. configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
  62. });
  63. AreaRegistration.RegisterAllAreas();
  64. RegisterGlobalFilters(GlobalFilters.Filters);
  65. RegisterRoutes(RouteTable.Routes);
  66. RouteTable.Routes.AddWcfServiceRoute<AuthenticationService>("AuthenticationService");
  67. RouteTable.Routes.AddWcfServiceRoute<SharedAccessSignatureService>("SharedAccessSignatureService");
  68. RouteTable.Routes.AddWcfServiceRoute<SamplePushUserRegistrationService>("PushNotificationService");
  69. RouteTable.Routes.AddWcfServiceRoute<SqlAzureSampleODataService>("SqlAzureSampleODataService");
  70. var account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
  71. CreateSilverlightClientAccessPolicy(account.CreateCloudBlobClient());
  72. CreateCloudTables(account.CreateCloudTableClient());
  73. Database.SetInitializer<SqlSampleDataContext>(new SqlSampleDataInitializer());
  74. }
  75. protected void Session_Start(object sender, EventArgs e)
  76. {
  77. if (!securityInitialized)
  78. {
  79. InitializeSecurity();
  80. securityInitialized = true;
  81. }
  82. }
  83. protected void Application_BeginRequest(object sender, EventArgs e)
  84. {
  85. if (this.ShouldRedirectToHttps())
  86. {
  87. this.RedirectScheme(this.Context.Request.Url, "https");
  88. }
  89. else if (this.ShouldRedirectToHttp())
  90. {
  91. this.RedirectScheme(this.Context.Request.Url, "http");
  92. }
  93. if (!this.IsPortNumberOK() && !IsAllowedContent(this.Context.Request.Path))
  94. {
  95. this.CreateWrongPortException();
  96. }
  97. }
  98. private static void InitializeSecurity()
  99. {
  100. var adminUser = Membership.FindUsersByName("admin").Cast<MembershipUser>().FirstOrDefault();
  101. if (adminUser == null)
  102. {
  103. adminUser = Membership.CreateUser("admin", "Passw0rd!", "admin@wp7cloudapp.com");
  104. }
  105. var adminUserId = adminUser.ProviderUserKey.ToString();
  106. IUserPrivilegesRepository userPrivilegesRepository = new UserTablesServiceContext();
  107. userPrivilegesRepository.AddPrivilegeToUser(adminUserId, PrivilegeConstants.AdminPrivilege);
  108. userPrivilegesRepository.AddPrivilegeToUser(adminUserId, PrivilegeConstants.QueuesUsagePrivilege);
  109. userPrivilegesRepository.AddPrivilegeToUser(adminUserId, PrivilegeConstants.TablesUsagePrivilege);
  110. userPrivilegesRepository.AddPrivilegeToUser(adminUserId, PrivilegeConstants.BlobsUsagePrivilege);
  111. userPrivilegesRepository.AddPrivilegeToUser(adminUserId, PrivilegeConstants.SqlUsagePrivilege);
  112. userPrivilegesRepository.AddPrivilegeToUser(adminUserId, string.Format(CultureInfo.InvariantCulture, "{0}{1}", "SampleData", PrivilegeConstants.TablePrivilegeSuffix));
  113. }
  114. private static bool IsAllowedContent(string path)
  115. {
  116. return path.EndsWith("/Error", StringComparison.OrdinalIgnoreCase)
  117. || path.StartsWith("/Content", StringComparison.OrdinalIgnoreCase)
  118. || path.StartsWith("/Scripts", StringComparison.OrdinalIgnoreCase);
  119. }
  120. private static void CreateSilverlightClientAccessPolicy(CloudBlobClient cloudBlobClient)
  121. {
  122. var container = cloudBlobClient.GetContainerReference("$root");
  123. container.CreateIfNotExist();
  124. container.SetPermissions(
  125. new BlobContainerPermissions
  126. {
  127. PublicAccess = BlobContainerPublicAccessType.Blob
  128. });
  129. var blob = cloudBlobClient.GetBlobReference("clientaccesspolicy.xml");
  130. blob.Properties.ContentType = "text/xml";
  131. blob.UploadText(
  132. @"<?xml version=""1.0"" encoding=""utf-8""?>
  133. <access-policy>
  134. <cross-domain-access>
  135. <policy>
  136. <allow-from http-methods=""*"" http-request-headers=""*"">
  137. <domain uri=""*"" />
  138. <domain uri=""http://*"" />
  139. </allow-from>
  140. <grant-to>
  141. <resource path=""/"" include-subpaths=""true"" />
  142. </grant-to>
  143. </policy>
  144. </cross-domain-access>
  145. </access-policy>");
  146. }
  147. private static void CreateCloudTables(CloudTableClient cloudTableClient)
  148. {
  149. CreatePushNotificationTable(cloudTableClient);
  150. CreateUserPrivilegeTable(cloudTableClient);
  151. }
  152. private static void CreatePushNotificationTable(CloudTableClient cloudTableClient)
  153. {
  154. cloudTableClient.CreateTableIfNotExist(UserTablesServiceContext.PushUserTableName);
  155. // Execute conditionally for development storage only.
  156. if (cloudTableClient.BaseUri.IsLoopback)
  157. {
  158. var context = cloudTableClient.GetDataServiceContext();
  159. var entity = new PushUserEndpoint("applicationID", "deviceId") { UserId = "UserName", ChannelUri = "http://tempuri", TileCount = 0 };
  160. context.AddObject(UserTablesServiceContext.PushUserTableName, entity);
  161. context.SaveChangesWithRetries();
  162. context.DeleteObject(entity);
  163. context.SaveChangesWithRetries();
  164. }
  165. }
  166. private static void CreateUserPrivilegeTable(CloudTableClient cloudTableClient)
  167. {
  168. cloudTableClient.CreateTableIfNotExist(UserTablesServiceContext.UserPrivilegeTableName);
  169. // Execute conditionally for development storage only.
  170. if (cloudTableClient.BaseUri.IsLoopback)
  171. {
  172. var context = cloudTableClient.GetDataServiceContext();
  173. var entity = new UserPrivilege { UserId = "UserId", Privilege = "Privilege" };
  174. context.AddObject(UserTablesServiceContext.UserPrivilegeTableName, entity);
  175. context.SaveChangesWithRetries();
  176. context.DeleteObject(entity);
  177. context.SaveChangesWithRetries();
  178. }
  179. }
  180. private void RedirectScheme(Uri originalUri, string intendedScheme)
  181. {
  182. int portNumber = 0;
  183. if (intendedScheme.Equals("https", StringComparison.OrdinalIgnoreCase))
  184. {
  185. portNumber = DefaultHttpsPort;
  186. }
  187. else if (intendedScheme.Equals("http", StringComparison.OrdinalIgnoreCase))
  188. {
  189. portNumber = DefaultHttpPort;
  190. }
  191. var redirectUrl = string.Format(
  192. CultureInfo.InvariantCulture,
  193. "{0}://{1}:{2}{3}",
  194. intendedScheme,
  195. originalUri.Host,
  196. portNumber,
  197. originalUri.PathAndQuery);
  198. this.Response.Redirect(redirectUrl, true);
  199. }
  200. private bool ShouldRedirectToHttp()
  201. {
  202. return this.Request.IsSecureConnection && this.Context.Request.Url.ToString().EndsWith(".cer", StringComparison.OrdinalIgnoreCase);
  203. }
  204. private bool ShouldRedirectToHttps()
  205. {
  206. return !this.Request.IsSecureConnection && !this.Context.Request.Url.ToString().EndsWith(".cer", StringComparison.OrdinalIgnoreCase);
  207. }
  208. private void CreateWrongPortException()
  209. {
  210. var exception = new RoleInWrongPortException(string.Format(CultureInfo.InvariantCulture, PortErrorMessage, DefaultHttpsPort));
  211. var routeData = new RouteData();
  212. routeData.Values.Add("Controller", "Error");
  213. routeData.Values.Add("Action", "Index");
  214. routeData.Values.Add("Error", exception);
  215. using (var errorController = new ErrorController())
  216. {
  217. ((IController)errorController).Execute(new RequestContext(new HttpContextWrapper(this.Context), routeData));
  218. }
  219. this.Context.Response.End();
  220. }
  221. private bool IsPortNumberOK()
  222. {
  223. var scheme = this.Context.Request.Url.Scheme;
  224. var portNumber = 0;
  225. if (scheme.Equals("https"))
  226. {
  227. portNumber = DefaultHttpsPort;
  228. }
  229. else if (scheme.Equals("http"))
  230. {
  231. portNumber = DefaultHttpPort;
  232. }
  233. var hostAddress = this.Context.Request.Headers["Host"] ?? string.Empty;
  234. var portPosition = hostAddress.IndexOf(":", StringComparison.OrdinalIgnoreCase);
  235. if (portPosition > 0)
  236. {
  237. int.TryParse(hostAddress.Substring(portPosition + 1), out portNumber);
  238. }
  239. return (portNumber == DefaultHttpsPort) || ((portNumber == DefaultHttpPort) && Context.Request.Url.ToString().EndsWith(".cer", StringComparison.OrdinalIgnoreCase));
  240. }
  241. }
  242. }