Skip to content

Commit

Permalink
webapi
Browse files Browse the repository at this point in the history
up to heroku
  • Loading branch information
caicangcua committed Feb 14, 2018
1 parent c3adf4e commit fb01217
Show file tree
Hide file tree
Showing 292 changed files with 296,616 additions and 0 deletions.
258 changes: 258 additions & 0 deletions App_Data/SampleData.xml

Large diffs are not rendered by default.

178 changes: 178 additions & 0 deletions App_Start/WebApiConfig.vb
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Linq
Imports System.Net.Http
Imports System.Net.Http.Extensions.Compression.Core.Compressors
Imports System.Net.Http.Formatting
Imports System.Net.Http.Headers
Imports System.Threading
Imports System.Threading.Tasks
Imports System.Web.Http
Imports System.Web.OData
Imports System.Web.OData.Builder
Imports System.Web.OData.Extensions
Imports System.Web.OData.Formatter
Imports Microsoft.AspNet.WebApi.Extensions.Compression.Server
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq

Public Module WebApiConfig
Public Sub Register(ByVal config As HttpConfiguration)
' Web API configuration and services
'config.MessageHandlers.Add(New CustomHeaderHandler())
' Web API routes
config.MapHttpAttributeRoutes()




'' OData configs
'Dim builder = New ODataConventionModelBuilder()






config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always
config.MapODataServiceRoute(routeName:="OData", routePrefix:="api", model:=GetModel)

config.Routes.MapHttpRoute(name:="DefaultApi", routeTemplate:="api/{controller}/{id}", defaults:=New With {
Key .id = RouteParameter.[Optional]
})

'config.Formatters.Clear()
'config.Formatters.AddRange(ODataMediaTypeFormatters.Create())
'config.Formatters.Add(New RawJsonMediaTypeFormatter())


' now the default setting for WebAPI OData is:
' client can’t apply $count, $orderby, $select, $top, $expand, $filter in the query, query
' like localhost\odata\Customers?$orderby=Name will failed as BadRequest,
' because all properties are not sort-able by default, this is a breaking change in 6.0.0
' So, we now need to enable OData Model Bound Attributes
'

config.Count().Filter().OrderBy().Expand().[Select]().MaxTop(Nothing)
''''config.Formatters.Clear()
''''config.Formatters.Add(New JsonMediaTypeFormatter())

''''' Ignore JSON reference loops
''''config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore

config.MessageHandlers.Insert(0, New ServerCompressionHandler(New GZipCompressor(), New DeflateCompressor()))


End Sub


Public Function GetModel() As Microsoft.OData.Edm.IEdmModel
'Dim builder As ODataModelBuilder = New ODataConventionModelBuilder()

''builder.EntitySet(Of Products)("Products")
''builder.EntitySet(Of Category)("Category")
'builder.EntitySet(Of Order)("Orders")



Dim builder = New ODataConventionModelBuilder() With {.[Namespace] = "Default"}
builder.EntitySet(Of Order)("Orders")
builder.EntitySet(Of OrderItem)("OrderItems")
builder.EntitySet(Of Product)("Product")
'builder.EntitySet(Of MyType)("Types")


Return builder.GetEdmModel()
End Function

Public Function GetControllerNameOf(Of TController As ODataController)() As String
Return GetType(TController).Name.Replace("Controller", "")
End Function


End Module

Public Class CustomHeaderHandler
Inherits DelegatingHandler

Protected Overrides Function SendAsync(request As HttpRequestMessage, cancellationToken As CancellationToken) As Task(Of HttpResponseMessage)
Dim queryStrings = request.RequestUri.ParseQueryString()
Dim format As String = queryStrings("$format")

Select Case format
Case Nothing
Exit Select
Case "xml"
request.Headers.Accept.Clear()
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/xml"))
Exit Select
Case "json"
request.Headers.Accept.Clear()
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"))
Exit Select
Case "atom"
request.Headers.Accept.Clear()
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/atom+xml"))
Exit Select
Case Else
request.Headers.Accept.Clear()
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse(format))
Exit Select
End Select

