locked
C# to vb code conversion issue RRS feed

  • Question

  • User-1668014665 posted

    MSVS 2015, .net 4.5.2 , Web API .net 5.2.3

    from this page

    https://github.com/rbercocano/WebApi-CsvMediaTypeFormatter/blob/master/WebApi.CsvMediaTypeFormatter/Formatters/EmployeeCsvFormatter.cs

    This code

    namespace WebApi.CsvMediaTypeFormatter.Formatters
    {
    
    public class EmployeeCsvFormatter : BufferedMediaTypeFormatter
    {
    public EmployeeCsvFormatter()
    {
    SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/csv"));
    SupportedEncodings.Add(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
    SupportedEncodings.Add(Encoding.GetEncoding("iso-8859-1"));
    }
    public EmployeeCsvFormatter(MediaTypeMapping mediaTypeMapping) : this()
    {
    MediaTypeMappings.Add(mediaTypeMapping);
    }
    
    public EmployeeCsvFormatter(IEnumerable<MediaTypeMapping> mediaTypeMappings) : this()
    {
    foreach (var mediaTypeMapping in mediaTypeMappings)
    MediaTypeMappings.Add(mediaTypeMapping);
    }
    // CUT SHORT FOR THIS POST } }

    I converted to vb 

    Namespace WebApi.CsvMediaTypeFormatter.Formatters
        Public Class EmployeeCsvFormatter
            Inherits BufferedMediaTypeFormatter
    
            Public Sub New()
                SupportedMediaTypes.Add(New MediaTypeHeaderValue("text/csv"))
                SupportedEncodings.Add(New UTF8Encoding(encoderShouldEmitUTF8Identifier:=False))
                SupportedEncodings.Add(Encoding.GetEncoding("iso-8859-1"))
            End Sub
    
            Public Sub New(ByVal mediaTypeMapping As MediaTypeMapping)
                Me.New()
                MediaTypeMappings.Add(mediaTypeMapping)
            End Sub
    
            Public Sub New(ByVal mediaTypeMappings As IEnumerable(Of MediaTypeMapping))
                Me.New()
    
                For Each mediaTypeMapping In mediaTypeMappings
                    MediaTypeMappings.Add(mediaTypeMapping)
                Next
            End Sub
        End Class
    End Namespace
    

    but in this line (in bold below) I get the error ADD IS NOT A MEMBER OF IEnumerable(Of MediaTypeMapping)

    Public Sub New(ByVal mediaTypeMappings As IEnumerable(Of MediaTypeMapping))
    Me.New()

    For Each mediaTypeMapping In mediaTypeMappings
    MediaTypeMappings.Add(mediaTypeMapping)
    Next
    End Sub

    Any ideas, what have I missed ????

    Friday, March 1, 2019 11:45 PM

Answers

  • User475983607 posted

    Can any one improve this??

    I'm not sure what you are trying to improve.  I assume file download?  I updated the GIT repo to include file download where the results can be filtered.

    https://github.com/mjgebhard/VbApiCsvFormatter

    I added a GET overload to filter the result set.

    http://localhost:57616/api/data?symbol=AAPL
    Option Strict On
    Option Explicit On
    
    Imports System.IO
    Imports System.Net
    Imports System.Net.Http
    Imports System.Net.Http.Headers
    Imports System.Web.Http
    Imports Newtonsoft.Json
    Imports System.Linq
    
    Namespace Controllers
        Public Class DataController
            Inherits ApiController
    
            Private data As List(Of SDOHLCV)
    
            Public Sub New()
                Dim json As String = "[
                {
                    ""nSymbol"": ""AAPL1"",
                    ""nDate"": ""20181130"",
                    ""nOpen"": 180.29,
                    ""nHigh"": 180.33,
                    ""nLow"": 177.03,
                    ""nClose"": 178.58,
                    ""nVolume"": 35981329
                },
                {
                    ""nSymbol"": ""AAPL1"",
                    ""nDate"": ""20181129"",
                    ""nOpen"": 182.66,
                    ""nHigh"": 182.8,
                    ""nLow"": 177.7,
                    ""nClose"": 179.55,
                    ""nVolume"": 41321868
                },
                {
                    ""nSymbol"": ""AAPL"",
                    ""nDate"": ""20181128"",
                    ""nOpen"": 176.73,
                    ""nHigh"": 181.29,
                    ""nLow"": 174.93,
                    ""nClose"": 180.94,
                    ""nVolume"": 45438931
                },
                {
                    ""nSymbol"": ""AAPL"",
                    ""nDate"": ""20181127"",
                    ""nOpen"": 171.51,
                    ""nHigh"": 174.77,
                    ""nLow"": 170.88,
                    ""nClose"": 174.24,
                    ""nVolume"": 40711655
                },
                {
                    ""nSymbol"": ""AAPL"",
                    ""nDate"": ""20181126"",
                    ""nOpen"": 174.24,
                    ""nHigh"": 174.95,
                    ""nLow"": 170.26,
                    ""nClose"": 174.62,
                    ""nVolume"": 43467288
                }
            ]"
                data = JsonConvert.DeserializeObject(Of List(Of SDOHLCV))(json)
            End Sub
    
            Public Function [Get]() As IEnumerable(Of SDOHLCV)
                Return data
            End Function
    
            Public Function [Get](ByVal Symbol As String) As HttpResponseMessage
    
                'Mock fetch data
                Dim queryResult = From d In data
                                  Where d.nSymbol = Symbol
                                  Select d
    
                Dim sb = New StringBuilder()
                sb.AppendLine(String.Format("{0},{1},{2},{3},{4},{5},{6}", "Symbol", "Date", "Open", "High", "Low", "Close", "Volume"))
                For Each SDOHLCV In queryResult.ToList()
                    sb.AppendLine(String.Format("{0},{1},{2},{3},{4},{5},{6}", Escape(SDOHLCV.nSymbol), Escape(SDOHLCV.nDate), Escape(SDOHLCV.nOpen), Escape(SDOHLCV.nHigh), Escape(SDOHLCV.nLow), Escape(SDOHLCV.nClose), Escape(SDOHLCV.nVolume)))
                Next
    
                Dim ms As Stream = New MemoryStream(Encoding.ASCII.GetBytes(sb.ToString()))
    
                Dim HttpResponseMessage As HttpResponseMessage = Request.CreateResponse(HttpStatusCode.OK)
                HttpResponseMessage.Content = New StreamContent(ms)
                HttpResponseMessage.Content.Headers.ContentDisposition = New System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
                HttpResponseMessage.Content.Headers.ContentDisposition.FileName = "SDOHLCV.csv"
                HttpResponseMessage.Content.Headers.ContentType = New System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream")
                HttpResponseMessage.Content.Headers.ContentLength = ms.Length
                Return HttpResponseMessage
    
            End Function
    
            Shared _specialChars As Char() = New Char() {","c, Convert.ToChar(vbLf), Convert.ToChar(vbCr), """"c}
    
            Private Function Escape(ByVal o As Object) As String
                If o Is Nothing Then
                    Return ""
                End If
    
                Dim field As String = o.ToString()
    
                If field.IndexOfAny(_specialChars) <> -1 Then
                    Return String.Format("""{0}""", field.Replace("""", """"""))
                Else
                    Return field
                End If
            End Function
    
            Public Sub Post(
    <FromBody> ByVal value As String)
            End Sub
    
            Public Sub Put(ByVal id As Integer,
    <FromBody> ByVal value As String)
            End Sub
    
            Public Sub Delete(ByVal id As Integer)
            End Sub
        End Class
    End Namespace




    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, March 2, 2019 6:17 PM
  • User1120430333 posted

    When I PUBLISH and go line from either CHROME or FIRECFOX

    You could have discovered the issue if you had stopped using IIS Express for the ASP.NET project and linked the project to local IIS and started developing, testing and debugging the Web project through VS using local IIS.

    https://docs.microsoft.com/en-us/visualstudio/debugger/how-to-enable-debugging-for-aspnet-applications?view=vs-2017

    However, you would probably have needed a console program to do the testing where you could have set a breakpoint in the console program, used the Debugger's Attach To Process, find the WPW3.exe that is servicing the Application Pool that is hosting the WebAPI set breakpoints and test and debugged the code.

    https://stackify.com/w3wp-exe-iis-worker-process/

    I stopped using IIS Express long ago and just use local IIS, becuase IIS Express hides issues until it is exposed on IIS.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, March 3, 2019 2:37 AM

All replies

  • User1120430333 posted

    but in this line (in bold below) I get the error ADD IS NOT A MEMBER OF IEnumerable(Of MediaTypeMapping)

    An IEnumberable is an enumerator it is not a List so there is no Add() in an IEnumeeable. You would have to go to the List IEnumerale is enumerating over to do an ADD(). 

    Saturday, March 2, 2019 1:04 AM
  • User475983607 posted

    Tested example below.  Be sure to configure PostMan to send an Accept text/csv header.  This will trigger the CSV response.  Keep in mind the HTTP response body is formatted as CSV.  The response is NOT a file.  The client needs to read the HTTP message body and do something with the text.

    Key     Value
    ------  --------
    Accept  text/csv

    Model

    Public Class SDOHLCV
        Public Property nSymbol As String
        Public Property nDate As String
        Public Property nOpen As Single
        Public Property nHigh As Single
        Public Property nLow As Single
        Public Property nClose As Single
        Public Property nVolume As Integer
    End Class

    CSV Formatter

    Imports System.IO
    Imports System.Net.Http
    Imports System.Net.Http.Formatting
    
    Public Class SDOHLCVCsvFormatter
        Inherits BufferedMediaTypeFormatter
    
        Public Sub New()
            SupportedMediaTypes.Add(New System.Net.Http.Headers.MediaTypeHeaderValue("text/csv"))
            SupportedEncodings.Add(New UTF8Encoding(False))
            SupportedEncodings.Add(Encoding.GetEncoding("iso-8859-1"))
        End Sub
    
        Public Overrides Function CanReadType(type As Type) As Boolean
            Return False
        End Function
    
        Public Overrides Function CanWriteType(type As Type) As Boolean
            If type.GetType() Is GetType(SDOHLCV) Then
                Return True
            Else
                Dim enumerableType As Type = GetType(IEnumerable(Of SDOHLCV))
                Return enumerableType.IsAssignableFrom(type)
            End If
        End Function
    
        Public Overrides Sub WriteToStream(ByVal type As Type, ByVal value As Object, ByVal writeStream As Stream, ByVal content As HttpContent)
            Dim effectiveEncoding As Encoding = SelectCharacterEncoding(content.Headers)
    
            Using writer = New StreamWriter(writeStream)
                Dim SDOHLCVs = TryCast(value, IEnumerable(Of SDOHLCV))
    
                If SDOHLCVs IsNot Nothing Then
    
                    For Each SDOHLCV In SDOHLCVs
                        WriteItem(SDOHLCV, writer)
                    Next
                Else
                    Dim singleSDOHLCV = TryCast(value, SDOHLCV)
    
                    If singleSDOHLCV Is Nothing Then
                        Throw New InvalidOperationException("Cannot serialize type")
                    End If
    
                    WriteItem(singleSDOHLCV, writer)
                End If
            End Using
        End Sub
    
        Private Sub WriteItem(ByVal SDOHLCV As SDOHLCV, ByVal writer As StreamWriter)
            writer.WriteLine("{0},{1},{2},{3},{4},{5},{6}", Escape(SDOHLCV.nSymbol), Escape(SDOHLCV.nDate), Escape(SDOHLCV.nOpen), Escape(SDOHLCV.nHigh), Escape(SDOHLCV.nLow), Escape(SDOHLCV.nClose), Escape(SDOHLCV.nVolume))
        End Sub
    
    
        Shared _specialChars As Char() = New Char() {","c, vbLf, vbCr, """"c}
    
        Private Function Escape(ByVal o As Object) As String
            If o Is Nothing Then
                Return ""
            End If
    
            Dim field As String = o.ToString()
    
            If field.IndexOfAny(_specialChars) <> -1 Then
                Return String.Format("""{0}""", field.Replace("""", """"""))
            Else
                Return field
            End If
        End Function
    
    End Class
    

    WebApiConfig.vb

    Imports System
    Imports System.Collections.Generic
    Imports System.Linq
    Imports System.Web.Http
    
    Public Module WebApiConfig
        Public Sub Register(ByVal config As HttpConfiguration)
            ' Web API configuration and services
            config.Formatters.Add(New SDOHLCVCsvFormatter())
    
            ' Web API routes
            config.MapHttpAttributeRoutes()
    
            config.Routes.MapHttpRoute(
                name:="DefaultApi",
                routeTemplate:="api/{controller}/{id}",
                defaults:=New With {.id = RouteParameter.Optional}
            )
        End Sub
    End Module
    

    Test controller with fake data.

    Imports System.Net
    Imports System.Web.Http
    Imports Newtonsoft.Json
    
    Namespace Controllers
        Public Class DataController
            Inherits ApiController
    
            Private data As List(Of SDOHLCV)
    
            Public Sub New()
                Dim json As String = "[
                {
                    ""nSymbol"": ""AAPL"",
                    ""nDate"": ""20181130"",
                    ""nOpen"": 180.29,
                    ""nHigh"": 180.33,
                    ""nLow"": 177.03,
                    ""nClose"": 178.58,
                    ""nVolume"": 35981329
                },
                {
                    ""nSymbol"": ""AAPL"",
                    ""nDate"": ""20181129"",
                    ""nOpen"": 182.66,
                    ""nHigh"": 182.8,
                    ""nLow"": 177.7,
                    ""nClose"": 179.55,
                    ""nVolume"": 41321868
                },
                {
                    ""nSymbol"": ""AAPL"",
                    ""nDate"": ""20181128"",
                    ""nOpen"": 176.73,
                    ""nHigh"": 181.29,
                    ""nLow"": 174.93,
                    ""nClose"": 180.94,
                    ""nVolume"": 45438931
                },
                {
                    ""nSymbol"": ""AAPL"",
                    ""nDate"": ""20181127"",
                    ""nOpen"": 171.51,
                    ""nHigh"": 174.77,
                    ""nLow"": 170.88,
                    ""nClose"": 174.24,
                    ""nVolume"": 40711655
                },
                {
                    ""nSymbol"": ""AAPL"",
                    ""nDate"": ""20181126"",
                    ""nOpen"": 174.24,
                    ""nHigh"": 174.95,
                    ""nLow"": 170.26,
                    ""nClose"": 174.62,
                    ""nVolume"": 43467288
                }
            ]"
                data = JsonConvert.DeserializeObject(Of List(Of SDOHLCV))(json)
            End Sub
    
            Public Function [Get]() As IEnumerable(Of SDOHLCV)
                Return data
            End Function
    
            Public Function [Get](ByVal id As Integer) As String
                Return "value"
            End Function
    
            Public Sub Post(
    <FromBody> ByVal value As String)
            End Sub
    
            Public Sub Put(ByVal id As Integer,
    <FromBody> ByVal value As String)
            End Sub
    
            Public Sub Delete(ByVal id As Integer)
            End Sub
        End Class
    End Namespace

    Saturday, March 2, 2019 1:27 AM
  • User-1668014665 posted

    Thanks for the efforts 

    I just copied this from your code

    Public Class SDOHLCVCsvFormatter

    Into my class, hit Run with Chrome (Build)

    I get this error

    Compiler Error Message: BC30002: Type 'HttpContent' is not defined.
    
    Source Error:
    
    
    Line 34: 
    Line 35:         Public Overrides Sub WriteToStream(ByVal type As Type, ByVal value As Object,
    Line 36:          ByVal writeStream As Stream, ByVal content As HttpContent)
    Line 37: 
    Line 38:             Dim effectiveEncoding As Encoding = SelectCharacterEncoding(content.Headers)
    
    
    // LINE 36

    Any ideas

    FYI , i am using 

    Option Strict On
    Option Explicit On

    Saturday, March 2, 2019 2:45 AM
  • User475983607 posted

    The code posted above just works as is.  The project target .NET 4.6.1.

    I added...

    Option Strict On
    Option Explicit On

    ...to the top of the SDOHLCVCsvFormatter class and the compiler complained about the vbCr and vbLf constants.   This change fixed the cast issue.

     Shared _specialChars As Char() = New Char() {","c, Convert.ToChar(vbLf), Convert.ToChar(vbCr), """"c}

    Tested and verified source.  Make sure you have the same Imports.

    Option Strict On
    Option Explicit On
    
    Imports System.IO
    Imports System.Net.Http
    Imports System.Net.Http.Formatting
    
    Public Class SDOHLCVCsvFormatter
        Inherits BufferedMediaTypeFormatter
    
        Public Sub New()
            SupportedMediaTypes.Add(New System.Net.Http.Headers.MediaTypeHeaderValue("text/csv"))
            SupportedEncodings.Add(New UTF8Encoding(False))
            SupportedEncodings.Add(Encoding.GetEncoding("iso-8859-1"))
        End Sub
    
        Public Overrides Function CanReadType(type As Type) As Boolean
            Return False
        End Function
    
        Public Overrides Function CanWriteType(type As Type) As Boolean
            If type.GetType() Is GetType(SDOHLCV) Then
                Return True
            Else
                Dim enumerableType As Type = GetType(IEnumerable(Of SDOHLCV))
                Return enumerableType.IsAssignableFrom(type)
            End If
        End Function
    
        Public Overrides Sub WriteToStream(ByVal type As Type, ByVal value As Object, ByVal writeStream As Stream, ByVal content As HttpContent)
            Dim effectiveEncoding As Encoding = SelectCharacterEncoding(content.Headers)
    
            Using writer = New StreamWriter(writeStream)
                Dim SDOHLCVs = TryCast(value, IEnumerable(Of SDOHLCV))
    
                If SDOHLCVs IsNot Nothing Then
    
                    For Each SDOHLCV In SDOHLCVs
                        WriteItem(SDOHLCV, writer)
                    Next
                Else
                    Dim singleSDOHLCV = TryCast(value, SDOHLCV)
    
                    If singleSDOHLCV Is Nothing Then
                        Throw New InvalidOperationException("Cannot serialize type")
                    End If
    
                    WriteItem(singleSDOHLCV, writer)
                End If
            End Using
        End Sub
    
        Private Sub WriteItem(ByVal SDOHLCV As SDOHLCV, ByVal writer As StreamWriter)
            writer.WriteLine("{0},{1},{2},{3},{4},{5},{6}", Escape(SDOHLCV.nSymbol), Escape(SDOHLCV.nDate), Escape(SDOHLCV.nOpen), Escape(SDOHLCV.nHigh), Escape(SDOHLCV.nLow), Escape(SDOHLCV.nClose), Escape(SDOHLCV.nVolume))
        End Sub
    
    
        Shared _specialChars As Char() = New Char() {","c, Convert.ToChar(vbLf), Convert.ToChar(vbCr), """"c}
    
        Private Function Escape(ByVal o As Object) As String
            If o Is Nothing Then
                Return ""
            End If
    
            Dim field As String = o.ToString()
    
            If field.IndexOfAny(_specialChars) <> -1 Then
                Return String.Format("""{0}""", field.Replace("""", """"""))
            Else
                Return field
            End If
        End Function
    
    End Class
    

    Saturday, March 2, 2019 3:14 AM
  • User-1668014665 posted

    I have Net 4.6.1, MSVS 2017 Community

    References System.net.http.formatting 5.2.7 from WepApi.client 5.2.7)

    see more ref on this link : https://imgur.com/a/75fCQO3

    I still get this error

    Compiler Error Message: BC30002: Type 'HttpContent' is not defined.

    code 

    Option Strict On
    Option Explicit On
    
    
    Imports System.IO
    Imports System.Net.Http
    Imports System.Net.Http.Formatting
    Imports XXXX.RTT_DataMod
    
    ''https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/media-formatters
    
    
    Namespace CSVFormatters
        Public Class SDOHLCVCsvFormatter
            Inherits BufferedMediaTypeFormatter
    
            Public Sub New()
                SupportedMediaTypes.Add(New System.Net.Http.Headers.MediaTypeHeaderValue("text/csv"))
                SupportedEncodings.Add(New UTF8Encoding(False))
                SupportedEncodings.Add(Encoding.GetEncoding("iso-8859-1"))
            End Sub
    
            Public Overrides Function CanReadType(type As Type) As Boolean
                Return False
            End Function
    
            Public Overrides Function CanWriteType(type As Type) As Boolean
                If type.GetType() Is GetType(SDOHLCV) Then
                    Return True
                Else
                    Dim enumerableType As Type = GetType(IEnumerable(Of SDOHLCV))
                    Return enumerableType.IsAssignableFrom(type)
                End If
            End Function
    
            Public Overrides Sub WriteToStream(ByVal type As Type, ByVal value As Object, ByVal writeStream As Stream, ByVal content As HttpContent)
    
                Dim effectiveEncoding As Encoding = SelectCharacterEncoding(content.Headers)
    
                Using writer = New StreamWriter(writeStream)
                    Dim SDOHLCVs = TryCast(value, IEnumerable(Of SDOHLCV))
    
                    If SDOHLCVs IsNot Nothing Then
    
                        For Each SDOHLCV In SDOHLCVs
                            WriteItem(SDOHLCV, writer)
                        Next
                    Else
                        Dim singleSDOHLCV = TryCast(value, SDOHLCV)
    
                        If singleSDOHLCV Is Nothing Then
                            Throw New InvalidOperationException("Cannot serialize type")
                        End If
    
                        WriteItem(singleSDOHLCV, writer)
                    End If
                End Using
            End Sub
    
            Private Sub WriteItem(ByVal SDOHLCV As SDOHLCV, ByVal writer As StreamWriter)
                writer.WriteLine("{0},{1},{2},{3},{4},{5},{6}", Escape(SDOHLCV.nSymbol), Escape(SDOHLCV.nDate), Escape(SDOHLCV.nOpen), Escape(SDOHLCV.nHigh), Escape(SDOHLCV.nLow), Escape(SDOHLCV.nClose), Escape(SDOHLCV.nVolume))
            End Sub
    
    
            Shared _specialChars As Char() = New Char() {","c, Convert.ToChar(vbLf), Convert.ToChar(vbCr), """"c}
    
            Private Function Escape(ByVal o As Object) As String
                If o Is Nothing Then
                    Return ""
                End If
    
                Dim field As String = o.ToString()
    
                If field.IndexOfAny(_specialChars) <> -1 Then
                    Return String.Format("""{0}""", field.Replace("""", """"""))
                Else
                    Return field
                End If
            End Function
    
        End Class
    
    
    End Namespace
    
    

    more detail error info

    C:\Program Files (x86)\IIS Express>C:\Users\RTT\Documents\Visual Studio 2017\Projects\readthetickerData\readthetickerData\bin\roslyn\vbc.exe /t:library /utf8output /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Runtime\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Runtime.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_32\System.EnterpriseServices\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.EnterpriseServices.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.ComponentModel.DataAnnotations\v4.0_4.0.0.0__31bf3856ad364e35\System.ComponentModel.DataAnnotations.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Drawing\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Drawing.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Web\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Web.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_32\System.Web\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Web.dll" /R:"C:\Users\RTT\AppData\Local\Temp\Temporary ASP.NET Files\vs\9e374982\e4ee87b5\assembly\dl3\451f6f39\0081ff6d_ce44d401\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.Extensions\v4.0_4.0.0.0__31bf3856ad364e35\System.Web.Extensions.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System\v4.0_4.0.0.0__b77a5c561934e089\System.dll" /R:"C:\Users\RTT\AppData\Local\Temp\Temporary ASP.NET Files\vs\9e374982\e4ee87b5\assembly\dl3\076fc2d3\00381ab7_ad86d401\System.Web.Http.WebHost.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_32\System.Data\v4.0_4.0.0.0__b77a5c561934e089\System.Data.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.CSharp\v4.0_4.0.0.0__b03f5f7f11d50a3a\Microsoft.CSharp.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.ApplicationServices\v4.0_4.0.0.0__31bf3856ad364e35\System.Web.ApplicationServices.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Activation\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Activation.dll" /R:"C:\Users\RTT\AppData\Local\Temp\Temporary ASP.NET Files\vs\9e374982\e4ee87b5\assembly\dl3\06057556\39c1c5b6_aad0d401\readthetickerData.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.Services\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Web.Services.dll" /R:"C:\Users\RTT\AppData\Local\Temp\Temporary ASP.NET Files\vs\9e374982\e4ee87b5\assembly\dl3\83dd3982\00eaa763_ad86d401\System.Net.Http.Formatting.dll" /R:"C:\Users\RTT\AppData\Local\Temp\Temporary ASP.NET Files\vs\9e374982\e4ee87b5\assembly\dl3\4cbce436\0034709d_7c18cd01\Elmah.dll" /R:"C:\Users\RTT\AppData\Local\Temp\Temporary ASP.NET Files\vs\9e374982\e4ee87b5\assembly\dl3\5481d922\0006f671_ad86d401\System.Web.Http.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.VisualStudio.Web.PageInspector.Loader\v4.0_1.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.Web.PageInspector.Loader.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Activities\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Activities.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Data.DataSetExtensions\v4.0_4.0.0.0__b77a5c561934e089\System.Data.DataSetExtensions.dll" /R:"C:\Users\RTT\AppData\Local\Temp\Temporary ASP.NET Files\vs\9e374982\e4ee87b5\assembly\dl3\66e13704\00ef391b_0f86d401\Newtonsoft.Json.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Xml.Linq\v4.0_4.0.0.0__b77a5c561934e089\System.Xml.Linq.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Runtime.Serialization\v4.0_4.0.0.0__b77a5c561934e089\System.Runtime.Serialization.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.WorkflowServices\v4.0_4.0.0.0__31bf3856ad364e35\System.WorkflowServices.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Activities\v4.0_4.0.0.0__31bf3856ad364e35\System.Activities.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.IdentityModel\v4.0_4.0.0.0__b77a5c561934e089\System.IdentityModel.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Core\v4.0_4.0.0.0__b77a5c561934e089\System.Core.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel\v4.0_4.0.0.0__b77a5c561934e089\System.ServiceModel.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.DynamicData\v4.0_4.0.0.0__31bf3856ad364e35\System.Web.DynamicData.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Xml\v4.0_4.0.0.0__b77a5c561934e089\System.Xml.dll" /out:"C:\Users\RTT\AppData\Local\Temp\Temporary ASP.NET Files\vs\9e374982\e4ee87b5\App_Code.q10v2nim.dll" /D:DEBUG=1 /debug+ /nowarn:41008,40000,40008 /define:_MYTYPE=\"Web\" /imports:Microsoft.VisualBasic,System,System.Collections,System.Collections.Generic,System.Collections.Specialized,System.ComponentModel.DataAnnotations,System.Configuration,System.Linq,System.Text,System.Text.RegularExpressions,System.Web,System.Web.Caching,System.Web.DynamicData,System.Web.SessionState,System.Web.Security,System.Web.Profile,System.Web.UI,System.Web.UI.WebControls,System.Web.UI.WebControls.WebParts,System.Web.UI.HtmlControls,System.Xml.Linq  /optionInfer+ /langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+  "C:\Users\RTT\AppData\Local\Temp\Temporary ASP.NET Files\vs\9e374982\e4ee87b5\App_Code.q10v2nim.0.vb" "C:\Users\RTT\AppData\Local\Temp\Temporary ASP.NET Files\vs\9e374982\e4ee87b5\App_Code.q10v2nim.1.vb" "C:\Users\RTT\AppData\Local\Temp\Temporary ASP.NET Files\vs\9e374982\e4ee87b5\App_Code.q10v2nim.2.vb" "C:\Users\RTT\AppData\Local\Temp\Temporary ASP.NET Files\vs\9e374982\e4ee87b5\App_Code.q10v2nim.3.vb" "C:\Users\RTT\AppData\Local\Temp\Temporary ASP.NET Files\vs\9e374982\e4ee87b5\App_Code.q10v2nim.4.vb" "C:\Users\RTT\AppData\Local\Temp\Temporary ASP.NET Files\vs\9e374982\e4ee87b5\App_Code.q10v2nim.5.vb" "C:\Users\RTT\AppData\Local\Temp\Temporary ASP.NET Files\vs\9e374982\e4ee87b5\App_Code.q10v2nim.6.vb"
    
    
    Microsoft (R) Visual Basic Compiler version 2.9.0.63208 (958f2354)
    Copyright (C) Microsoft Corporation. All rights reserved.
    
    C:\Users\RTT\Documents\Visual Studio 2017\Projects\readthetickerData\readthetickerData\App_Code\CSVFormatter.vb(37) : error BC30002: Type 'HttpContent' is not defined.
    
                                               ByVal writeStream As Stream, ByVal content As HttpContent)
                                                                                             ~~~~~~~~~~~ 
    C:\Users\RTT\Documents\Visual Studio 2017\Projects\readthetickerData\readthetickerData\App_Code\CSVFormatter.vb(36) : error BC30284: sub 'WriteToStream' cannot be declared 'Overrides' because it does not override a sub in a base class.
    
            Public Overrides Sub WriteToStream(ByVal type As Type, ByVal value As Object,

    Saturday, March 2, 2019 3:36 AM
  • User475983607 posted

    My configuration.

    • Target: .NET 4.6.1 
    • Project Template: Web API
    • System.Net.Http.Formatting version: 5.2.4.0
    • Microsoft.asp.Net.WebAPi.Client 5.2.4.0.

    I upgraded all assemblies except the Core assemblies and the code continued to function as expected.

    • System.Net.Http.Formatting version: 5.2.7.0
    • Microsoft.asp.Net.WebAPi.Client 5.2.7.0.

    My best guess is you are adding something extra.  Simply create a new Web API project and copy the files above.  Do nothing extra.

    Saturday, March 2, 2019 4:13 AM
  • User-1668014665 posted

    I will rebuild, Thanks for the attention.. 

    Saturday, March 2, 2019 4:23 AM
  • User-1668014665 posted

    There are NO NameSpaces around your classes

    So where do you place all your code, which folders?

    I get the same HTTPContent as before error

    I have this setup NOW

    • Target: .NET 4.6.1 
    • Project Template: Web API
    • System.Net.Http.Formatting version: 5.2.4.0
    • Microsoft.asp.Net.WebAPi.Client 5.2.4.0.

    I have in these folders

    App_Code (NameSpace .RTTFormatters)
    FormattersCSV.vb

    Models
    DataModel.vb

    Controller
    DataController.vb

    App_start    (using import Imports readthetickerData.RTTFormatters)

    WebApiConfig.vb

    Any chance loading up a ZIP file

    Saturday, March 2, 2019 5:07 AM
  • User475983607 posted

    It is a web application project.

    https://github.com/mjgebhard/VbApiCsvFormatter

    Saturday, March 2, 2019 4:45 PM
  • User-1668014665 posted

    So I got working by removing NAMESPACE and put the FormattersCSV.vb code into the controllers folder.

    WHY DOES THAT HAVE TO BE SO ?

    I got postman to show me CSV, but input into Headers KEY:Accept, VALUE: text/csv

    QUESTION In the real world will the API URL

    http://localhost:49327/api/data

    return this to browser/output??  

    AAPL,20181130,180.29,180.33,177.03,178.58,35981329
    AAPL,20181129,182.66,182.8,177.7,179.55,41321868
    AAPL,20181128,176.73,181.29,174.93,180.94,45438931
    AAPL,20181127,171.51,174.77,170.88,174.24,40711655
    AAPL,20181126,174.24,174.95,170.26,174.62,43467288

    Shame there are no field headers....

    Saturday, March 2, 2019 4:45 PM
  • User475983607 posted

    So I got working by removing NAMESPACE and put the FormattersCSV.vb code into the controllers folder.

    WHY DOES THAT HAVE TO BE SO ?

    I'm not sure as I can't see your project.

    I got postman to show me CSV, but input into Headers KEY:Accept, VALUE: text/csv

    Right, that's called content negotiation.  The HTTP request header Accept: text/csv tells the Web API format the response using the CSV foramtter.

    QUESTION In the real world will the API URL

    http://localhost:49327/api/data

    return this to browser/output??  

    The browser does not know about the text/csv header.  Client code adds this header to the HTTP request and reads the response stream.

    I've already explained this a couple of time above but you probably did not understand until this point.  I imagine you want to return a CSV file?  If so, the HTTP response needs to return a file rather than a formatted HTTP message.

    Saturday, March 2, 2019 4:55 PM
  • User-1668014665 posted

    Yes I am used to asp net forms.

    Is there some docs as why all the code must go into controllers folder

    So I guess if I were to use MS SQL data via stored procedure , what are my options

    1) Put all the code under the GET

    or

    2) Put the code in a public class with in the Controllers folder and use class in GET 

    Please advise

    Saturday, March 2, 2019 4:55 PM
  • User475983607 posted

    Yes I am used to asp net forms.

    Is there some docs as why all the code must go into controllers folder

    There is no reason the class must go in the controller folder.  See the GIT repo above where I have the class in the Infrastructure folder.

    So I guess if I were to use MS SQL data via stored procedure , what are my options

    I don't understand the question.  Simply build a data access layer or class.

    1) Put all the code under the GET

    or

    2) Put the code in a public class with in the Controllers folder and use class in GET 

    An HTTP GET can be bookmarked and used as a link.  If you do not want users to bookmark then use a POST action filter.

    Can you explain the problem you are trying to solve?  Do you really want to return a CSV file?

    Saturday, March 2, 2019 5:09 PM
  • User-1668014665 posted

    I adjust the FormatterCSV file , this returns a CSV file attached

    This part, with a new import: Imports System.Net.Http.Headers

        Public Overrides Sub SetDefaultContentHeaders(ByVal type As Type, ByVal headers As System.Net.Http.Headers.HttpContentHeaders, ByVal mediaType As MediaTypeHeaderValue)
            MyBase.SetDefaultContentHeaders(type, headers, mediaType)
            headers.Add("Content-Disposition", "attachment; filename=SDOHLCV.csv")
            headers.ContentType = New MediaTypeHeaderValue("application/octet-stream")
    
        End Sub
    Imports System.IO
    Imports System.Net.Http
    Imports System.Net.Http.Formatting
    Imports System.Net.Http.Headers
    
    
    Public Class SDOHLCVCsvFormatter
        Inherits BufferedMediaTypeFormatter
    
        Public Sub New()
            SupportedMediaTypes.Add(New System.Net.Http.Headers.MediaTypeHeaderValue("text/csv"))
            SupportedEncodings.Add(New UTF8Encoding(False))
            SupportedEncodings.Add(Encoding.GetEncoding("iso-8859-1"))
        End Sub
    
        Public Overrides Sub SetDefaultContentHeaders(ByVal type As Type, ByVal headers As System.Net.Http.Headers.HttpContentHeaders, ByVal mediaType As MediaTypeHeaderValue)
            MyBase.SetDefaultContentHeaders(type, headers, mediaType)
            headers.Add("Content-Disposition", "attachment; filename=SDOHLCV.csv")
            headers.ContentType = New MediaTypeHeaderValue("application/octet-stream")
    
        End Sub
        Public Overrides Function CanReadType(type As Type) As Boolean
            Return False
        End Function
    
        Public Overrides Function CanWriteType(type As Type) As Boolean
            If type.GetType() Is GetType(SDOHLCV) Then
                Return True
            Else
                Dim enumerableType As Type = GetType(IEnumerable(Of SDOHLCV))
                Return enumerableType.IsAssignableFrom(type)
            End If
        End Function
    
        Public Overrides Sub WriteToStream(ByVal type As Type, ByVal value As Object, ByVal writeStream As Stream, ByVal content As HttpContent)
            Dim effectiveEncoding As Encoding = SelectCharacterEncoding(content.Headers)
    
            Using writer = New StreamWriter(writeStream)
                Dim SDOHLCVs = TryCast(value, IEnumerable(Of SDOHLCV))
    
                If SDOHLCVs IsNot Nothing Then
    
                    For Each SDOHLCV In SDOHLCVs
                        WriteItem(SDOHLCV, writer)
                    Next
                Else
                    Dim singleSDOHLCV = TryCast(value, SDOHLCV)
    
                    If singleSDOHLCV Is Nothing Then
                        Throw New InvalidOperationException("Cannot serialize type")
                    End If
    
                    WriteItem(singleSDOHLCV, writer)
                End If
            End Using
        End Sub
    
        Private Sub WriteItem(ByVal SDOHLCV As SDOHLCV, ByVal writer As StreamWriter)
            writer.WriteLine("{0},{1},{2},{3},{4},{5},{6}", Escape(SDOHLCV.nSymbol), Escape(SDOHLCV.nDate), Escape(SDOHLCV.nOpen), Escape(SDOHLCV.nHigh), Escape(SDOHLCV.nLow), Escape(SDOHLCV.nClose), Escape(SDOHLCV.nVolume))
        End Sub
    
    
        Shared _specialChars As Char() = New Char() {","c, Convert.ToChar(vbLf), Convert.ToChar(vbCr), """"c}
    
        Private Function Escape(ByVal o As Object) As String
            If o Is Nothing Then
                Return ""
            End If
    
            Dim field As String = o.ToString()
    
            If field.IndexOfAny(_specialChars) <> -1 Then
                Return String.Format("""{0}""", field.Replace("""", """"""))
            Else
                Return field
            End If
        End Function
    
    End Class

    But POSTMAN does not any headers like

    Symbol,Date,open,high,low,close,volume

    Saturday, March 2, 2019 5:16 PM
  • User-1668014665 posted

    Here is the code improved with TEXT headers

    Success OUT PUT 

    Symbol,Date,Open,High,Low,Close,Volume
    AAPL,20181130,180.29,180.33,177.03,178.58,35981329
    AAPL,20181129,182.66,182.8,177.7,179.55,41321868
    AAPL,20181128,176.73,181.29,174.93,180.94,45438931
    AAPL,20181127,171.51,174.77,170.88,174.24,40711655
    AAPL,20181126,174.24,174.95,170.26,174.62,43467288

    Imports System.IO
    Imports System.Net.Http
    Imports System.Net.Http.Formatting
    Imports System.Net.Http.Headers
    
    
    Public Class SDOHLCVCsvFormatter
        Inherits BufferedMediaTypeFormatter
    
        Public Sub New()
            SupportedMediaTypes.Add(New System.Net.Http.Headers.MediaTypeHeaderValue("text/txt"))
            SupportedEncodings.Add(New UTF8Encoding(False))
            SupportedEncodings.Add(Encoding.GetEncoding("iso-8859-1"))
        End Sub
    
        Public Overrides Sub SetDefaultContentHeaders(ByVal type As Type, ByVal headers As System.Net.Http.Headers.HttpContentHeaders, ByVal mediaType As MediaTypeHeaderValue)
            MyBase.SetDefaultContentHeaders(type, headers, mediaType)
            headers.Add("Content-Disposition", "attachment; filename=DataCSV.txt")
            headers.ContentType = New MediaTypeHeaderValue("application/octet-stream")
    
        End Sub
        Public Overrides Function CanReadType(type As Type) As Boolean
            Return False
        End Function
    
        Public Overrides Function CanWriteType(type As Type) As Boolean
            If type.GetType() Is GetType(SDOHLCV) Then
                Return True
            Else
                Dim enumerableType As Type = GetType(IEnumerable(Of SDOHLCV))
                Return enumerableType.IsAssignableFrom(type)
            End If
        End Function
    
        Public Overrides Sub WriteToStream(ByVal type As Type, ByVal value As Object, ByVal writeStream As Stream, ByVal content As HttpContent)
            Dim effectiveEncoding As Encoding = SelectCharacterEncoding(content.Headers)
    
            Using writer = New StreamWriter(writeStream)
    
                WriteItem1(writer)
    
                Dim SDOHLCVs = TryCast(value, IEnumerable(Of SDOHLCV))
                If SDOHLCVs IsNot Nothing Then
    
                    For Each SDOHLCV In SDOHLCVs
                        WriteItem2(SDOHLCV, writer)
                    Next
                Else
                    Dim singleSDOHLCV = TryCast(value, SDOHLCV)
    
                    If singleSDOHLCV Is Nothing Then
                        Throw New InvalidOperationException("Cannot serialize type")
                    End If
    
                    WriteItem2(singleSDOHLCV, writer)
                End If
            End Using
        End Sub
        Private Sub WriteItem1(ByVal writer As StreamWriter)
            writer.WriteLine("{0},{1},{2},{3},{4},{5},{6}", "Symbol", "Date", "Open", "High", "Low", "Close", "Volume")
        End Sub
        Private Sub WriteItem2(ByVal SDOHLCV As SDOHLCV, ByVal writer As StreamWriter)
            writer.WriteLine("{0},{1},{2},{3},{4},{5},{6}", Escape(SDOHLCV.nSymbol), Escape(SDOHLCV.nDate), Escape(SDOHLCV.nOpen), Escape(SDOHLCV.nHigh), Escape(SDOHLCV.nLow), Escape(SDOHLCV.nClose), Escape(SDOHLCV.nVolume))
        End Sub
    
    
        Shared _specialChars As Char() = New Char() {","c, Convert.ToChar(vbLf), Convert.ToChar(vbCr), """"c}
    
        Private Function Escape(ByVal o As Object) As String
            If o Is Nothing Then
                Return ""
            End If
    
            Dim field As String = o.ToString()
    
            If field.IndexOfAny(_specialChars) <> -1 Then
                Return String.Format("""{0}""", field.Replace("""", """"""))
            Else
                Return field
            End If
        End Function
    
    End Class

    Can any one improve this??

    Saturday, March 2, 2019 5:30 PM
  • User475983607 posted

    Can any one improve this??

    I'm not sure what you are trying to improve.  I assume file download?  I updated the GIT repo to include file download where the results can be filtered.

    https://github.com/mjgebhard/VbApiCsvFormatter

    I added a GET overload to filter the result set.

    http://localhost:57616/api/data?symbol=AAPL
    Option Strict On
    Option Explicit On
    
    Imports System.IO
    Imports System.Net
    Imports System.Net.Http
    Imports System.Net.Http.Headers
    Imports System.Web.Http
    Imports Newtonsoft.Json
    Imports System.Linq
    
    Namespace Controllers
        Public Class DataController
            Inherits ApiController
    
            Private data As List(Of SDOHLCV)
    
            Public Sub New()
                Dim json As String = "[
                {
                    ""nSymbol"": ""AAPL1"",
                    ""nDate"": ""20181130"",
                    ""nOpen"": 180.29,
                    ""nHigh"": 180.33,
                    ""nLow"": 177.03,
                    ""nClose"": 178.58,
                    ""nVolume"": 35981329
                },
                {
                    ""nSymbol"": ""AAPL1"",
                    ""nDate"": ""20181129"",
                    ""nOpen"": 182.66,
                    ""nHigh"": 182.8,
                    ""nLow"": 177.7,
                    ""nClose"": 179.55,
                    ""nVolume"": 41321868
                },
                {
                    ""nSymbol"": ""AAPL"",
                    ""nDate"": ""20181128"",
                    ""nOpen"": 176.73,
                    ""nHigh"": 181.29,
                    ""nLow"": 174.93,
                    ""nClose"": 180.94,
                    ""nVolume"": 45438931
                },
                {
                    ""nSymbol"": ""AAPL"",
                    ""nDate"": ""20181127"",
                    ""nOpen"": 171.51,
                    ""nHigh"": 174.77,
                    ""nLow"": 170.88,
                    ""nClose"": 174.24,
                    ""nVolume"": 40711655
                },
                {
                    ""nSymbol"": ""AAPL"",
                    ""nDate"": ""20181126"",
                    ""nOpen"": 174.24,
                    ""nHigh"": 174.95,
                    ""nLow"": 170.26,
                    ""nClose"": 174.62,
                    ""nVolume"": 43467288
                }
            ]"
                data = JsonConvert.DeserializeObject(Of List(Of SDOHLCV))(json)
            End Sub
    
            Public Function [Get]() As IEnumerable(Of SDOHLCV)
                Return data
            End Function
    
            Public Function [Get](ByVal Symbol As String) As HttpResponseMessage
    
                'Mock fetch data
                Dim queryResult = From d In data
                                  Where d.nSymbol = Symbol
                                  Select d
    
                Dim sb = New StringBuilder()
                sb.AppendLine(String.Format("{0},{1},{2},{3},{4},{5},{6}", "Symbol", "Date", "Open", "High", "Low", "Close", "Volume"))
                For Each SDOHLCV In queryResult.ToList()
                    sb.AppendLine(String.Format("{0},{1},{2},{3},{4},{5},{6}", Escape(SDOHLCV.nSymbol), Escape(SDOHLCV.nDate), Escape(SDOHLCV.nOpen), Escape(SDOHLCV.nHigh), Escape(SDOHLCV.nLow), Escape(SDOHLCV.nClose), Escape(SDOHLCV.nVolume)))
                Next
    
                Dim ms As Stream = New MemoryStream(Encoding.ASCII.GetBytes(sb.ToString()))
    
                Dim HttpResponseMessage As HttpResponseMessage = Request.CreateResponse(HttpStatusCode.OK)
                HttpResponseMessage.Content = New StreamContent(ms)
                HttpResponseMessage.Content.Headers.ContentDisposition = New System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
                HttpResponseMessage.Content.Headers.ContentDisposition.FileName = "SDOHLCV.csv"
                HttpResponseMessage.Content.Headers.ContentType = New System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream")
                HttpResponseMessage.Content.Headers.ContentLength = ms.Length
                Return HttpResponseMessage
    
            End Function
    
            Shared _specialChars As Char() = New Char() {","c, Convert.ToChar(vbLf), Convert.ToChar(vbCr), """"c}
    
            Private Function Escape(ByVal o As Object) As String
                If o Is Nothing Then
                    Return ""
                End If
    
                Dim field As String = o.ToString()
    
                If field.IndexOfAny(_specialChars) <> -1 Then
                    Return String.Format("""{0}""", field.Replace("""", """"""))
                Else
                    Return field
                End If
            End Function
    
            Public Sub Post(
    <FromBody> ByVal value As String)
            End Sub
    
            Public Sub Put(ByVal id As Integer,
    <FromBody> ByVal value As String)
            End Sub
    
            Public Sub Delete(ByVal id As Integer)
            End Sub
        End Class
    End Namespace




    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, March 2, 2019 6:17 PM
  • User-1668014665 posted

    I am very happy, all is working, I think, This is my FormatterCSV.vb which returns a file (text/txt) containg comma separate data with a header

    Symbol,Date,Open,High,Low,Close,Volume
    AAPL,20181130,180.29,180.33,177.03,178.58,35981329
    AAPL,20181129,182.66,182.8,177.7,179.55,41321868
    AAPL,20181128,176.73,181.29,174.93,180.94,45438931
    AAPL,20181127,171.51,174.77,170.88,174.24,40711655
    AAPL,20181126,174.24,174.95,170.26,174.62,43467288

    Imports System.IO
    Imports System.Net.Http
    Imports System.Net.Http.Formatting
    Imports System.Net.Http.Headers
    
    
    Public Class SDOHLCVCsvFormatter
        Inherits BufferedMediaTypeFormatter
    
        Public Sub New()
            SupportedMediaTypes.Add(New System.Net.Http.Headers.MediaTypeHeaderValue("text/txt"))
            SupportedEncodings.Add(New UTF8Encoding(False))
            SupportedEncodings.Add(Encoding.GetEncoding("iso-8859-1"))
        End Sub
    
        Public Overrides Sub SetDefaultContentHeaders(ByVal type As Type, ByVal headers As System.Net.Http.Headers.HttpContentHeaders, ByVal mediaType As MediaTypeHeaderValue)
            MyBase.SetDefaultContentHeaders(type, headers, mediaType)
            headers.Add("Content-Disposition", "attachment; filename=DataCSV.txt")
            headers.ContentType = New MediaTypeHeaderValue("application/octet-stream")
    
        End Sub
        Public Overrides Function CanReadType(type As Type) As Boolean
            Return False
        End Function
    
        Public Overrides Function CanWriteType(type As Type) As Boolean
            If type.GetType() Is GetType(SDOHLCV) Then
                Return True
            Else
                Dim enumerableType As Type = GetType(IEnumerable(Of SDOHLCV))
                Return enumerableType.IsAssignableFrom(type)
            End If
        End Function
    
        Public Overrides Sub WriteToStream(ByVal type As Type, ByVal value As Object, ByVal writeStream As Stream, ByVal content As HttpContent)
            Dim effectiveEncoding As Encoding = SelectCharacterEncoding(content.Headers)
    
            Using writer = New StreamWriter(writeStream)
    
                Dim SDOHLCVs = TryCast(value, IEnumerable(Of SDOHLCV))
                If SDOHLCVs IsNot Nothing Then
    
                    WriteItem1(writer)
    
                    For Each SDOHLCV In SDOHLCVs
                        WriteItem2(SDOHLCV, writer)
                    Next
                Else
                    Dim singleSDOHLCV = TryCast(value, SDOHLCV)
    
                    If singleSDOHLCV Is Nothing Then
                        Throw New InvalidOperationException("Cannot serialize type")
                    End If
    
                    WriteItem2(singleSDOHLCV, writer)
                End If
            End Using
        End Sub
        Private Sub WriteItem1(ByVal writer As StreamWriter)
            writer.WriteLine("{0},{1},{2},{3},{4},{5},{6}", "Symbol", "Date", "Open", "High", "Low", "Close", "Volume")
        End Sub
        Private Sub WriteItem2(ByVal SDOHLCV As SDOHLCV, ByVal writer As StreamWriter)
            writer.WriteLine("{0},{1},{2},{3},{4},{5},{6}", Escape(SDOHLCV.nSymbol), Escape(SDOHLCV.nDate), Escape(SDOHLCV.nOpen), Escape(SDOHLCV.nHigh), Escape(SDOHLCV.nLow), Escape(SDOHLCV.nClose), Escape(SDOHLCV.nVolume))
        End Sub
    
    
        Shared _specialChars As Char() = New Char() {","c, Convert.ToChar(vbLf), Convert.ToChar(vbCr), """"c}
    
        Private Function Escape(ByVal o As Object) As String
            If o Is Nothing Then
                Return ""
            End If
    
            Dim field As String = o.ToString()
    
            If field.IndexOfAny(_specialChars) <> -1 Then
                Return String.Format("""{0}""", field.Replace("""", """"""))
            Else
                Return field
            End If
        End Function
    
    End Class

    This part created the file

        Public Overrides Sub SetDefaultContentHeaders(ByVal type As Type, ByVal headers As System.Net.Http.Headers.HttpContentHeaders, ByVal mediaType As MediaTypeHeaderValue)
            MyBase.SetDefaultContentHeaders(type, headers, mediaType)
            headers.Add("Content-Disposition", "attachment; filename=DataCSV.txt")
            headers.ContentType = New MediaTypeHeaderValue("application/octet-stream")
    
        End Sub

    Saturday, March 2, 2019 6:29 PM
  • User-1668014665 posted

    OK I got the above working in Chrome APP POSTMAN

    I published my code to my domain name

    inputted the URL in a browser address bar

    http://www.MYDOMAIN.com/api/data?symbol=AAPL

    I got this error

    This XML file does not appear to have any style information associated with it. The document tree is shown below.
      
    
    <Error><Message>An error has occurred.</Message><ExceptionMessage>Object reference not set to an instance of an object.</ExceptionMessage><ExceptionType>System.NullReferenceException</ExceptionType><StackTrace>  Etc etc etc </StackTrace></Error>
          

    What do I put in the URL to ensure CSV comes back

    I tried

    http://www.MYDOMAIN.com/api/data?symbol=AAPL&accept=text/csv    same error as above

    This http://www.MYDOMAIN.com/api/data?symbol=AAPL&type=csv     got the error below

    {"Method":"data","Error":{"Code":200,"Msg":"Invalid method"}}
    
    

    Any ideas

    I guess I must do something like this

    https://andrewlock.net/formatting-response-data-as-xml-or-json-based-on-the-url-in-asp-net-core/

    Saturday, March 2, 2019 10:38 PM
  • User475983607 posted

    icm63

    What do I put in the URL to ensure CSV comes back

    I explained this several times and even posted working source code in my last post.  The issue has to do with content negotiation.  The browser does not send accept: text/csv.  Just build an action that returns a file.

           Public Function [Get](ByVal Symbol As String) As HttpResponseMessage
    
                'Mock fetch data
                Dim queryResult = From d In data
                                  Where d.nSymbol = Symbol
                                  Select d
    
                Dim sb = New StringBuilder()
                sb.AppendLine(String.Format("{0},{1},{2},{3},{4},{5},{6}", "Symbol", "Date", "Open", "High", "Low", "Close", "Volume"))
                For Each SDOHLCV In queryResult.ToList()
                    sb.AppendLine(String.Format("{0},{1},{2},{3},{4},{5},{6}", Escape(SDOHLCV.nSymbol), Escape(SDOHLCV.nDate), Escape(SDOHLCV.nOpen), Escape(SDOHLCV.nHigh), Escape(SDOHLCV.nLow), Escape(SDOHLCV.nClose), Escape(SDOHLCV.nVolume)))
                Next
    
                Dim ms As Stream = New MemoryStream(Encoding.ASCII.GetBytes(sb.ToString()))
    
                Dim HttpResponseMessage As HttpResponseMessage = Request.CreateResponse(HttpStatusCode.OK)
                HttpResponseMessage.Content = New StreamContent(ms)
                HttpResponseMessage.Content.Headers.ContentDisposition = New System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
                HttpResponseMessage.Content.Headers.ContentDisposition.FileName = "SDOHLCV.csv"
                HttpResponseMessage.Content.Headers.ContentType = New System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream")
                HttpResponseMessage.Content.Headers.ContentLength = ms.Length
                Return HttpResponseMessage
    
            End Function
    
            Shared _specialChars As Char() = New Char() {","c, Convert.ToChar(vbLf), Convert.ToChar(vbCr), """"c}
    
            Private Function Escape(ByVal o As Object) As String
                If o Is Nothing Then
                    Return ""
                End If
    
                Dim field As String = o.ToString()
    
                If field.IndexOfAny(_specialChars) <> -1 Then
                    Return String.Format("""{0}""", field.Replace("""", """"""))
                Else
                    Return field
                End If
            End Function

    Saturday, March 2, 2019 10:59 PM
  • User-1668014665 posted

    Ok I get it.

    I was confused as other APIs I have seen have format=csv or format=json and the get the result written the browser page

    I get it convert output to :

      Public Function [Get](ByVal Symbol As String) As HttpResponseMessage

    QUESTION is there any way to run from the URL the option of

    &format=csv   OR &format=json

    format=csv would be returned within the file code, and json would be raw data has json (not in a file)

    Too weird maybe?

    Saturday, March 2, 2019 11:17 PM
  • User475983607 posted

    format=csv would be returned within the file code, and json would be raw data has json (not in a file)

    Too weird maybe?

    Just add an input parameter to the action.

    Public Function [Get](ByVal Symbol As String, ByVal Format As String) As HttpResponseMessage

    I would use two different controllers or action names.

    Saturday, March 2, 2019 11:22 PM
  • User-1668014665 posted

    This works great in POSTMAN

    Imports System.Net
    Imports System.Net.Http
    Imports System.Net.Http.Headers
    Imports System.Web.Http
    Imports System.IO
    Imports Newtonsoft.Json
    Imports System.Linq
    
    
    Namespace Controllers
        Public Class DataController
            Inherits ApiController
    
    
            ''' /api/data?symbol=AAPL
            Public Function [Get](ByVal Symbol As String,
                                  Optional FHead As Boolean = True,
                                  Optional SymD As Boolean = False,
                                  Optional DateF As Integer = 21) As HttpResponseMessage
    
                'FHead = File header on data
                'SymD = Symbol in data line
                'DateF = Date Format
    
    
    
    
                Dim HttpRes As HttpResponseMessage = Nothing
                Dim OHLC As List(Of SDOHLCV) = New List(Of SDOHLCV)
                Dim dr As IDataReader = Nothing
                Dim DateFormatstr As String = "MM/dd/yyyy"
                Dim RecCount As Int32
    
                Try
    
                    Select Case DateF
                        Case Is = 1
                            DateFormatstr = "M/dd/yyyy"
                        Case Is = 2
                            DateFormatstr = "M/d/yy"
                        Case Is = 3
                            DateFormatstr = "yyyyMMdd"
                        Case Is = 4
                            DateFormatstr = "yyMMdd"
                        Case Is = 5
                            DateFormatstr = "dd/MM/yyyy"
                        Case Is = 6
                            DateFormatstr = "d/M/yyyy"
                        Case Is = 7
                            DateFormatstr = "dd/MM/yy"
                        Case Is = 8
                            DateFormatstr = "d/M/yy"
                        Case Is = 9
                            DateFormatstr = "dd/MMM/yyyy"
                        Case Is = 10
                            DateFormatstr = "d/MMM/yyyy"
                        Case Is = 11
                            DateFormatstr = "dd/MMM/yy"
                        Case Is = 12
                            DateFormatstr = "d/MMM/yy"
                        Case Else
                            DateFormatstr = "MM/dd/yyyy"
                    End Select
    
                    Symbol = Symbol.ToUpper.Trim.ToString
    
                    'CHECK TOKEN HERE
    
                    'GET DATA
                    dr = UtilDataSQL.GetSymbolData(Symbol)
    
                    'FIRST DATA SET
                    Do While dr.Read
                        RecCount = UtilDBase.GetInt32(dr, "RecCount")
                    Loop
    
                    If RecCount = 0 Then
                        Dim err As String = String.Format("Error(-1001): {0} is not found: Records:Zero!", Symbol)
                        Return Request.CreateErrorResponse(HttpStatusCode.NotFound, err)
                    End If
    
                    'SECOND DATA SET
                    dr.NextResult()
                    Do While dr.Read
    
                        Dim n As New SDOHLCV With {
                            .nSymbol = UtilDBase.GetString(dr, "Symbol"),
                            .nDate = UtilDBase.GetDateTime(dr, "Date").ToString(DateFormatstr),
                            .nOpen = UtilDBase.GetDouble(dr, "Open"),
                            .nHigh = UtilDBase.GetDouble(dr, "High"),
                            .nLow = UtilDBase.GetDouble(dr, "Low"),
                            .nClose = UtilDBase.GetDouble(dr, "Close"),
                            .nVolume = UtilDBase.GetDouble(dr, "Volume")
                        }
    
                        OHLC.Add(n)
                        n = Nothing
                    Loop
    
                    Dim sb = New StringBuilder()
                    If FHead = True And SymD = True Then
                        sb.AppendLine(String.Format("{0},{1},{2},{3},{4},{5},{6}", "Symbol", "Date", "Open", "High", "Low", "Close", "Volume"))
                    ElseIf FHead = True And SymD = False Then
                        sb.AppendLine(String.Format("{0},{1},{2},{3},{4},{5}", "Date", "Open", "High", "Low", "Close", "Volume"))
                    End If
    
                    For Each SDOHLCV In OHLC
                        If SymD = True Then
                            sb.AppendLine(String.Format("{0},{1},{2},{3},{4},{5},{6}",
                                SDOHLCVCsvFormatter.Escape(SDOHLCV.nSymbol),
                                SDOHLCVCsvFormatter.Escape(SDOHLCV.nDate),
                                SDOHLCVCsvFormatter.Escape(SDOHLCV.nOpen),
                                SDOHLCVCsvFormatter.Escape(SDOHLCV.nHigh),
                                SDOHLCVCsvFormatter.Escape(SDOHLCV.nLow),
                                SDOHLCVCsvFormatter.Escape(SDOHLCV.nClose),
                                SDOHLCVCsvFormatter.Escape(SDOHLCV.nVolume)))
                        ElseIf SymD = False Then
                            sb.AppendLine(String.Format("{0},{1},{2},{3},{4},{5}",
                                SDOHLCVCsvFormatter.Escape(SDOHLCV.nDate),
                                SDOHLCVCsvFormatter.Escape(SDOHLCV.nOpen),
                                SDOHLCVCsvFormatter.Escape(SDOHLCV.nHigh),
                                SDOHLCVCsvFormatter.Escape(SDOHLCV.nLow),
                                SDOHLCVCsvFormatter.Escape(SDOHLCV.nClose),
                                SDOHLCVCsvFormatter.Escape(SDOHLCV.nVolume)))
                        End If
                    Next
    
                    Dim ms As Stream = New MemoryStream(Encoding.ASCII.GetBytes(sb.ToString()))
    
                    HttpRes = Request.CreateResponse(HttpStatusCode.OK)
                    HttpRes.Content = New StreamContent(ms)
    
                    HttpRes.Content.Headers.ContentDisposition = New System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") _
                        With {.FileName = Symbol & ".csv"}
    
                    HttpRes.Content.Headers.ContentType = New System.Net.Http.Headers.MediaTypeHeaderValue("text/csv")
                    HttpRes.Content.Headers.ContentLength = ms.Length
    
    
    
                Catch ex As Exception
                    UtilDataSQL.RunExELMAH(ex, "WebAPI:" & Symbol & ":SQLEx2")
    
                Finally
                    If OHLC IsNot Nothing Then OHLC = Nothing
                    If dr IsNot Nothing Then
                        dr.Close()
                        dr.Dispose()
                    End If
                End Try
    
                Return HttpRes
            End Function
    
    
    
    
    
        End Class
    End Namespace

    the only think I changed is webconfig for IIS at there end is different than my home PC IIS

    <?xml version="1.0" encoding="utf-8"?>
    
    
    <configuration>
      
      <configSections>
        <sectionGroup name="elmah">
          <section name="security" requirePermission="false" type="Elmah.SecuritySectionHandler, Elmah" />
          <section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah" />
          <section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah" />
          <section name="errorFilter" requirePermission="false" type="Elmah.ErrorFilterSectionHandler, Elmah" />
        </sectionGroup>
      </configSections>
    
    
      <!-- ELMAH SQL ERRORS-->
      <elmah>
        <errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="RTT_OPS_con" applicationName="/RTT_DataAPI" />
        <security allowRemoteAccess="0" />
        <errorFilter>
          <test>
            <or>
              <equal binding="HttpStatusCode" value="404" type="Int32" />
              <jscript>
                <expression>
                  <![CDATA[
                    // @assembly Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
                    // @import Microsoft.VisualBasic
                    Information.Err().Number < 0
                    ]]>
                </expression>
              </jscript>
            </or>
          </test>
        </errorFilter>
      </elmah>
    
    
    
      <appSettings>
    
      </appSettings>
    
      
    
      <location path="1966error.axd">
        <system.web>
          <authorization>
            <allow users="*"/>
          </authorization>
        </system.web>
      </location>
    
    
    
    
    
      <!-- DBASE CONNECTIONS FOR LOCAL MACHINE  999-->
      <connectionStrings>
        <add name="RTT_OPS_con" connectionString="Server=.;Database=XXXXXXXXX;User Id=XXXXXXXX;Password=XXXXXXXXXXXX;MultipleActiveResultSets=true;Trusted_Connection=False;Connection Timeout=60;" providerName="System.Data.SqlClient" />
      </connectionStrings>
    
    
      
      
      <system.web>
        <!-- WEB API -->
        <compilation debug="false" targetFramework="4.6.1" />
        <httpRuntime targetFramework="4.6.1" />
        <trust level="Full"/>
        <customErrors mode="Off"/>
    
        
        <httpHandlers>
          <!-- ELMAH  LEAVE FOR II6-->
          <add verb="POST,GET,HEAD" path="1963error.axd" type="Elmah.ErrorLogPageFactory, Elmah"/>
        </httpHandlers>
        
        
      <httpModules>
    
        <!-- REMOVE UNWANTED PIPES -->
        <remove name ="Session="/>
        <remove name="WindowsAuthentication"/>
        <remove name="PassportAuthentication"/>
        <remove name="AnonymousIdentification"/>
        <remove name="FileAuthorization"/>
        <remove name="UrlAuthorization"/>
    
    
        <!-- ELMAH  LEAVE FOR II6-->
         <add name="FixIIS5xWildcardMapping" type="Elmah.FixIIS5xWildcardMappingModule, Elmah"/>
          <add name="MsAjaxDeltaErrorLog" type="Elmah.MsAjaxDeltaErrorLogModule, Elmah"/>
          <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />
          <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" />
          <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" />
    
        
        </httpModules>
        
      </system.web>
    
    
      <!-- WEB API -->
      <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
          <dependentAssembly>
            <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" />
            <bindingRedirect oldVersion="0.0.0.0-11.0.0.0" newVersion="11.0.0.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="0.0.0.0-5.2.4.0" newVersion="5.2.4.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
          </dependentAssembly>
        </assemblyBinding>
      </runtime>
    
    
      <!-- WEB API -->
      <system.codedom>
        <compilers>
          <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
          <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
        </compilers>
      </system.codedom>
    
    
    
    
      <system.webServer>
        
        <validation validateIntegratedModeConfiguration="false" />
        <defaultDocument>
          <files>
            <clear />
            <add value="index.html"/>
          </files>
        </defaultDocument>
        
    
        <modules>
          <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" preCondition="managedHandler" />
          <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" preCondition="managedHandler" />
          <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" preCondition="managedHandler" />
    
          <!-- REMOVE UNWANTED PIPES -->
          <remove name="WindowsAuthentication"/>
          <remove name="PassportAuthentication"/>
          <remove name="AnonymousIdentification"/>
          <remove name="FileAuthorization"/>
          
        </modules>
    
        
        <handlers>
          <!-- WEB API -->
          <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
          <remove name="OPTIONSVerbHandler" />
          <remove name="TRACEVerbHandler" />
    
          <!-- ELMAH IF IIS7 removes IIS6 ENTRIES -->
          <remove name="WebServiceHandlerFactory-Integrated" />
    
          <!-- WEB API -->
          <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    
          <!-- ELMAH IIS7 -->
          <add name="Elmah" path="1963error.axd" verb="POST,GET,HEAD" type="Elmah.ErrorLogPageFactory, Elmah" preCondition="integratedMode" />
    
        </handlers>
    
      </system.webServer>
    
      
      
     
    
    </configuration>
    

    When I PUBLISH and go line from either CHROME or FIRECFOX

    This    http://www.XXXXXXXX.com/api/data?symbol=AAPL

    Gives me this error

    This XML file does not appear to have any style information associated with it. The document tree is shown below.
            <Error><Message>An error has occurred.</Message><ExceptionMessage>A null value was returned where an instance of 
    
    HttpResponseMessage was 
    
    expected.</ExceptionMessage><ExceptionType>System.InvalidOperationException</ExceptionType><StackTrace>   at 
    
    System.Web.Http.Controllers.ResponseMessageResultConverter.Convert(HttpControllerContext controllerContext, Object 
    
    actionResult)
       at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__1.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__5.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__15.MoveNext()</StackTrace></Error>
    

    Any ideas

    Sunday, March 3, 2019 1:49 AM
  • User1120430333 posted

    When I PUBLISH and go line from either CHROME or FIRECFOX

    You could have discovered the issue if you had stopped using IIS Express for the ASP.NET project and linked the project to local IIS and started developing, testing and debugging the Web project through VS using local IIS.

    https://docs.microsoft.com/en-us/visualstudio/debugger/how-to-enable-debugging-for-aspnet-applications?view=vs-2017

    However, you would probably have needed a console program to do the testing where you could have set a breakpoint in the console program, used the Debugger's Attach To Process, find the WPW3.exe that is servicing the Application Pool that is hosting the WebAPI set breakpoints and test and debugged the code.

    https://stackify.com/w3wp-exe-iis-worker-process/

    I stopped using IIS Express long ago and just use local IIS, becuase IIS Express hides issues until it is exposed on IIS.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, March 3, 2019 2:37 AM
  • User475983607 posted

    Any ideas

    I recommend catching the complete exception and any inner exception(s).  The Exception.Mssage, System.InvalidOperationException, is generic but means that something went wrong in the logic.  I would closer at fetching or manipulating data from the database and verify the data is expected.

    https://docs.microsoft.com/en-us/dotnet/api/system.invalidoperationexception?view=netframework-4.7.2

    I disagree that developing with IIS Express is a handicap.  I use IIS Express everyday and don't have issues.  One problem you can run into though, is IIS Express runs under your account which is most likely an admin account.  This can cause errors when trying to access resources outside the web application when deployed to a server.  The web application  runs under the application pool identity (default) which has limited access.

    Sunday, March 3, 2019 3:57 PM
  • User-1668014665 posted

    Found the error my DB connection string was wrong

    Sunday, March 3, 2019 4:10 PM
  • User-1668014665 posted

    AWESOME SUPPORT

    THANKS TEAM ASP NET 

    EVEN VB GUYS GET HELP!

    Sunday, March 3, 2019 6:16 PM
  • User1120430333 posted

    I disagree that developing with IIS Express is a handicap. I use IIS Express everyday and don't have issues. One problem you can run into though, is IIS Express runs under your account which is most likely an admin account. This can cause errors when trying to access resources outside the web application when deployed to a server. The web application runs under the application pool identity (default) which has limited access.

    I have contracted or worked as a fulltime employee  in a lot of shops over the years  private sector and government. I have only been in one shop where IIS Express was even used. The rest of them used local IIS  that matched the environment that the Web application was being hosted by the QA, and Production Web servers. 

    I worked in some shops where the developer's computer was a Windows O/S server version that matched the servers that were hosting IIS and the Web program

    So I and apparently a whole lot of others don't use IIS Express for the very reason that it is NOT IIS, a real Web server. You need to go out into the field, and find out what the real  deal is about.  

    Sunday, March 3, 2019 6:17 PM
  • User475983607 posted

    DA924

    So I and apparently a whole lot of others don't use IIS Express for the very reason that it is NOT IIS, a real Web server. You need to go out into the field, and find out what the real  deal is about.  

    You could be right... 

    My point is there is nothing wrong with IIS Express or any of the other light weight hosts used in modern web development.  The light weight hosts save a lot of development time. I simply can not imagine going back to the dark ages of web dev without file watchers and console debug output.  Hey, but man you do you.

    Keep in mind, the type of IIS configuration you're referring to is generally done once then it just becomes part of the deployment process.   Maybe expand your horizons and jump into the newer web dev practices.

    Sunday, March 3, 2019 10:00 PM
  • User1120430333 posted

    mgebhard

    DA924

    So I and apparently a whole lot of others don't use IIS Express for the very reason that it is NOT IIS, a real Web server. You need to go out into the field, and find out what the real  deal is about.  

    You could be right... 

    My point is there is nothing wrong with IIS Express or any of the other light weight hosts used in modern web development.  The light weight hosts save a lot of development time. I simply can not imagine going back to the dark ages of web dev without file watchers and console debug output.  Hey, but man you do you.

    Keep in mind, the type of IIS configuration you're referring to is generally done once then it just becomes part of the deployment process.   Maybe expand your horizons and jump into the newer web dev practices.

    Why what new practices are you talking about?

    The Web application is not running on IIS Express when  it is deployed. It's running on IIS. Myself, I'll just go directly to the horse, local IIS, and ride that knowing that if  the program fails or passes on local IIS during the development and testing process, it's going to do the same when deployed to IIS on another machine.

    IIS Express to me is no better than the VS Web Developer in previous versions of Visual Stuido. I would rather know that it failed on local IIS than to deploy the solution to a Web Server in QA and have it fail there and face that embracement, becuase it never failed when using IIS Express. 

    And besides, some of the biggest companies and government institutions  shops are not using IIS Express during the development and testing  process by the developer on the developer's machine.  

    Sunday, March 3, 2019 10:52 PM
  • User475983607 posted

    DA924

    Why what new practices are you talking about?

    I'm referring to modern web development tools.  I would have a very hard time going back to the type of development practices that you're suggesting.   I use local IIS every day for supporting classic ASP applications that consume COM/COM+.  I also use local IIS to host ASMX and WCF services that do not change much.  I try to pick the right tools for the job.

    DA924

    The Web application is not running on IIS Express when  it is deployed. It's running on IIS. Myself, I'll just go directly to the horse, local IIS, and ride that knowing that if  the program fails or passes on local IIS during the development and testing process, it's going to do the same when deployed to IIS on another machine.

    Dealing will local IIS cuts into my development time.  I generally have a few kestrel hosts running, task runners, and at least one IIS Express host.  I rarely use a debugger and mostly rely on writing debug output to the console.  To your point, when the program fails, I know immediately and look no further than the console screen open on my of my monitors.  When hosting in IIS I have to open a log.  It's just extra step that takes away from development time.

    DA924

    IIS Express to me is no better than the VS Web Developer in previous versions of Visual Stuido. I would rather know that it failed on local IIS than to deploy the solution to a Web Server in QA and have it fail there and face that embracement, becuase it never failed when using IIS Express. 

    I find this statement rather telling.  Once you have IIS configured, it just works,  Generally IIS configuration is a very small effort as compared to actual development. 

    DA924

    And besides, some of the biggest companies and government institutions  shops are not using IIS Express during the development and testing  process by the developer on the developer's machine.

    I'm pretty confident most developers develop on their local machine then deploy to a dev or text environment.  In my experience, developers get a bit  touchy when the someone breaks the dev or test environment.  

    Anyway, you do you and I'll do me.  

    Sunday, March 3, 2019 11:36 PM
  • User1120430333 posted

    I'm referring to modern web development tools. I would have a very hard time going back to the type of development practices that you're suggesting. I use local IIS every day for supporting classic ASP applications that consume COM/COM+. I also use local IIS to host ASMX and WCF services that do not change much. I try to pick the right tools for the job.

    I only deal with new development. You get that a lot as a contractor. 

    Dealing will local IIS cuts into my development time. I generally have a few kestrel hosts running, task runners, and at least one IIS Express host. I rarely use a debugger and mostly rely on writing debug output to the console. To your point, when the program fails, I know immediately and look no further than the console screen open on my of my monitors. When hosting in IIS I have to open a log. It's just extra step that takes away from development time.

    I am talking about the development process at the developer's   machine,  and when the Web program throws an exception in debug mode, and  it's hosted on local IIS,  it points directly to the exception at code at the time of the exception.  I don't have to look at some log file., although I have looked at log files dumped in QA and production environments. 

    I find this statement rather telling. Once you have IIS configured, it just works, Generally IIS configuration is a very small effort as compared to actual development.

    Yep, and  as along as local IIS not Express is being used, you're right there is no problem.

    I'm pretty confident most developers develop on their local machine then deploy to a dev or text environment. In my experience, developers get a bit touchy when the someone breaks the dev or test environment.

    That seems like a waste of money. Nah, I have not seen that in a long time. I see deployment to QA. If it breaks it broke on the developer's machine becuase the developer's machine will have the latest version of the code that was checked into the repository. The developer's machine is the test environment,.

    Anyway, you do you and I'll do me.

    I don't see IIS Express being used, and I don't use. There is nothing wrong in using VS and the Web project out on local IIS instead of IIS Express. If it was not meant to be done in either case, then nether one of the solutions would be available in Visual Stuido. But that's not the case, and there is nothing wrong in using local IIS.

    It is what it is.

    Monday, March 4, 2019 12:15 AM