How to Set the URL property of a Web Browser control to a String - webbrowser-control

I'm using a Web Browser control in C# and I'd like to be able to plug in different URLs depending on other things that have happened in the program. How can I set the URL property to a string in the code? Can I convert a string to the System.Uri type?
string link;
string searchedtitle = "The+Italian+Job";
link = "http://www.imdb.com/find?s=all&q=" + searchedtitle + "&x=0y=0";
WbBrowser.Url = link; // This is what I don't know how to do
Something to that effect would be ideal, where I could change 'searchedtitle' within the program somewhere else and still have it run properly. Unfortunately, the Url property is of type System.Uri, and I only have a System.String.

WbBrowser.Url is of type Uri so you need to use
WbBrowser.Url = new Uri(link);

Note that setting the URL is exactly the same as calling the Navigate() function. Navigate takes a string as an argument as the URL, eliminating the step of converting your URL to a string.

Related

Quarkus: Using placeholders in #Path

With Spring MVC, it is possible to use placeholders with Path configurations. In #RequestMapping("${myapp.path}") the placeholder will be replaced with the myapp.path propert.
Is there an equivalent method for the #Path annotation in Quarkus? There the {myapp.path} part is interpreted to be a path parameter.
To prevent an X-Y Problem: I'm looking for a way to configure a path on application startup and looked towards the solution I've known from Spring.
So, after struggling for a bit, I found this solution. Tell me if it helped.
I used the brackets in the #Path annotation (in my interface class service).
Then I specified what my id parameter is by specifying it with the #PathParam annotation in my method.
#GET
#Path("api/{myId}")
#Produces(MediaType.APPLICATION_JSON)
public Response findArticlePriceById(#HeaderParam("header") String myheader, #PathParam("id") String myId, #QueryParam("name") String myName);
You can then just send that parameter as a string from where you call your method.
Response jsonResponse = myService.findArticlePriceById("my-header", "133", "my-name");
My GET request will be : localhost:8080/api/133?name=my-name
As it turns out, this is currently impossible. I've opened up an issue, so we'll see if it will be in the future.

Using a local image with EmbedBuilder

According to the Discord.NET documentation page for the EmbedBuilder class, the syntax (converted to VB) to add a local image to an EmbedBuilder object should look something like this:
Dim fileName = "image.png"
Dim embed = New EmbedBuilder() With {
.ImageUrl = $"attachment://{fileName}"
}.Build()
I'm trying to use something like this to add a dynamically created image to the EmbedBuilder, but I can't seem to get it to work properly. Here's basically what I've got:
Dim TweetBuilder As New Discord.EmbedBuilder
Dim DynamicImagePath As String = CreateDynamicImage()
Dim AttachURI As String = $"attachment:///" & DynamicImagePath.Replace("\", "/").Replace(" ", "%20")
With Builder
.Description = "SAMPLE DESCRIPTION"
.ImageUrl = AttachURI
End With
MyClient.GetGuild(ServerID).GetTextChannel(PostChannelID).SendMessageAsync("THIS IS A TEST", False, Builder.Build)
My CreateDynamicImage method returns the full path to the locally created image (e.g., C:\Folder\Another Folder\image.png). I've done a fair amount of "fighting"/testing with this to get past the Url must be a well-formed URI exception I was initially getting because of the [SPACE] in the path.
MyClient is a Discord.WebSocket.SocketClient object set elsewhere.
The SendMessageAsync method does send the Embed to Discord on the correct channel, but without the embedded image.
If I instead send the image using the SendFileAsync method (like so):
MyClient.GetGuild(ServerID).GetTextChannel(PostChannelID).SendFileAsync(DynamicImagePath, "THIS IS A TEST", False, Builder.Build)
the image is sent, but as a part of the message, rather than included as a part of the Embed (this is expected behavior - I only bring it up b/c it was a part of my testing to ensure that there wasn't a problem with actually sending the image to Discord).
I've tried using the file:/// scheme instead of the attachment:/// scheme, but that results in the entire post never making it to Discord at all.
Additionally, I've tried setting the ImageUrl property to a Web resource (e.g., https://www.somesite.com/someimage.png) and the Embed looks exactly as expected with the image and everything when it successfully posts to Discord.
So, I'm just wondering at this point if I'm just missing something, or if I'm just doing it completely wrong?
I cross-posted this to issue #1609 in the Discord.Net GitHub project to get a better idea of what options are available for this and received a good explanation of the issue:
The Embed (and EmbedImage) objects don't do anything with files. They simply pass the URI as configured straight into Discord. Discord then expects a URI in the form attachment://filename.ext if you want to refer to an attached image.
What you need to do is use SendFileAsync with the embed. You have two options here:
Use SendFileAsync with the Stream stream, string filename overload. I think this makes it clear what you need to do: you provide a file stream (via File.OpenRead or similar) and a filename. The provided filename does not have to match any file on disk. > So, for example:
var embed = new EmbedBuilder()
.WithImageUrl("attachment://myimage.png")
.Build();
await channel.SendFileAsync(stream, "myimage.png", embed: embed);
Alternatively, you can use SendFileAsync with the string filePath overload. Internally, this gets a stream of the file at the path, and sets filename (as sent to Discord) to the last part of the path. So it's equivalent to:
using var stream = File.OpenRead(filePath);
var filename = Path.GetFileName(filePath);
await channel.SendFileAsync(stream, filename);
From here, you can see that if you want to use the string filePath overload, you need to set embed image URI to something like $"attachment://{Path.GetFileName(filePath)}", because the attachment filename must match the one sent to Discord.
I almost had it with my code above, but I misunderstood the intention and usage of the method and property. I guess I thought the .ImageUrl property somehow "automatically" initiated a Stream in the background. Additionally, I missed one very important piece:
As it's an async method, you must await (or whatever the VB.NET equivalent is) on SendFileAsync.
So, after making my calling method into an async method, my code now looks like this:
Private Async Sub TestMessageToDiscord()
Dim Builder As New Discord.EmbedBuilder
Dim AttachmentPath As String = CreateDynamicImage() '<-- Returns the full, local path to the created file
With Builder
.Description = "SAMPLE DESCRIPTION"
.ImageUrl = $"attachment://{IO.Path.GetFileName(AttachmentPath)}"
End With
Using AttachmentStream As IO.Stream = IO.File.OpenRead(AttachmentPath)
Await MyClient.GetGuild(ServerID).GetTextChannel(PostChannelID).SendFileAsync(AttachmentStream, IO.Path.GetFileName(AttachmentPath), "THIS IS A TEST", False, Builder.Build)
End Using
End Sub
Now, everything works exactly as expected and I didn't have to resort to uploading the image to a hosting site and using the new URL (I actually had that working before I got the response on GitHub. I'm sure that code won't go to waste).
EDIT
Okay, so I still ended up going back to my separately hosted image option for one reason: I have a separate event method that modifies the original Embed object during which I want to remove the image and replace the text. However, when that event fired, while the text was replaced, the image was "moved" to the body of the Discord message. While I may have been able to figure out how to get rid of the image entirely, I decided to "drop back and punt" since I had already worked out the hosted image solution.
I've tried everyting I could, but I got stuck at the same point at where you are now.
My guesses are that Discord doesn't like the embedded images from https://cdn.discordapp.com/attachments, and only accepts the new files from https://media.discordapp.net. I might be wrong though, this is the way it worked for me.
I believe it's only a visual glitch, as I found if you send a link for an image from cdn.discordapp.com/attchments in your regular Discord client, it bugs out and shows an empty embed for some reason.
That would make sense since the default link used in an embedded image actually starts with https://cdn.discordapp.com/attachments/...
You could solve this issue by using https://media.discordapp.net, but it seems like Discord.net is configured to use the old domain.

wcf rest appending escape characters to HTML tags

I am trying to convert an existing .Net shop site to an Android app.
(This is in VB)
One of the main objects holds product data.
Within that object there is, for instance:
<H2>Product Title</H2>
<P>A description</P>
I have already built a WCF Rest service which returns the data I expect:...
Having said that, I have trialled Newtonsoft.Json and DataContractJsonSerializer which produce the same, but different, outputs.
When running the WCF service in debug using Newtonsoft.Json it returns those items as I would expect:
Newtonsoft:
<H2>Product Title<\/H2><P>A description<\/P>
DataContractJsonSerializer:
<H2>Product Title<\\\/H2><P>A description<\\\/P>
However, when I run the Android app through Eclipse I get the error of "Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \ )"
So, in short; how to stop Newtonsoft or DataContractJsonSerializer from inserting these escape sequences?
Thanks
Dave
UPDATE:
I have tracked this down to something (?) that WCF is doing. Here is the final bit of my code which returns the JSON string:
retVal = CacheManager.JSONFullProduct("P" & ProductID)
At this point 'retVal' is storing closing HTML tags with just '/'
retVal = retVal.Replace("\/", "/")
At this point 'retVal' is still storing closing HTML tags with just '/'
Return retVal
At this point 'retVal' itself is still storing closing HTML tags with just '/', but when it actually returns (either to Notepad if I'm running the Service direct, or to Android) '/' suddenly becomes '{backslash}/'
I've tried to do a string replace in the android app:
result.replace("\/", "/");
But that returns the same error of "Invalid escape sequence...", and anyway, I don't really want to be doing this kind of work on the phone.
So, what is happening at Return retVal to suddenly insert all of these escape characters??
I have searched high and wide for an answer to this, and have finally found it.
I will share for anyone else experiencing the same issue:
It is the WCF Rest service.
Learning WCF and Android at the same time led me to believe that the response from WCF should be a String serialized in the Json format.
To do this, a .Net object, array or whatever would go through DataContractJsonSerializer before being returned as a String to Android for further parsing.
Something like this:
Dim stream1 As MemoryStream = New MemoryStream
Dim ser As DataContractJsonSerializer = New DataContractJsonSerializer(GetType(myType))
ser.WriteObject(stream1, myThing)
Dim _json As String = Encoding.UTF8.GetString(stream1.ToArray())
stream1.Close()
return _json
Wrong.
Keep your object, array or whatever and return that instead; WCF will take care of the proper escaping for you.
For example (this is VB);
IService:
<OperationContract()> _
<WebGet(BodyStyle:=WebMessageBodyStyle.WrappedRequest, RequestFormat:=WebMessageFormat.Json, ResponseFormat:=WebMessageFormat.Json, UriTemplate:="/MyKit/{AccountID}")> _
Function GetKit(ByVal AccountID As String) As MyKit
Service:
Public Function GetKit(ByVal AccountID As String) As MyKit Implements IService1.GetKit
Dim allKit As New MyKit() //Your object
objDal.CommandText = 'run some sql here - or whatever
Using dr As SqlDataReader = "blah"
//populate your object
End Using
Return allKit //return the object, not the string representation of it
End Function
Using DataContractJsonSerializer for sending as Json to Android from WCF effectively 'pre-escapes' the data. When it gets to Android, the Json parser is unable to handle it, because it also escapes the data.

Message Properties File

Is there a VB equivalent to org.springframework.context.support.ResourceBundleMessageSource package in java?
I am not focusing on Spring with this question. I want to know if there is a way to have a message properties file that I can pass variables like you can with hat java package.
Here is an example of what I would like to do.
In a properties file have the following line:
success.message = Successfully created document with Trans No. {0}
In source code have this line:
ResourceBundleMessageSource.getMessage("success.message",new String[] {transObject.getTransId()}, null));
This code uses the properties file finds success.message and passes the variable from getTransId().
I want to do this to centralize all my error messages. and not have hard coded messages throughout my code.
Is there some kind of equivalent in VB?
One solution is to use resource files. Add a resource by right clicking on the project and selecting project properties. Then click on resources, and add a new resource.
We work from the example in the question :
With resources we cannot follow the sam naming convention as you see above. We need to replace the '.' with a '_' ie: success.message -> success_message
Resource files do not allow the '.' in the key name.
Next we need to the message into the resource file.
"{0} successfully submitted the file."
We use {0}....{x} as place holders for variables.
The first line in the resource tab should look like this
success_message | {0} successfully submitted the file.
The function to do the replacing of the place holders should look like this:
Public Shared Function messageRetriver(ByVal message As String, ByVal variables As String()) As String
Dim i As Integer
Dim pattern As String
For i = 0 To variables.Length - 1
pattern = "\x7B" & i & "\x7D"
Dim myRegex As New Regex(pattern)
message = myRegex.Replace(message, variables(i))
Next
Return message
End Function
Now in your code all you have to do is call this function passing the resource, and the string array of variables.
Utility.messageRetriver(My.Resources.success_message, {"My Program"})
That should do the trick.
I used this as a resource to compile this information.

Getting Path (context root) to the Application in Restlet

I am needing to get the application root within a Restlet resource class (it extends ServerResource). My end goal is trying to return a full explicit path to another Resource.
I am currently using getRequest().getResourceRef().getPath() and this almost gets me what I need. This does not return the full URL (like http://example.com/app), it returns to me /resourceName. So two problems I'm having with that, one is it is missing the schema (the http or https part) and server name, the other is it does not return where the application has been mounted to.
So given a person resource at 'http://dev.example.com/app_name/person', I would like to find a way to get back 'http://dev.example.com/app_name'.
I am using Restlet 2.0 RC3 and deploying it to GAE.
It looks like getRequest().getRootRef().toString() gives me what I want. I tried using a combination of method calls of getRequest().getRootRef() (like getPath or getRelativePart) but either they gave me something I didn't want or null.
Just get the base url from service context, then share it with the resources and add resource path if needed.
MyServlet.init():
String contextPath = getServletContext().getContextPath();
getApplication().getContext().getAttributes().put("contextPath", contextPath);
MyResource:
String contextPath = getContext().getAttributes().get("contextPath");
request.getRootRef() or request.getHostRef()?
The servlet's context is accessible from the restlet's application:
org.restlet.Application app = org.restlet.Application.getCurrent();
javax.servlet.ServletContext ctx = ((javax.servlet.ServletContext) app.getContext().getAttributes().get("org.restlet.ext.servlet.ServletContext"));
String path = ctx.getResource("").toString();