Return MyBase.SendAsync(request, cancellationToken)
End Function

End Class



Public Class RawJsonMediaTypeFormatter
Inherits MediaTypeFormatter
Private Shared ReadOnly _customMediaType As MediaTypeHeaderValue = MediaTypeHeaderValue.Parse("application/prs.adrianm+json")

Public Sub New()
MyBase.New()
Me.Intialize()
End Sub

Protected Sub New(formatter As MediaTypeFormatter)
MyBase.New(formatter)
Me.Intialize()
End Sub

Protected Sub Intialize()
Me.SupportedMediaTypes.Add(_customMediaType)
End Sub

Public Overrides Function GetPerRequestFormatterInstance(type As Type, request As HttpRequestMessage, mediaType As MediaTypeHeaderValue) As MediaTypeFormatter
If type = GetType(JToken) AndAlso mediaType.MediaType = _customMediaType.MediaType Then
Return Me
End If

Return MyBase.GetPerRequestFormatterInstance(type, request, mediaType)
End Function

Public Overrides Function CanReadType(type As Type) As Boolean
Return type = GetType(JToken)
End Function

Public Overrides Function CanWriteType(type As Type) As Boolean
Return False
End Function

Public Overrides Function ReadFromStreamAsync(type As Type, readStream As Stream, content As HttpContent, formatterLogger As IFormatterLogger) As Task(Of Object)
Return Me.ReadFromStreamAsync(type, readStream, content, formatterLogger, Nothing)
End Function

Public Overrides Function ReadFromStreamAsync(type As Type, readStream As Stream, content As HttpContent, formatterLogger As IFormatterLogger, cancellationToken As CancellationToken) As Task(Of Object)
Dim result As Object

Using reader = New JsonTextReader(New StreamReader(readStream))
result = JToken.ReadFrom(reader)
End Using

