Results 1 to 30 of 30

Thread: Syntax

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Aug 2021
    Posts
    117

    Syntax

    I'm new to .net but am having trouble with an "End of Statement Expected" error when defining a text line.

    Here is my code:

    Code:
    Private Function buildPVRRequest() As String
            Dim output As String = "{ "patient": {"identity": {"dateOfBirth": "1997-03-20","familyName": "Dalton", "givenName": "James","secondInitial": "","sex": "2"},"medicare": {"memberNumber": "2953931881","memberRefNumber":"1"}}, "dateofService": "2022-03-04","typeCode":"PVM"}"
    
            Return output
    End Function
    I'm wanting to return the output of the Function as the exact text inside the two "" marks - why can't I do that???

    Thanks for helping...
    Last edited by dday9; Apr 7th, 2022 at 10:19 AM. Reason: Added BB Code

  2. #2
    Frenzied Member
    Join Date
    Feb 2003
    Posts
    1,807

    Re: Syntax

    Your syntax doesn't make any sense. What variables are involved and could you post a mockup of the output you expect?

  3. #3

    Thread Starter
    Lively Member
    Join Date
    Aug 2021
    Posts
    117

    Re: Syntax

    Well I haven't put in the variables yet, this is just a trial of a web services transmission, with the raw text being prepared for transmission before I add the variables - so I just wanted the raw text, but Visual Studio returns an error expecting an end of statement. So this text is the body of the request for web services with dummy data in there for various variable. Cant I do this as a test??

  4. #4

    Thread Starter
    Lively Member
    Join Date
    Aug 2021
    Posts
    117

    Re: Syntax

    Can anyone help? If I just return a simple text I dont get errors, so something must be wrong with the construction that I have to include in the body, but what is it????

  5. #5
    Fanatic Member
    Join Date
    Aug 2004
    Location
    Essex, UK
    Posts
    750

    Re: Syntax

    Adding an extra pair of quotation marks around each item will work:

    Code:
            Dim output As String = "{ ""patient"": {""identity"": {""dateOfBirth"": ""1997-03-20"",""familyName"": ""Dalton"", ""givenName"": ""James"",""secondInitial"": "",""sex"": ""2""},""medicare"": {""memberNumber"": ""2953931881"",""memberRefNumber"":""1""}}, ""dateofService"": ""2022-03-04"",""typeCode"":""PVM""}
    "

    A better option would be to use single quotes around the elements if your web service will accept those.

  6. #6

    Thread Starter
    Lively Member
    Join Date
    Aug 2021
    Posts
    117

    Re: Syntax

    Oh great, that works, thanks - no they wont accept single quotes, but the double doubles you suggested works, thanks Paul

  7. #7
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,479

    Re: Syntax

    If you want to create a JSON Response, it’d be easier using Newtonsoft JSON than trying to cobble together a string through string concatenation…

    https://www.codeproject.com/Question...t-in-windows-a
    Last edited by .paul.; Mar 4th, 2022 at 09:09 AM.

  8. #8

    Thread Starter
    Lively Member
    Join Date
    Aug 2021
    Posts
    117

    Re: Syntax

    Ah, I see, yes better! Thanks!

  9. #9
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    39,038

    Re: Syntax

    Also, if you are using .NET5 or 6, there are some built in libraries that could replace NewtonSoft. It's the objects in the System.Text.Json namespace.
    My usual boring signature: Nothing

  10. #10

    Thread Starter
    Lively Member
    Join Date
    Aug 2021
    Posts
    117

    Re: Syntax

    Oh cool, thanks, I’ll have a look.]

  11. #11
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,753

    Re: Syntax

    Going the serialization way, Visual Studio has a cool feature called Paste JSON as Classes that can be found under Edit > Paste Special > Paste JSON as Classes. Using either Newtonsoft.Json or System.Text.Json, you can tidy the classes up a little bit using decorators so that you can conform to .NET standard naming conventions while still serializing the JSON to the expected values.

    This is how the class definitions would look (tidied up):
    Code:
    Public Class Payload
        <JsonProperty("patient")>
        Public Property Patient As Patient
    
        <JsonProperty("dateofService")>
        Public Property ServiceDate As DateTime
    
        <JsonProperty("typeCode")>
        Public Property TypeCode As String
    End Class
    
    Public Class Patient
    
        <JsonProperty("identity")>
        Public Property Identity As Identity
    
        <JsonProperty("medicare")>
        Public Property Medicare As Medicare
    
    End Class
    
    Public Class Identity
    
        <JsonProperty("dateOfBirth")>
        Public Property Birthday As String
    
        <JsonProperty("familyName")>
        Public Property FamilyName As String
    
        <JsonProperty("givenName")>
        Public Property GivenName As String
    
        <JsonProperty("secondInitial")>
        Public Property SecondInitial As String
    
        <JsonProperty("sex")>
        Public Property Sex As String
    
    End Class
    
    Public Class Medicare
    
        <JsonProperty("memberNumber")>
        Public Property MemberNumber As String
    
        <JsonProperty("MemberRefNumber")>
        Public Property MemberReferenceNumber As String
    
    End Class
    And here is how you'd create a new instance of the object and serialize it:
    Code:
    Dim payload = New Payload() With {
        .Patient = New Patient() With {
            .Identity = New Identity() With {
                .Birthday = New DateTime(1997, 3, 7),
                .FamilyName = "Dalton",
                .GivenName = "James",
                .SecondInitial = String.Empty,
                .Sex = "2"
            },
            .Medicare = New Medicare() With {
                .MemberNumber = "2953931881",
                .MemberReferenceNumber = "1"
            }
        },
        .ServiceDate = New DateTime(2022, 3, 4),
        .TypeCode = "PVM"
    }
    Dim serializedPayload = JsonConvert.SerializeObject(payload)
    Fiddle: https://dotnetfiddle.net/OHdFM8
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  12. #12

    Thread Starter
    Lively Member
    Join Date
    Aug 2021
    Posts
    117

    Re: Syntax

    Wow, thanks Dday, thats amazing generosity for you to help me, I’ll give it a go once I’m back to the coding…

  13. #13

    Thread Starter
    Lively Member
    Join Date
    Aug 2021
    Posts
    117

    Re: Syntax

    Dday and Shaggy, I have investigated further and the core base vb code I was given has a JSONUtility.vb component to it, which is used to generate RSA keys for the project and to generate token authorisation for the Httputility communications such as my medicare topic.

    I have copied the component below in full. Dday's 4 public classes appear at the end. The code flags an error that the JSONProperty is not defined.

    Also when I paste special using the Edit:Paste special:PasteJSONAsClasses feature I get an error stating the clipboard content isnt a valid JSON instance - flagging unexpected character when parsing value: P.Path", line 2 position 4.

    How do I fix this?

    Code:
    Public Class JSONUtility
    
        Public Shared Function convertDictionaryToJson(dict As Dictionary(Of String, Object)) As String
            ' open json object
            Dim result As String = "{"
    
            ' iterate through dictionary and populate json object
            For Each kvp As KeyValuePair(Of String, Object) In dict
                result += """" + kvp.Key + """:""" + kvp.Value + ""","
            Next
    
            ' remove trailing comma
            result = result.Remove(result.Length - 1)
    
            ' close json object
            result += "}"
    
            Return result
        End Function
    
        Public Class ActivateResponse
            Public Property orgId As String
            Public Property deviceName As String
            Public Property deviceStatus As String
            Public Property deviceExpiry As String
            Public Property keyStatus As String
            Public Property keyExpiry As String
        End Class
    
    
        Public Class TokenResponse
            Public Property device_expiry As String
            Public Property key_expiry As String
            Public Property expires_in As Int16
            Public Property access_token As String
    
        End Class
    
    
        ' Dday and SHAGGYS CODE
        Public Class Payload
            <JsonProperty("patient")>
            Public Property Patient As Patient
    
            <JsonProperty("dateofService")>
            Public Property ServiceDate As DateTime
    
            <JsonProperty("typeCode")>
            Public Property TypeCode As String
        End Class
    
        Public Class Patient
    
            <JsonProperty("identity")>
            Public Property Identity As Identity
    
            <JsonProperty("medicare")>
            Public Property Medicare As Medicare
    
        End Class
    
        Public Class Identity
    
            <JsonProperty("dateOfBirth")>
            Public Property Birthday As String
    
            <JsonProperty("familyName")>
            Public Property FamilyName As String
    
            <JsonProperty("givenName")>
            Public Property GivenName As String
    
            <JsonProperty("secondInitial")>
            Public Property SecondInitial As String
    
            <JsonProperty("sex")>
            Public Property Sex As String
    
        End Class
    
        Public Class Medicare
    
            <JsonProperty("memberNumber")>
            Public Property MemberNumber As String
    
            <JsonProperty("MemberRefNumber")>
            Public Property MemberReferenceNumber As String
    
        End Class
    End Class
    Last edited by dday9; Apr 5th, 2022 at 08:42 AM. Reason: Added BB Code

  14. #14
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,479

    Re: Syntax

    The JsonProperty attributes are the Newtonsoft.Json or System.Text.Json decorators that dday9 told you about…

  15. #15

    Thread Starter
    Lively Member
    Join Date
    Aug 2021
    Posts
    117

    Re: Syntax

    Hmm, OK, so I think I have to load those or have them recognised? I have Newtonsoft.json in my References and I have now added

    Imports Newtonsoft.Json

    as the opening statement to the whole module. It seems to have resolved the issue - is this all I have to do?
    Last edited by Bear89; Mar 5th, 2022 at 11:11 PM.

  16. #16
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,479

    Re: Syntax

    This is how it would look without dday’s decorators…

    Code:
    Public Class Payload
        Public Property patient As Patient
        Public Property dateofService As DateTime
        Public Property typeCode As String
    End Class
    
    Public Class Patient
        Public Property identity As Identity
        Public Property medicare As Medicare
    End Class
    
    Public Class Identity
        Public Property dateOfBirth As String
        Public Property familyName As String
        Public Property givenName As String
        Public Property secondInitial As String
        Public Property sex As String
    End Class
    
    Public Class Medicare
        Public Property memberNumber As String
        Public Property memberRefNumber As String
    End Class
    Last edited by .paul.; Mar 5th, 2022 at 11:53 PM.

  17. #17

    Thread Starter
    Lively Member
    Join Date
    Aug 2021
    Posts
    117

    Re: Syntax

    Thanks Paul, makes sense, at least I think I'm following, and it does seem to work, with payload produced and appropriate, though I have it displaying at the moment as a LogScreen where it appears as a string - can I display it somehow in the correct format so I can check it?

  18. #18

  19. #19

    Thread Starter
    Lively Member
    Join Date
    Aug 2021
    Posts
    117

    Re: Syntax

    Guys, I'm not great with .JSON and now I'm struggling to format the Web Services response to the above code. Here is an example of a response below:

    Code:
    {
      "medicareStatus" : {
        "status" : {
          "code" : 0,
          "text" : "Patient is eligible to claim for Medicare with details provided."
        }
      }
    }
    And the designated structure for the response, in my own declarations, is:
    Code:
      Public Class MedicareStatus
            <JsonProperty("Status")>
            Public Property Status As String
    
            <JsonProperty("CurrentMembership")>
            Public Property CurrentMembership As String
    
            <JsonProperty("CurrentMember")>
            Public Property CurrentMember As String
        End Class
        Public Class status
            <JsonProperty("Code")>
            Public Property Code As String
    
            <JsonProperty("text")>
            Public Property Text As String
        End Class
        Public Class CurrentMembership
    
            <JsonProperty("memberNumber")>
            Public Property MemberNumber As String
    
            <JsonProperty("memberRefNumber")>
            Public Property MemberRefNumber As String
        End Class
        Public Class currentMember
    
            <JsonProperty("givenName")>
            Public Property GivenName As String
    
        End Class
    So what I'm wanting is to be able to return individual properties back to the WPF. I have tried the following but I get no data in the output Messageboxes. Am I way off???

    Code:
            Dim result As String = 'Webservices respose'
    
    
            Dim json As String = result
            Dim ser As JObject = JObject.Parse(json)
            Dim data As List(Of JToken) = ser.Children().ToList
            Dim output As String = ""
            Dim output1 As String = ""
    
            For Each item As JProperty In data
                item.CreateReader()
                Select Case item.Name
                    Case "MedicareStatus"
                        output += "MedicareStatus:" + vbCrLf
                        For Each MedicareStatus As JObject In item.Values
                            Dim u As String = MedicareStatus("Status")
                            Dim d As String = MedicareStatus("CurrentMembership")
                            Dim c As String = MedicareStatus("CurrentMember")
                            output = u + vbTab + d + vbTab + c + vbCrLf
                        Next
    
                    Case "Status"
                        output += "Status:" + vbCrLf
                        For Each msg As JObject In item.Values
                            Dim f As String = "Code"
                            Dim t As String = "Text"
                            output1 = f + vbTab + t + vbTab
    
                        Next
    
                End Select
            Next
            MsgBox(output)
            MsgBox(output1)
    Last edited by dday9; Apr 5th, 2022 at 08:43 AM.

  20. #20
    Frenzied Member
    Join Date
    Feb 2003
    Posts
    1,807

    Re: Syntax

    Some tips:
    1. You could initialize strings to "Nothing" instead of an empty string.
    2. The "Output" variable should be declared as "StringBuilder" (System.Text).
    Link: https://docs.microsoft.com/en-us/dot...r?view=net-6.0
    3. "VbCrLf" can be replaced with "NewLine" (System.Environment)
    4. Look up string interpolation: https://docs.microsoft.com/en-us/dot...olated-strings
    5. "MsgBox" can be replaced with "MessageBox.Show" (System.Windows.Forms)
    6. In fact, I recommend avoiding the Microsoft.VisualBasic namespace as much as possible.
    7. Use code tags to enclose your code when posting it in the forum. (The "#" button in the toolbar above the message you're about to submit,)

  21. #21

    Thread Starter
    Lively Member
    Join Date
    Aug 2021
    Posts
    117

    Re: Syntax

    OK, thanks Peter, but I'm still struggling, would it be possible someone to write a brief vb code to extract the values of 'code' (should = 0) and 'text' (should = 'Patient is eligible to claim for Medicare with details provided.') in my above example just so I can see what it is meant to look like???
    Last edited by Bear89; Apr 5th, 2022 at 06:30 PM.

  22. #22
    Frenzied Member
    Join Date
    Feb 2003
    Posts
    1,807

    Re: Syntax

    @bear89: you're welcome! And I see you put code tags in your posts. :-)

    I am afraid I don't understand your last question. Sorry.

  23. #23

    Thread Starter
    Lively Member
    Join Date
    Aug 2021
    Posts
    117

    Re: Syntax

    Thanks Peter, I was really just wondering f it was possible for you or someone to write a simple piece of coding to extract the object values from the JSON response (ie the first set of code in my 10:26pm post yesterday). I’m just struggling as I read through your suggestions to see how it should be done?

    So my understanding is that the ‘code’ and ‘text’ elements are constants and the respective variables are ‘=0’ and ‘= ‘Patient is eligible….’. So how can I obtain the elements and their values in a fixed code to deal with this response? Does that make sense?

  24. #24
    Frenzied Member
    Join Date
    Feb 2003
    Posts
    1,807

    Re: Syntax

    Nothing I posted directly relates to your question. My tips apply to anything written in vb.

    Perhaps you should check this tutorial:
    https://www.w3schools.com/js/js_json_intro.asp

  25. #25

    Thread Starter
    Lively Member
    Join Date
    Aug 2021
    Posts
    117

    Re: Syntax

    Hmm, nice tutorial Peter, but it has not helped, for example I try using the suggested JSON Objects syntax to get my Code and Text object values, and various declarations etc that I try just give errors.

    Do I have to import something to access the Javascript to the code:
    Dim myObj As Object = JSON.parse(result)
    as when I enter this in my VS project I get JSON as not declared - but I had presumed it would be part of the Imports I already have, ie:
    Imports Newtonsoft.Json
    Imports Newtonsoft.Json.Linq

    Do I need other imports?

    Or can anyone else just tell me how I can access the values of the objects in the JSON response?
    Last edited by Bear89; Apr 6th, 2022 at 07:04 AM.

  26. #26
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,753

    Re: Syntax

    Again, I would highly suggest using Edit > Paste Special > Paste As Json and then clean up the generated code to follow typical .NET coding patterns.

    For example, based on your JSON from post 19, these are the class definitions:
    Code:
    Public Class WebResponse
    	
    	<JsonProperty("medicareStatus")>
    	Public Property MedicareStatus As MedicareStatus
    
    End Class
    
    Public Class MedicareStatus
    	
    	<JsonProperty("status")>
    	Public Property Status As Status
    
    End Class
    
    Public Class Status
    
    	<JsonProperty("code")>
    	Public Property Code As Integer
    
    	<JsonProperty("text")>
    	Public Property Text As String
    
    End Class
    And here you are parsing it:
    Code:
    Dim conversion = JsonConvert.DeserializeObject(Of WebResponse)(literal)
    Fiddle: https://dotnetfiddle.net/JHoFyv
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  27. #27

    Thread Starter
    Lively Member
    Join Date
    Aug 2021
    Posts
    117

    Re: Syntax

    Excellent, all works well, thanks Dday, I have used the decorators as you suggest and I have a lot of code to do now, so just a couple of questions:
    1. What are the benefits of the decorators - I have tried to look up without a clear answer as many don't use them?
    2. I am using visual studio with vb.net and notice their updated inbuilt system.text.json, which of course they promote. My guess is that Newtonsoft.json is more mature and best for my needs, but any comment?
    3. I do have a variety of properties returned in the web service response and my code flagged an ex if I tried to retrieve an absent property, so I have got around this with an If statement, but I suspect there is a more efficient way, but I just cant see it? Current code example is:

    If result.Contains("Text") Then
    Dim statusCode1 = rootMedicare.MedicareStatus.Status.Text
    MsgBox(statusCode1)
    End If
    4. And last, do you know a good newtonsoft.json tutorial in vb.net?

    Thank you once again.

  28. #28
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,753

    Re: Syntax

    1. It just helps with the naming conventions. Typically speaking, programmers are very opinionated. In .NET land you will find property names in proper-case whereas in JavaScript you will find pascal-case, and in PHP you will find heavy usage of underscores.

    2. System.Text.Json is a complete rewrite of Newtonsoft. For a while, Microsoft really pushed XML and so in the days of the .NET framework there was widespread support for XML but not JSON, so you has to go through non-Microsoft libraries to parse JSON and Newtonsoft was most popular. When .NET core (now .NET 5) came out, Microsoft rolled out support for JSON by getting the main author of Newtonsoft to rewrite the library conforming to Microsoft’s standards.

    3. Typically if you get unexpected responses, you will need to parse the JSON to something generic and use conditional statements like you are. This is a side effect of Visual Basic .NET being a strongly typed language.

    4. Not really. JSON was ready for me because I worked with XML and relational databases for a while. My best advice is to just jump in and ask questions like you are doing.
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  29. #29

    Thread Starter
    Lively Member
    Join Date
    Aug 2021
    Posts
    117

    Re: Syntax

    Excellent, thanks Dday, I'll stay with my current approaches then.

    I do agree with your view that just jumping in and asking questions is the best way to learn. I have a reasonably large database (20,000 records) which was coded in VB Access many years ago and it is time to completely re-write, especially for us as we need to interact with high security which obligates the newer cryptographies. Tutorials and google searches sometimes help, but being able to have your expert advice does so often save time, so thanks to you and all!!

    I do have a new question though and not sure if you can help. Our project is in WPF with vb.net of course, and the main window has a range of data controls which we can read and write to via mainwindow.<controlname>.textbox. These controls are bound to a large primary table with datagrid, with the primary datagrid in turn binding to several child tables/datagrids. I can access the properties of each of the child datagrids and alter them, but I can't see how to access individual cells to read and write to. So essentially I need a simple syntax for these grid cells - such as the simple code which works for the textbox controls (ie Dim aa = mw.<controlname>.tb)

    There must surely be a simple way, but can you help?
    Last edited by Bear89; Apr 7th, 2022 at 10:10 PM.

  30. #30
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,753

    Re: Syntax

    You would need to get the child from the parent, something like this:
    Code:
    Dim textbox = MyMainWindow.Children.OfType(Of TextBox).FirstOrDefault(Function(txt) txt.Name = "TheNameOfTheTextBox")
    If (textbox IsNot Nothing) Then
        MessageBox.Show(textbox.Text)
    End If
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width