Using Flurl in vb.net - vb.net

How can I use Flurl in VB.NET for GET and POST? I installed the NuGet package and imported Flurl.
How can I translate this C# code to VB?
var responseString = await "http://www.example.com/recepticle.aspx"
.PostUrlEncodedAsync(new { thing1 = "hello", thing2 = "world" })
.ReceiveString();

First, import the relevant namespace:
Imports Flurl.Http
..and then this should work:
Dim responseString = Await "http://www.example.com/recepticle.aspx".
PostUrlEncodedAsync(New With {.thing1 = "hello", .thing2 = "world"}).
ReceiveString()
Explanation:
In VB.NET, when declaring an anonymous object, you should use New With instead of new. Also, the properties must be preceded by a dot ..
When breaking statements into multiple lines, the dot can't be at the beginning of the line so we add it at the end of the previous line. If you prefer to start the next line with a dot. You may end the previous line with the line-continuation character _ like this:
Dim responseString = Await "http://www.example.com/recepticle.aspx" _
.PostUrlEncodedAsync(New With {.thing1 = "hello", .thing2 = "world"}) _
.ReceiveString()
For more information, see: Continuing a statement over multiple lines

Related

How to serialize an object with newtonsoft, which has a value with backslash [\]

I prepared this small example to show you my problem (vb.net and Newtonsoft)
I would prefer that the solution be done with Newtonsoft.
Public Class Message
Property Emoji As String
End Class
Public Sub GetJson()
Dim msgObject As New Message With {.Emoji = "\uD83D\uDE00"}
'Option 1
Dim JsonSerializerSettings As New JsonSerializerSettings
JsonSerializerSettings.StringEscapeHandling = StringEscapeHandling.EscapeNonAscii
Dim msgJson_1 As String = Newtonsoft.Json.JsonConvert.SerializeObject(msgObject, JsonSerializerSettings)
'Option 2
Dim msgJson_2 As String = Newtonsoft.Json.JsonConvert.SerializeObject(msgObject, Newtonsoft.Json.Formatting.None)
'Option 3
Dim stringWriter As New StringWriter()
Using writer As New JsonTextWriter(stringWriter)
writer.Formatting = Formatting.None
Dim serializer As New JsonSerializer()
serializer.Serialize(writer, msgObject)
End Using
Dim msgJson_3 As String = stringWriter.ToString()
End Sub
with none of the three options works, it always results in
{
"Emoji": "\\uD83D\\uDE00"
}
The result I need is
{
"Emoji": "\uD83D\uDE00"
}
How do I set Newtonsoft to not take into account the backslash character, as an escaped character?
Another unorthodox way could be:
jsonString = jsonString.replace("\\","\")
I do not really like
Thanks!!!!
\ is an escape char in JSON hence if you try and serialise a \ it gets escaped as \\ then when you deserialise \\ you get \
My guess is you have been given an example asking you to send "Emoji": "\uD83D\uDE00"
In json (and C#) \u#### specifies a unicode character (usually for something not found on a keyboard) as you are using VB.NET instead you should use $"{ChrW(&HD83D)}{ChrW(&HDE00)}"
"jsonString = jsonString.replace("//","/") " will never work, this is more safe way
json = json.Replace("\\\\u","\\u");
or since you don't like old, good classical solutions
json = Regex.Replace(json, #"\\u", #"u");
//or
json = json.Replace(#"\\u", #"\u");
even this will work in your case ( but I will not recommend for another cases since it is not safe)
json = Regex.Unescape(json);

VB.NET String.Format FormatException was unhandled

I want to generate a json string but
What did I do is wrong? Why to this code throws an An unhandled exception
Public Function GenerateJsonString(doer As Integer, comment As String, id As Integer) As String
Dim jsonString As String = String.Format("{done_by:{0}, comment:{1}, request_id:{2}}", doer, comment, id)
Return jsonString
End Function
An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll
Additional information: Input string was not in a correct format.
The bracket { is a special character in string.format so you need to use two brackets if you want them in the output like so:
Dim jsonString As String = String.Format("{{done_by:{0}, comment:{1}, request_id:{2}}}", 806, "comment", 16233)
It outputs
{done_by:806, comment:comment, request_id:16233}
Which is not valid json since it's missing the "-characters. So to correct that you could do
Dim jsonString As String = String.Format("{{""done_by"":{0}, ""comment"":""{1}"", ""request_id"":{2}}}", 806, "comment", 16233)
Note that comment is string and also needs the "-characters in value.
Output is correct json:
{"done_by":806, "comment":"comment", "request_id":16233}
There is also easier and more robust way to do this by serialization:
Dim serializer As New System.Web.Script.Serialization.JavaScriptSerializer
Dim jsonString As String = serializer.Serialize(New With {.done_by = 806, .comment = "comment", .request_id = 16233})
If you have class library or windows -project it needs System.Web.Extensions reference to your project.
Good luck!
The issue is the fact that you have braces in your literal text. When calling String.Format, braces are used to indicate place-holders but you have an opening brace at the beginning of the text and a closing brace at the end. If you want those literal braces included then you must escape them, i.e.
"{{done_by:{0}, comment:{1}, request_id:{2}}}"

Select everything from //

I'm making like a "mini programming language" in visual basic.
Mostly just for practice and for fun.
I just have one problem. I want to make a commenting system.
I got an idea how it would work, but i don't know how to do it.
So this is what i want to do:
I want to start to select all text from //
So for example, if i write:
print = "Hello World!"; //This is a comment!
it will select everything from the // so it will select
//This is a comment!
Then i would just replace the selected text with nothing.
You can use String.IndexOf + Substring:
Dim code = "Dim print = ""Hello World!""; //This is a comment!"
Dim indexOfComment = code.IndexOf("//")
Dim comment As String = Nothing
If indexOfComment >= 0 Then comment = code.Substring(indexOfComment)
If you want the part before the comment dont use String.Replace but also Substring or Remove:
code.Substring(0, indexOfComment)

Translation of c# linq to vb - overload resolution failure in intellisense with 'selectmany' statement

I've tried every translation service under the sun to get this syntax right but I still get "Overload resolution failed because no accessible 'SelectMany' can be called with these arguments"
on the first part of the select statement (up to the full stop just before the groupby keyword)
the original c# statement from an online example I'm trying to get working locally:
public IEnumerable<TagGroup> GetTagGroups()
{
var tagGroups =
// extract the delimited tags string and session id from all sessions
DbSet.Select(s => new { s.Tags, s.Id })
.ToArray() // we'll process them in memory.
// split the "Tags" string into individual tags
// and flatten into {tag, id} pairs
.SelectMany(
s =>
s.Tags.Split(_tagDelimiter, StringSplitOptions.RemoveEmptyEntries)
.Select(t => new { Tag = t, s.Id })
)
// group {tag, id} by tag into unique {tag, [session-id-array]}
.GroupBy(g => g.Tag, data => data.Id)
// project the group into TagGroup instances
// ensuring that ids array in each array are unique
.Select(tg => new TagGroup
{
Tag = tg.Key,
Ids = tg.Distinct().ToArray(),
})
.OrderBy(tg => tg.Tag);
return tagGroups;
}
The closest I've come to it in VB:
Public Function GetTagGroups() As IEnumerable(Of TagGroup)
' extract the delimited tags string and session id from all sessions
' we'll process them in memory.
' split the "Tags" string into individual tags
' and flatten into {tag, id} pairs
' group {tag, id} by tag into unique {tag, [session-id-array]}
' project the group into TagGroup instances
' ensuring that ids array in each array are unique
Dim tagGroups = DbSet.[Select](Function(s) New With { _
s.Tags, _
s.Id _
}).ToArray().SelectMany(Function(s) s.Tags.Split(_tagDelimiter, StringSplitOptions.RemoveEmptyEntries).[Select](Function(t) New With { _
Key .Tag = t, _
s.Id _
})).GroupBy(Function(g) g.Tag, Function(data) data.Id).[Select](Function(tg) New With { _
Key .Tag = tg.Key, _
Key .Ids = tg.Distinct().ToArray() _
}).OrderBy(Function(tg) tg.Tag)
Return tagGroups
End Function
This results in the visual studio 2012 intellisense underlining in blue the first part of the statement from "DbSet" on the first line through to the last parenthesis before the ".GroupBy" near the bottom. The error is "Overload resolution failed because no accessible 'SelectMany' can be called with these arguments".
As it's a code example I'm trying to convert to vb to run locally and understand and I'm not experienced enough with linq I'm completely at a loss of how to try and deal with this. It's way beyond my current understanding so could be a simple syntax error or a complete hash from start to finish for all I know!
Would be very grateful for any pointers.
I have now put this in VS2k8, and as well as the two simple issues with the VB sample I previously noted:
The first two New With constructs must specify .<field> = AFAIK, and
the last New With should not be anonymous.
I now also note these are the declarations I needed to get the code to not have errors. Other than adding intermediate query variables (which BTW mean you could thread the C# comments back in), I don't recall actually changing the code further. Note the _tagDelimiter as a Char() -- what did the C# code declare it as? (Looking at the String.Split overloads that mention StringSplitOptions it has to be Char() or String() or C# is implicitly changing types somewhere that VB.NET doesn't.)
Class TagList
Public Tags As String
Public Id As String
End Class
Private DbSet As IQueryable(Of TagList)
Class TagGroup
Public Tag As String
Public Ids() As String
End Class
Private _tagDelimiter As Char()
Public Function GetTagGroups() As IEnumerable(Of TagGroup)
Dim theTags = DbSet.[Select](Function(s) New With { _
.Tags = s.Tags, _
.Id = s.Id _
}).ToArray()
Dim many = theTags.SelectMany(Function(s) s.Tags.Split(_tagDelimiter, StringSplitOptions.RemoveEmptyEntries).[Select](Function(t) New With { _
Key .Tag = t, _
.Id = s.Id _
}))
Dim grouped = many.GroupBy(Function(g) g.Tag, Function(data) data.Id)
Dim unordered = grouped.[Select](Function(tg) New TagGroup With { _
.Tag = tg.Key, _
.Ids = tg.Distinct().ToArray() _
})
Dim tagGroups = unordered.OrderBy(Function(tg) tg.Tag)
Return tagGroups
End Function

Problem while sending JSON DATA

I have to pass my Json data in a particular format.
My app is coded in vb.
The following is my code :
Dim jsonObject As New Json.JsonObject
jsonObject.Item("count") = New Json.JsonNumber("0")
jsonObject.Item("data") = New Json.JsonArray("")
**jsonObject.Item("success") = New Json.JsonString("True")**
The Problem lies in the line :
jsonObject.Item("success") = New Json.JsonString("True") .
The error message being shown is " Type 'Jayrock.Json.JsonString' has no constructors."
Just to add i have imported the associated libraries .
What should I do to tackle this problem ??
Try simply like this:
Dim jsonObject As New Json.JsonObject
jsonObject.Item("count") = 0
jsonObject.Item("data") = New Json.JsonArray()
jsonObject.Item("success") = "True"
In other words, you can use primitive types like string and integer as values.