Return Task.FromResult(result)
End Function
End Class
79 changes: 79 additions & 0 deletions ApplicationInsights.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
<?xml version="1.0" encoding="utf-8"?>
<ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings">
<TelemetryInitializers>
<Add Type="Microsoft.ApplicationInsights.DependencyCollector.HttpDependenciesParsingTelemetryInitializer, Microsoft.AI.DependencyCollector"/>
<Add Type="Microsoft.ApplicationInsights.WindowsServer.AzureRoleEnvironmentTelemetryInitializer, Microsoft.AI.WindowsServer"/>
<Add Type="Microsoft.ApplicationInsights.WindowsServer.AzureWebAppRoleEnvironmentTelemetryInitializer, Microsoft.AI.WindowsServer"/>
<Add Type="Microsoft.ApplicationInsights.WindowsServer.BuildInfoConfigComponentVersionTelemetryInitializer, Microsoft.AI.WindowsServer"/>
<Add Type="Microsoft.ApplicationInsights.Web.WebTestTelemetryInitializer, Microsoft.AI.Web"/>
<Add Type="Microsoft.ApplicationInsights.Web.SyntheticUserAgentTelemetryInitializer, Microsoft.AI.Web">
<!-- Extended list of bots:
search|spider|crawl|Bot|Monitor|BrowserMob|BingPreview|PagePeeker|WebThumb|URL2PNG|ZooShot|GomezA|Google SketchUp|Read Later|KTXN|KHTE|Keynote|Pingdom|AlwaysOn|zao|borg|oegp|silk|Xenu|zeal|NING|htdig|lycos|slurp|teoma|voila|yahoo|Sogou|CiBra|Nutch|Java|JNLP|Daumoa|Genieo|ichiro|larbin|pompos|Scrapy|snappy|speedy|vortex|favicon|indexer|Riddler|scooter|scraper|scrubby|WhatWeb|WinHTTP|voyager|archiver|Icarus6j|mogimogi|Netvibes|altavista|charlotte|findlinks|Retreiver|TLSProber|WordPress|wsr-agent|http client|Python-urllib|AppEngine-Google|semanticdiscovery|facebookexternalhit|web/snippet|Google-HTTP-Java-Client-->
<Filters>search|spider|crawl|Bot|Monitor|AlwaysOn</Filters>
</Add>
<Add Type="Microsoft.ApplicationInsights.Web.ClientIpHeaderTelemetryInitializer, Microsoft.AI.Web"/>
<Add Type="Microsoft.ApplicationInsights.Web.OperationNameTelemetryInitializer, Microsoft.AI.Web"/>
<Add Type="Microsoft.ApplicationInsights.Web.OperationCorrelationTelemetryInitializer, Microsoft.AI.Web"/>
<Add Type="Microsoft.ApplicationInsights.Web.UserTelemetryInitializer, Microsoft.AI.Web"/>
<Add Type="Microsoft.ApplicationInsights.Web.AuthenticatedUserIdTelemetryInitializer, Microsoft.AI.Web"/>
<Add Type="Microsoft.ApplicationInsights.Web.AccountIdTelemetryInitializer, Microsoft.AI.Web"/>
<Add Type="Microsoft.ApplicationInsights.Web.SessionTelemetryInitializer, Microsoft.AI.Web"/>
</TelemetryInitializers>
<TelemetryModules>
<Add Type="Microsoft.ApplicationInsights.DependencyCollector.DependencyTrackingTelemetryModule, Microsoft.AI.DependencyCollector"/>
<Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.PerformanceCollectorModule, Microsoft.AI.PerfCounterCollector">
<!--
Use the following syntax here to collect additional performance counters:
<Counters>
<Add PerformanceCounter="\Process(??APP_WIN32_PROC??)\Handle Count" ReportAs="Process handle count" />
...
</Counters>
PerformanceCounter must be either \CategoryName(InstanceName)\CounterName or \CategoryName\CounterName
NOTE: performance counters configuration will be lost upon NuGet upgrade.
The following placeholders are supported as InstanceName:
??APP_WIN32_PROC?? - instance name of the application process for Win32 counters.
??APP_W3SVC_PROC?? - instance name of the application IIS worker process for IIS/ASP.NET counters.
??APP_CLR_PROC?? - instance name of the application CLR process for .NET counters.
-->
</Add>
<Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse.QuickPulseTelemetryModule, Microsoft.AI.PerfCounterCollector"/>
<Add Type="Microsoft.ApplicationInsights.WindowsServer.DeveloperModeWithDebuggerAttachedTelemetryModule, Microsoft.AI.WindowsServer"/>
<Add Type="Microsoft.ApplicationInsights.WindowsServer.UnhandledExceptionTelemetryModule, Microsoft.AI.WindowsServer"/>
<Add Type="Microsoft.ApplicationInsights.WindowsServer.UnobservedExceptionTelemetryModule, Microsoft.AI.WindowsServer"/>
<Add Type="Microsoft.ApplicationInsights.Web.RequestTrackingTelemetryModule, Microsoft.AI.Web">
<Handlers>
<!--
Add entries here to filter out additional handlers:
NOTE: handler configuration will be lost upon NuGet upgrade.
-->
<Add>System.Web.Handlers.TransferRequestHandler</Add>
<Add>Microsoft.VisualStudio.Web.PageInspector.Runtime.Tracing.RequestDataHttpHandler</Add>
<Add>System.Web.StaticFileHandler</Add>
<Add>System.Web.Handlers.AssemblyResourceLoader</Add>
<Add>System.Web.Optimization.BundleHandler</Add>
<Add>System.Web.Script.Services.ScriptHandlerFactory</Add>
<Add>System.Web.Handlers.TraceHandler</Add>
<Add>System.Web.Services.Discovery.DiscoveryRequestHandler</Add>
<Add>System.Web.HttpDebugHandler</Add>
</Handlers>
</Add>
<Add Type="Microsoft.ApplicationInsights.Web.ExceptionTrackingTelemetryModule, Microsoft.AI.Web"/>
</TelemetryModules>
<TelemetryProcessors>
<Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse.QuickPulseTelemetryProcessor, Microsoft.AI.PerfCounterCollector"/>
<Add Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.AdaptiveSamplingTelemetryProcessor, Microsoft.AI.ServerTelemetryChannel">
<MaxTelemetryItemsPerSecond>5</MaxTelemetryItemsPerSecond>
</Add>
</TelemetryProcessors>
<TelemetryChannel Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.ServerTelemetryChannel, Microsoft.AI.ServerTelemetryChannel"/>
<!--
Learn more about Application Insights configuration with ApplicationInsights.config here:
http://go.microsoft.com/fwlink/?LinkID=513840
Note: If not present, please add <InstrumentationKey>Your Key</InstrumentationKey> to the top of this file.
--></ApplicationInsights>
61 changes: 61 additions & 0 deletions Controllers/CategoriesController.vb
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Linq
Imports System.Net
Imports System.Net.Http
Imports System.Web.Http
Imports Newtonsoft.Json

