Updating Vb.net deprecated code - vb.net

I am new to vb this is the code i am working on:
Dim InputDoc As XmlDocument = New XmlDocument()
InputDoc.LoadXml(tem)
Dim Transformer As XslCompiledTransform = New XslCompiledTransform()
Transformer.Load(Server.MapPath("D/" & T))
Dim xmlCtl As System.Web.UI.WebControls.Xml = New System.Web.UI.WebControls.Xml
xmlCtl.Document = InputDoc
xmlCtl.Transform = Transformer
Controls.Add(xmlCtl)
I changed XslTranform to XslCompiledTranform - is this right thing to do?
But i am still getting few other errors as xmlCtl.Document is obselete and value of xmlCtl.Transform cannot be converted to Transformer. I am using .Net 4.0 . Can anybody please tell me how to resolve these?

I changed XslTranform to XslCompiledTranform - is this right thing to do?
As to this post yes that is the right thing to do.
Apparently there is an issue with memory leakage when transforming large documents. So i guess be wary of that.
But i am still getting few other errors as xmlCtl.Document is obselete and value of xmlCtl.Transform cannot be converted to Transformer
This would be right if you were not going to have XSLT transformations.
Dim xmlCtl As System.Web.UI.WebControls.Xml = New System.Web.UI.WebControls.Xml
But you want to use XSLT, so that will not work.
Create an XPathDocument and call CreateNavigator()
Use XPathNavigator to execute an XSLT transformation.
This post talks about working with xml web controls and xslt.
You may want to take a look at this as well.
This uses XslCompiledTransform and is supposed to be a replacement of the ASP.NET Xml control. Will work with integrating XSLCompiledTransform
Anyways i hoped some of this helped.

Related

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.

WriteStartElement using an Array value

I have created a XML document using visual basic in visual studio 2010.
it seems its not letting me use array values when i write a start element.
arrayValue = array(UBound(array))
Dim xw As XmlWriter = XmlWriter.Create("xmlfile.xml", xws)
xw.WriteStartDocument()
xw.WriteStartElement(arrayValue)
xw.WriteEndElement()
xw.WriteEndDocument()
xw.Flush()
xw.Close()
Wont let me do that it gives me an error and also does nothing.
"A first chance exception of type 'System.ArgumentException' occurred in System.Xml.dll"
Whats going on?
You could try using the XMLTextWriter.
arrayValue = array(UBound(array))
Dim xWriter As New Xml.XmlTextWriter("C:\Users\Admin\Desktop\mytest.xml", System.Text.Encoding.UTF8)
xWriter.Formatting = Formatting.Indented
xWriter.Indentation = 2
xWriter.WriteStartDocument(True)
xWriter.WriteStartElement(arrayValue)
xWriter.WriteEndElement()
xWriter.Flush()
xWriter.Close()
A few of my arrayValue values were not coming out as xml standard. There happen to be a lot of them.
Some started with numbers (which you cannot have as nodenames). That is why it wasn't writing to the document. I have to write a filter to change the values into XML standard.
I wish visual studio would of told me this in an error message or something. Thanks for all of your help.

Error on retrieving RSS Feed (vb.net project)

So, i'm developing a project on vb.net to manage rss feeds and if they have a file attached it downloads automatically the files to a folder. I know something about vb.net but in Xml i'm having my first steps.
I already managed to properly download content from links with this code i found online:
Dim webReq As HttpWebRequest = DirectCast(WebRequest.Create(tsCboFeeds.Text), HttpWebRequest)
webReq.AutomaticDecompression = DecompressionMethods.GZip
Dim resp As HttpWebResponse = DirectCast(webReq.GetResponse(), HttpWebResponse)
Dim xml As String
Using sr As New StreamReader(resp.GetResponseStream())
xml = sr.ReadToEnd()
End Using
doc.LoadXml(xml)
It works great for 99% of the feeds i found, the only problem are the ones that have the download url in an enclosure tag, like this example (the link is the url of the post, not the to the file):
<channel>
<title>...</title>
<link>...</link>
<description>...</description>
<item>
<title>...</title>
<description>...</description>
<category>...</category>
<author>...</author>
<link...</link>
<pubDate>...</pubDate>
<enclosure url="http:..." />
</item>
When i try to use
Dim nodesLink As XPathNodeIterator = navigator.Select("/rss/channel/item/enclosure_url")
i dont get the information inside the tag, it gives me back the whole xml doc.
As i mentioned i dont understand that much of Xml, but by now i tried a number of solutions i found online, even changing the method of getting the file, but mainly because of enconding problems this method has been the best for my project.
Any ideas?
I think that the problem is that your xpath expression is wrong. In the Xml i see an element called and not an element called .
You could try this:
Dim nodesLink As XPathNodeIterator = navigator.Select("/rss/channel/item/enclosure")
nodesLink.Attributes("url")

How to convert certain C# code to VB.NET

