PageRenderTime 49ms CodeModel.GetById 7ms RepoModel.GetById 0ms app.codeStats 0ms

/WP7.1/Templates/VB/WPCloud.Mem/WindowsPhoneCloud.Web/Infrastructure/Extensions.vb

#
Visual Basic | 146 lines | 108 code | 21 blank | 17 comment | 0 complexity | e239a498b9291dd6bd6bd5b7598ac527 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. Imports System.Globalization
  17. Imports System.IO
  18. Imports System.Net
  19. Imports System.ServiceModel.Activation
  20. Imports Microsoft.WindowsAzure
  21. Imports Microsoft.WindowsAzure.StorageClient
  22. Imports WindowsPhone.Recipes.Push.Messages
  23. Namespace Infrastructure
  24. Public Module Extensions
  25. Private Const ErrorResponse As String = "<?xml version=""1.0"" encoding=""utf-8"" standalone=""yes"" ?><error {0}><code>{1}</code><message xml:lang=""en-US"">{2}</message></error>"
  26. Private Const DataServiceNamespace As String = "xmlns=""http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"""
  27. <System.Runtime.CompilerServices.Extension()> _
  28. Public Function ToModel(ByVal blobItem As IListBlobItem, ByVal containerName As String, ByVal accountName As String) As Models.CloudBlob
  29. Dim blob = TryCast(blobItem, CloudBlob)
  30. Dim sas = blob.GetSharedAccessSignature(New SharedAccessPolicy(), "readonly")
  31. Dim uriBuilder = New UriBuilder(blob.Uri) With {.Query = sas.TrimStart("?"c)}
  32. Dim blobUri = uriBuilder.Uri
  33. Dim blobName = blobUri.LocalPath
  34. ' When using the Storage Emulator the first segment is the dev account, not the container.
  35. Dim devaccount = CloudStorageAccount.DevelopmentStorageAccount.Credentials.AccountName
  36. If accountName.Equals(devaccount, StringComparison.OrdinalIgnoreCase) AndAlso blobName.StartsWith(String.Format(CultureInfo.InvariantCulture, "/{0}", devaccount), StringComparison.OrdinalIgnoreCase) Then
  37. blobName = blobName.Remove(0, devaccount.Length + 1)
  38. End If
  39. Return New Models.CloudBlob With {.Name = blobName.Remove(0, containerName.Length + 1).TrimStart("/"c), .Uri = blobUri}
  40. ' Remove container name.
  41. End Function
  42. <CLSCompliant(False)>
  43. <System.Runtime.CompilerServices.Extension()> _
  44. Public Function SendAndHandleErrors(ByVal message As PushNotificationMessage, ByVal uri As Uri) As MessageSendResultLight
  45. Dim result As MessageSendResultLight
  46. Try
  47. Dim sendResult = message.Send(uri)
  48. result = If(sendResult.NotificationStatus = NotificationStatus.Received, New MessageSendResultLight With {.Status = MessageSendResultLight.Success}, New MessageSendResultLight With {.Status = MessageSendResultLight.Error, .Description = "The notification was not received by the device."})
  49. Catch exception As Exception
  50. result = New MessageSendResultLight With {.Status = MessageSendResultLight.Error, .Description = exception.Message}
  51. End Try
  52. Return result
  53. End Function
  54. <System.Runtime.CompilerServices.Extension> _
  55. Public Function MenuItem(ByVal helper As HtmlHelper, ByVal linkText As String, ByVal actionName As String, ByVal controllerName As String) As MvcHtmlString
  56. Dim li = New TagBuilder("li")
  57. Dim routeData = helper.ViewContext.RouteData
  58. Dim currentAction = routeData.GetRequiredString("action")
  59. Dim currentController = routeData.GetRequiredString("controller")
  60. If String.Equals(currentAction, actionName, StringComparison.OrdinalIgnoreCase) AndAlso String.Equals(currentController, controllerName, StringComparison.OrdinalIgnoreCase) Then
  61. li.AddCssClass("selected")
  62. End If
  63. li.InnerHtml = helper.ActionLink(linkText, actionName, controllerName).ToHtmlString()
  64. Return MvcHtmlString.Create(li.ToString())
  65. End Function
  66. <System.Runtime.CompilerServices.Extension()> _
  67. Public Sub EndWithDataServiceError(ByVal response As HttpResponse, ByVal code As Integer, ByVal [error] As String, ByVal detail As String)
  68. response.Clear()
  69. response.ContentType = HttpConstants.MimeApplicationAtomXml
  70. response.StatusCode = code
  71. response.StatusDescription = [error]
  72. response.Write(String.Format(CultureInfo.InvariantCulture, ErrorResponse, DataServiceNamespace, [error], detail))
  73. response.Flush()
  74. response.End()
  75. response.Clear()
  76. End Sub
  77. <System.Runtime.CompilerServices.Extension()> _
  78. Public Sub CopyRequestHeadersTo(ByVal sourceRequest As HttpRequest, ByVal destinationRequest As WebRequest)
  79. destinationRequest.ContentType = sourceRequest.ContentType
  80. Dim finalHttpWebRequest = TryCast(destinationRequest, HttpWebRequest)
  81. If finalHttpWebRequest IsNot Nothing Then
  82. Dim connection = sourceRequest.Headers("Connection")
  83. finalHttpWebRequest.KeepAlive = If((Not String.IsNullOrEmpty(connection)) AndAlso connection.Equals("Close", StringComparison.OrdinalIgnoreCase), False, True)
  84. finalHttpWebRequest.Accept = HttpConstants.MimeApplicationAtomXml
  85. finalHttpWebRequest.Referer = sourceRequest.Headers("Referer")
  86. finalHttpWebRequest.UserAgent = sourceRequest.Headers("User-Agent")
  87. End If
  88. Dim excludeHeaders() As String = {"Connection", "Accept", "User-Agent", "Host", "Authorization", "AuthToken", "x-ms-date", "Content-Length", "Content-Type", "Referer"}
  89. For Each header In sourceRequest.Headers.AllKeys
  90. If Not excludeHeaders.Contains(header) Then
  91. destinationRequest.Headers.Add(header, sourceRequest.Headers(header))
  92. End If
  93. Next header
  94. End Sub
  95. <System.Runtime.CompilerServices.Extension()> _
  96. Public Function ExtractBodyString(ByVal webResponse As WebResponse) As String
  97. Using stream = webResponse.GetResponseStream()
  98. Return New StreamReader(stream).ReadToEnd()
  99. End Using
  100. End Function
  101. <System.Runtime.CompilerServices.Extension()> _
  102. Public Sub CopyResponseHeadersTo(ByVal sourceResponse As WebResponse, ByVal destinationResponse As HttpResponse, ByVal contentType As String)
  103. destinationResponse.ContentType = contentType
  104. Dim httpWebResponse = TryCast(sourceResponse, HttpWebResponse)
  105. If httpWebResponse IsNot Nothing Then
  106. destinationResponse.StatusCode = CInt(Fix(httpWebResponse.StatusCode))
  107. destinationResponse.StatusDescription = httpWebResponse.StatusDescription
  108. End If
  109. Dim excludeHeaders() As String = {"Content-Type", "Transfer-Encoding"}
  110. For Each header In sourceResponse.Headers.AllKeys
  111. If Not excludeHeaders.Contains(header) Then
  112. destinationResponse.Headers.Add(header, sourceResponse.Headers(header))
  113. End If
  114. Next header
  115. End Sub
  116. <System.Runtime.CompilerServices.Extension()> _
  117. Public Sub AddWcfServiceRoute(ByVal routes As RouteCollection, ByVal dataServiceType As Type, ByVal prefix As String)
  118. routes.Add(New ServiceRoute(prefix, New AutomaticFormatServiceHostFactory(), dataServiceType))
  119. End Sub
  120. <System.Runtime.CompilerServices.Extension()> _
  121. Public Sub AddWcfServiceRoute(Of TService)(ByVal routes As RouteCollection, ByVal prefix As String)
  122. AddWcfServiceRoute(routes, GetType(TService), prefix)
  123. End Sub
  124. End Module
  125. End Namespace