Namespace MyRestService.Controllers
Public Class CategoriesController
Inherits ApiController

ReadOnly _db As New EntitiesModel()
'Public Function [Get]() As IEnumerable(Of Category)



' Dim options = Request.GetQueryNameValuePairs().ToDictionary(Function(x) x.Key, Function(x) JsonConvert.DeserializeObject(x.Value)) 'parsed options

' 'see the QueryHelper class for the implementation
' Dim query = _db.Category.AsEnumerable().FilterByOptions(options).SortByOptions(options).PageByOptions(options) 'paging - sorting - filtering
' Return query
'End Function


Public Function [Get]() As HttpResponseMessage
Dim response = Request.CreateResponse(HttpStatusCode.OK)

Dim _repo = New SK8Data()
Dim _orders = _repo.Orders()
Dim Json As String = JsonConvert.SerializeObject(_orders.ToArray())

'Dim line As String = Nothing
'Using reader As StreamReader = File.OpenText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data\dog.txt"))
' line = reader.ReadToEnd
'End Using

response.Content = New StringContent(Json, Encoding.UTF8, "application/json")
Return response

End Function
Public Function [Get](ByVal id As Integer) As Category
Return _db.Category.Find(id)
End Function
Public Function Post(ByVal cat As Category) As Integer
_db.Category.Add(cat)
Return _db.SaveChanges()
End Function
Public Function Put(ByVal cat As Category) As Integer
Dim categ As Category = _db.Category.Find(cat.Id)
categ.Name = cat.Name
Return _db.SaveChanges()
End Function
Public Function Delete(ByVal id As Integer) As Integer
Dim cat As Category = _db.Category.Find(id)
_db.Category.Remove(cat)
Return _db.SaveChanges()
End Function
End Class
End Namespace
35 changes: 35 additions & 0 deletions Controllers/MyODataModelController.vb
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
Imports System.Net
Imports System.Web.Http
Imports System.Web.OData

Public Class MyODataModelController
Inherits ODataController
Private ReadOnly Property MyODataModelService() As IMyODataModelService

' Delete this constructor and user dependency injection instead
' For simplicity, i omitted any DI container, use the one you like :)
Public Sub New()
Me.New(New MyODataModelService(New MyDatabaseEntityRepository(), New MyODataModelMapper()))
End Sub

Public Sub New(myODataModelService__1 As IMyODataModelService)
If myODataModelService__1 Is Nothing Then
Throw New ArgumentNullException(NameOf(myODataModelService__1))
End If
MyODataModelService = myODataModelService__1
End Sub

<EnableQuery>
Public Function [Get]() As IHttpActionResult
Return Ok(MyODataModelService.All())
End Function

<EnableQuery>
Public Function [Get](<FromODataUri> key As Integer) As IHttpActionResult
Dim record = MyODataModelService.Find(key)
If record Is Nothing Then
Return NotFound()
End If
Return Ok(record)
End Function
End Class
Loading

0 comments on commit fb01217

Please sign in to comment.