I've been googling around around and read this article
C# How to get SQL Server installation path programatically?
and this is exactly what i need in VB.NET , however i'm not good in translating this code into VB.NET Code. So, any help would greatly appreciated. Thank you.
Note : I'm using SQL Server 2005 and Visual Basic 2008
While the question was originally titled about retrieving SQL Server's installation path, I felt it was more about a code translation problem (the solution already existed, just not in the right language).
But then I thought that the method in the original code was fairly blunt.
Evan provided you with what I assume is a workable translation of the existing solution. But probably a much easier way to perform this specific task - assuming you just need to find the installation path for an instance you're already connected to, and assuming that a user who can read the registry will also have VIEW SERVER STATE permissions - is to issue this simple query against the DMV sys.dm_os_loaded_modules from your program:
SELECT name
FROM sys.dm_os_loaded_modules
WHERE name LIKE '%sqlservr.exe';
This will give you something like this:
C:\Program Files\Microsoft SQL Server\MSSQL11.SQL2012\MSSQL\Binn\sqlservr.exe
You have some parsing to do, depending on exactly what you're after (e.g. do you want to stop at MSSQL, or Binn?), but this is much easier than reading the registry or other methods that are out there IMHO.
I just used a code converter ... There are only basic things that need to be changed ..
Using sqlServerKey As RegistryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Microsoft SQL Server")
For Each subKeyName As String In sqlServerKey.GetSubKeyNames()
If subKeyName.StartsWith("MSSQL.") Then
Using instanceKey As RegistryKey = sqlServerKey.OpenSubKey(subKeyName)
Dim instanceName As String = instanceKey.GetValue("").ToString()
If instanceName = "MSSQLSERVER" Then
'say
Dim path__1 As String = instanceKey.OpenSubKey("Setup").GetValue("SQLBinRoot").ToString()
path__1 = Path.Combine(path__1, "sqlserver.exe")
Return path__1
End If
End Using
End If
Next
End Using
If you were to just read a quick article on C#, you would notice that strings are declared differently, and minor syntax discrepancies exist such as foreach vs for each
You can read here for some more common differences.
I use a very good (offline) tool, called Convert .NET Free
It's from www.fishcodelib.com
Here's a direct link to the latest release (as of 19/04/14) Size: 2.06MB, File: Zip :
[Direct Link]
Hope this is of some use ;)
P.S. This software requires .NET Framework 4.5.
This almost never fails! :) Good Luck
http://www.developerfusion.com/tools/convert/csharp-to-vb/

Using System.Reflection and resources in Phalanger

I need to embed some resource in a pure compiled dll written in php using phalanger.
These are txt files tha I set in visual studio as "Embedded Resource".
My problem is that I cannot use the Assembly class to get the resource using GetManifestResourceStream.
I tried code like this:
use System\Reflection\Assembly
$asm = Assembly::GetExecutingAssembly(); //this gives me mscorlib instead of my dll
$str = $asm->GetManifestResourceStream("name");
My question is: how do I get access to embedded resources in phalanger?
Many thanks
I'm not sure, why Assembly::GetExecutingAssembly() returns an incorrect value. Anyway to workaround the $asm value, use following code:
$MyType = CLRTypeOf MyProgram;
$asm = $MyType->Assembly;
Then you can access embedded resources as you posted
$asm->GetManifestResourceStream("TextFile1.txt");
or you can include standard resource file (.resx) into your project, and use \System\Resources\ResourceManager
$this->manager = new \System\Resources\ResourceManager("",$asm);
$this->manager->GetObject("String1",null);
Just note, currently there can be just one .resx within Phalanger project
This question is old, but the part of the Phalanger code (Php.Core.Emit.AddResourceFile() method) responsible for this hasn't changed since this was asked. I faced the same problem and solved it in (almost) non-hacky way. You have to provide alternative name (/res:/path/to/filename,alternative-name) for this to work though.
$asm = clr_typeof('self')->Assembly;
$resourceStream = $asm->GetManifestResourceStream("filename");
$reader = new \System\Resources\ResourceReader($resourceStream);
$type = $data = null;
$reader->GetResourceData("alternative-name", $type, $data);
// and still there are 4 excess bytes
// representing the length of the resource
$data = \substr($data, 4);
$stream = new IO\MemoryStream($data);
// after this $stream is usable as you would expect
Straightforward GetManifestResourceStream() (as suggested by Jakub) does not work because Phalanger does not use System.Reflection.Emit.ModuleBuilder.DefineManifestResource() (like I think it should when supplied with unrecognized file format). It uses ModuleBuilder.DefineResource() which returns ResourceWriter instead, that only really suited for .resources files. And this is what dictates the requirement to use ResourceReader when you need to read your resource.
Note: This answer applies to Phalanger master branch at the time of writing and prior versions since circa 2011. Noted because it looks like a bug (especially the need to use both original and alternative names).