FilePath as a URL, Visual Basic Desktop App - vb.net

I am using the code below to bind data from a XML file in my PC. It works fine when using a local PC filePath, but when I change the location of the XML filePath to an URL which is listed below. it simply doesn't work. I made this xml file public in my onedrive but still doen´t work. Do I need to download the file and then readXML?
Many Thanks,
Imports System
Imports System.IO
Imports System.Net
Imports System.Xml
Public Class NasgoLive
Private Sub RefreshButton_Click(sender As Object, e As EventArgs) Handles RefreshButton.Click, RefreshButton.Click
MessageBox.Show("Done")
Me.BackColor = Color.FloralWhite
Dim filePath As String = "Complete path where you saved the XML"
AuthorsDataSet.ReadXml("https://onedrive.live.com/? cid=42FE4354E1EDA2AE&id=42FE4354E1EDA2AE%21674")
alliancehorizonvalue.DataSource = AuthorsDataSet
alliancehorizonvalue.DataMember = "alliancehorizon"
arcticovalue.DataSource = AuthorsDataSet
arcticovalue.DataMember = "arctico"

You need to download the file first. DataSet.ReadXml supports just a file name, not url.
You could download the file with a WebClient (not tested):
byte[] data;
using (WebClient client = new WebClient()) {
data = client.DownloadData("https://onedrive.live.com/?cid=42FE4354E1EDA2AE&id=42FE4354E1EDA2AE!674");
}
File.WriteAllBytes(#"c:\myfile.xml", data);
EDIT:
For downloading you need to use OneDrive API

Related

Cannot get CefSharp Chromium web brower to work on target PC

I have a Windows VB application developed in Visual Studio 2013 that incorporates a CefSharp Chromium web browser (version 86.0.241 using the NuGet packages). Target CPU is set to x86, the build output path is set to bin\x86\debug, Configuration is set to Active (debug) and the Platform is set to Active (x86). The web browser works great on the development machine, but when I deploy the app to the target machine (which is a server), the browser displays a blank screen and freezes.
The CefSharp support files are included in the deployment package (InnoSetup), but I'm confused on which version of VC++ redistributables I need to deploy.The CefSharp FAQ's state that with versions 65.0.0 and above, the minimum of VC++2015 needs to be deployed. I had the client install this version on the target machine (when I originally deployed this app, I did not include the VC++ redistributables), but the browser still does not work. Do I need to deploy a different version?
Any other ideas on what I'm doing wrong? Please help!
Larry
Here is a link to the .zip file containing the CEF debug.log files from the client's three servers (the three servers rotate based on demand):
https://www.dropbox.com/s/b3zjxxk79v9xl9b/DataMinerDebugLogs.zip?dl=0
Please let me know if any of these provides the reason why the Chromium browser is displaying only a blank page.
Thanks.
Details of the log entry mentioned in my last comment:
[1228/093028.760:INFO:CONSOLE(32)] "Refused to connect to 'https://collection.decibelinsight.net/i/13878/265573/c.json' because it violates the following Content Security Policy directive: "connect-src https://qbonline.api.intuit.net https://cdn.decibelinsight.net https://api.segment.io 'self' https://.intuit.com https://.intuit.com:* https://.intuitcdn.net: https://hosted-shell-assets-us-west-2.s3.us-west-2.amazonaws.com wss://plugin-localhost.intuitcdn.net:* wss://plugin.intuitcdn.net:* https://.intuit.net wss://.msg.liveperson.net/ws_api/account/ https://*.objectstorage.liveperson.net/ https://scripts.neuro-id.com https://api.neuro-id.com https://logs.neuro-id.com".
", source: https://cdn.decibelinsight.net/i/13878/265573/di.js (32)
Code from Auth Class (the form that opens and displays the Chromium browser):
Imports Intuit.Ipp.OAuth2PlatformClient
Imports System.Net
Imports System.IO
Imports System.Web
Imports CefSharp
Imports CefSharp.WinForms
Public Class Auth
Public WithEvents Browser As ChromiumWebBrowser
Dim Settings As New CefSettings
Private Sub Auth_Load(sender As Object, e As EventArgs) Handles MyBase.Load
oauthClient = New OAuth2Client(ClientID, ClientSecret, RedirectURL, "production")
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
Dim scopes As List(Of OidcScopes) = New List(Of OidcScopes)()
scopes.Add(OidcScopes.Accounting)
authorizeURL = oauthClient.GetAuthorizationURL(scopes)
Settings.CefCommandLineArgs.Add("disable-gpu")
Browser = New ChromiumWebBrowser(authorizeURL)
Me.Controls.Add(Browser)
Browser.Dock = DockStyle.Fill
End Sub
Private Sub Browser_AddressChanged(sender As Object, e As AddressChangedEventArgs) Handles Browser.AddressChanged
Dim Str As String = Browser.Address
If InStr(Str, "&realmID", CompareMethod.Text) Then
Dim q = HttpUtility.ParseQueryString(Browser.Address)
Dim Code As String = ""
Dim RealmID As String = ""
For Each key In q.Keys
If InStr(key, "code") Then
Code = q.Item(key)
ElseIf InStr(key, "realmId", CompareMethod.Text) Then
RealmID = q.Item(key)
End If
Next
Call GetAuthTokens(Code, RealmID)
End If
End Sub
End Class
The "Address_Changed" event can be ignored and the first 5 lines of the "Load" event all relate to another SDK used in the app, none of which is related to the Chromium browser.
Startup code added:
Shared Sub Main()
'This sub executes first.
Dim Settings As New CefSettings
Settings.CefCommandLineArgs.Add("disable-gpu")
cef.initialize(Settings)
Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(False)
Application.Run(New MainMenu)
End Sub

SSIS VB.Net Script to download a file using a proxy

I am trying to write a VB.Net script to download a file from the web in a SSIS dtsx package.
I started from this, but I am having only proxy authentication errors (error 407).
I double checked the proxy, the port and the URL an they are right!
Can anyone help me please? I can't understand where the problem could be.
' Microsoft SQL Server Integration Services Script Task
' Write scripts using Microsoft Visual Basic
' The ScriptMain class is the entry point of the Script Task.
Imports System
Imports System.Data
Imports System.Math
Imports Microsoft.SqlServer.Dts.Runtime
Imports System.Net
Public Class ScriptMain
Public Sub Main()
Dim objWebClient As WebClient = New WebClient()
Dim objCache As New CredentialCache()
Dim strDownloadURL As String = "http://www.example.com/data.xlsx"
Dim strProxyURL As String = "myproxy.mycompany.local"
Dim intProxyPort As Integer = 1234
'Set Proxy & Credentials as a Network Domain User acc to get through the Proxy
Dim wp As WebProxy = New WebProxy(strProxyURL, intProxyPort)
objWebClient.Proxy = wp
'Download file, use Flat File Connectionstring to save the file
objWebClient.DownloadFile(strDownloadURL, "E:\MyFile.xlsx")
Dts.TaskResult = Dts.Results.Success
End Sub
End Class
The file of strDownloadURL is accessible by browser and doesn't need any form of authentication. Anyone can access it by a web browser.

Missing Carriage Return in Downloaded Email Attachment ImapX

Here is my code:
#Region "Imports"
Imports System.Text.RegularExpressions
Imports System.Text
Imports Microsoft.VisualBasic.CallType
Imports ImapX
Imports System.Runtime.CompilerServices
Imports System.Security.Authentication
Imports System.IO
Imports ml = System.Net.Mail
Imports System.Net
Imports ImapX.Enums
Imports ImapX.Constants
Imports System.Security.Authentication.SslProtocols
#End Region
Module Module1
Sub Main()
Dim _messages As List(Of ImapX.Message)
Using MyImapClient = New ImapX.ImapClient
With MyImapClient
.Host = ImapServer
.Port = Port
.SslProtocol = Ssl3 Or Tls
.ValidateServerCertificate = True
.Credentials = New ImapX.Authentication.PlainCredentials(UserName, Password)
Dim IsConnected As Boolean = .Connect
.Login()
.Behavior.AutoDownloadBodyOnAccess = False
.Behavior.AutoPopulateFolderMessages = False
.Behavior.MessageFetchMode = MessageFetchMode.Full
.Behavior.ExamineFolders = False
.Behavior.RequestedHeaders = {MessageHeader.From, MessageHeader.[Date], MessageHeader.Subject, MessageHeader.ContentType, MessageHeader.Importance}
'Dim IsInboxSelected As Boolean = .SelectFolder(.Folders.Inbox.Name)
'Dim IsInboxSelected As Boolean = .Folders(.Folders.Inbox.Name).[Select]()
End With
Dim MyFolder As Folder = MyImapClient.Folders.Inbox
_messages = MyFolder.Search().OrderBy(Function(n) n.[Date]).ToList()
_messages.ForEach(Sub(n) n.Download(MessageFetchMode.Full))
_messages.ForEach(Sub(n) n.Download(MessageFetchMode.Full))
End Using
Dim MyAttachment As ImapX.Attachment = _messages.First.Attachments.First
MyAttachment.Download()
Dim FolderPath As String = "C:\Users\AAA\Downloads\"
Dim LocalFileName As String = "1212.txt"
MyAttachment.Save(FolderPath, LocalFileName)
End Sub
End Module
The code works without issue--it connects to the imap server, downloads the first attachment of the first email, which happens to be a .txt file, so I'm saving it as such.
The problem is that the contents of the file is prepended with " * 2 FETCH (" and is followed by " UID 45", and all carriage returns are removed from the file.
Can you please assist? Thanks,
My guess is the CRLF's ( Carriage Return Line Feeds ) are not the format whatever you're viewing the download in is looking for. I would look at your attachment using something like NotePad++ and make sure you're showing Carriage Returns. If all you see are cr's and you're viewing the file in something looking for crlf's then they will get ignored.
Another thing to look at is what default encoding is your .download call using and what encoding is the original attachment in.

Zip and unzip files

I am a programmer using VS2012. I am wanting to unzip a zip file (made with Winzip, filzip or other zip compression routines) and then also be able to zip the files back up into a zip file.
What is the best library to use for this and can I please have some sample code on how to use the library?
EDIT
I am using VB.net, here is my code:
Public Function extractZipArchive() As Boolean
Dim zipPath As String = "c:\example\start.zip"
Dim extractPath As String = "c:\example\extract"
Using archive As ZipArchive = ZipFile.OpenRead(zipPath)
For Each entry As ZipArchiveEntry In archive.Entries
If entry.FullName.EndsWith(".txt", StringComparison.OrdinalIgnoreCase) Then
entry.ExtractToFile(Path.Combine(extractPath, entry.FullName))
End If
Next
End Using
End Function
What import statements do I need to use?
Currently I have added the following:
Imports System.IO
Imports System.IO.Compression
I am getting the error:
Type 'ZipArchive' is not defined
How can I fix this error?
If you're using Visual Studio 2012 and the .NET Framework 4.5 you can use the new compression library:
//This stores the path where the file should be unzipped to,
//including any subfolders that the file was originally in.
string fileUnzipFullPath;
//This is the full name of the destination file including
//the path
string fileUnzipFullName;
//Opens the zip file up to be read
using (ZipArchive archive = ZipFile.OpenRead(zipName))
{
//Loops through each file in the zip file
foreach (ZipArchiveEntry file in archive.Entries)
{
//Outputs relevant file information to the console
Console.WriteLine("File Name: {0}", file.Name);
Console.WriteLine("File Size: {0} bytes", file.Length);
Console.WriteLine("Compression Ratio: {0}", ((double)file.CompressedLength / file.Length).ToString("0.0%"));
//Identifies the destination file name and path
fileUnzipFullName = Path.Combine(dirToUnzipTo, file.FullName);
//Extracts the files to the output folder in a safer manner
if (!System.IO.File.Exists(fileUnzipFullName))
{
//Calculates what the new full path for the unzipped file should be
fileUnzipFullPath = Path.GetDirectoryName(fileUnzipFullName);
//Creates the directory (if it doesn't exist) for the new path
Directory.CreateDirectory(fileUnzipFullPath);
//Extracts the file to (potentially new) path
file.ExtractToFile(fileUnzipFullName);
}
}
}
Unanswered, although a while ago, so I'll still put my $0.02 in there for anyone else who hits this on keywords...
VB 2012 (.Net 4.5) added new features to System.IO.Compression (System.IO.Compression.FileSystem.dll) that will do what you want. We only had GZip before. You can still use the free DotNetZip or SharpZipLib, of course.
The ZipFile class has 2 static methods that make simple compression/decompression drop-dead simple: CreateFromDirectory and ExtractToDirectory. Yo also have compression choices of NoCompression, Fastest, and Optimal.
One thing about it that struck me about your post was the concept of files (even archives) within archives. With the ZipArchive and ZipArchiveEntry classes you can now
ZipArchive:
Using zippedFile as ZipArchive = ZipFile.Open("foo.zip", ZipArchiveMode.Read)
For Each ntry as ZipArchiveEntry In zippedFile.Entries
Debug.Writeline("entry " & ntry.FullName & " is only " & ntry.CompressedLength.ToString)
Next
End Using
Your question also was about adding to an existing archive. You can now do that like this:
Using zippedFile as ZipArchive = ZipFile.Open("foo.zip", ZipArchiveMode.Update)
zippedFile.createEntry("bar.txt", CompressionLevel.Fastest)
' likewise you can get an entry already in there...
Dim ntry As ZipArchiveEntry = zippedFile.GetEntry("wtf.doc")
' even delete an entry without need to decompress & compress again!
ntry.Delete() ' !
End Using
Again, this was a while ago, but a lot of us still use 2012, and as this change won't be going anywhere in future versions, it should still prove helpful moving forward if anyone hits in on a keyword/tag search...
...and we didn't even talk about UTF-8 support!
You probably aren't referencing System.IO.Compression. Check the box for that assembly reference and it should eliminate the error.
As mentioned in https://msdn.microsoft.com/en-us/library/system.io.compression.zipfile(v=vs.110).aspx
You can use ZipFile.ExtractToDirectory and CreateFromDirectory
This is the example:
Imports System.IO
Imports System.IO.Compression
Module Module1
Sub Main()
Dim startPath As String = "c:\example\start"
Dim zipPath As String = "c:\example\result.zip"
Dim extractPath As String = "c:\example\extract"
ZipFile.CreateFromDirectory(startPath, zipPath)
ZipFile.ExtractToDirectory(zipPath, extractPath)
End Sub
End Module
Make sure you have referenced System.IO.Compression.FileSystem for using this function.
Dim fileStream As Stream = File.OpenRead("your file path")
Using zipToOpen As FileStream = New FileStream(".......\My.zip", FileMode.CreateNew)
Using archive As ZipArchive = New ZipArchive(zipToOpen, ZipArchiveMode.Create)
Dim readmeEntry As ZipArchiveEntry = archive.CreateEntry("your file path")
fileStream.CopyTo(readmeEntry.Open())
End Using
End Using

Save user-defined object into Windows Registry using VB.NET

I need to save created object into Windows Registry and after reopening application to read it? I know how to save and read string but this is complex object.
Any idea?
You maybe want to use a XmlSerializer (or other serializers). It's easy to use, and the documentation is full of examples.
But why storing it in the registry?
Better use Application Settings and User Settings.
EDIT:
Instead of the registry, save your object to a file in the ApplicationData directory of the user. You can get the path to this directory with
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
Full example:
Imports System.IO
Imports System.Xml.Serialization
Module Module1
Public Class MySuperClass
Public Property MyString() As String
Public Property MyInt() As Int32
End Class
Public Sub Main(ByVal args() As String)
Dim myFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MyApplication")
If Not Directory.Exists(myFolder) Then
Directory.CreateDirectory(myFolder)
End If
Dim myFile = Path.Combine(myFolder, "MySettings.txt")
Dim o = New MySuperClass With {.MyString = "Hi!", .MyInt = 42}
Dim x = New XmlSerializer(GetType(MySuperClass))
Using sr = New StreamWriter(myFile)
' Save directly to file
x.Serialize(sr, o)
End Using
' for demonstrating purpose
o = Nothing
Using sr = New StreamReader(myFile)
' Load directly from file
o = CType(x.Deserialize(sr), MySuperClass)
End Using
End Sub
End Module