UWP epPlus - choose directory to save - vb.net

I am making an application in vb using UWP and epPlus along with it to save the current database to an excel file. I would create a pop up dialog box that will allow the client to select the directory they want to save the excel file to. There isn't a "Savefiledialog" in UWP... Ideas?
UPDATE
I tried to use FileSavePicker: if I save it in the principal directory (C:\, Desktop, Documents ...) epPlus doesn't work, but if I save it in another directory (D:\, USB...) it workes... How can I save it in the principal directory?
I post my code here:
Private Async Sub ButtonXls_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
OutputTextBlock.Text = ""
Dim savePicker As FileSavePicker = New FileSavePicker()
savePicker.SuggestedStartLocation = PickerLocationId.Desktop
savePicker.FileTypeChoices.Add("Microsoft Excel", New List(Of String)() From {
".xlsx"
})
savePicker.SuggestedFileName = "Riepilogo_Test"
Dim file As StorageFile = Await savePicker.PickSaveFileAsync()
If file IsNot Nothing Then
CachedFileManager.DeferUpdates(file)
Dim ExcelPkg As ExcelPackage = New ExcelPackage()
Dim wsSheet1 As ExcelWorksheet = ExcelPkg.Workbook.Worksheets.Add("Sheet1")
Using Rng As ExcelRange = wsSheet1.Cells(2, 2, 2, 2)
Rng.Value = "Text file on Excel here"
Rng.Style.Font.Size = 16
Rng.Style.Font.Bold = True
Rng.Style.Font.Italic = True
End Using
wsSheet1.Protection.IsProtected = False
wsSheet1.Protection.AllowSelectLockedCells = False
Dim filePath As FileInfo = New FileInfo(file.Path)
ExcelPkg.SaveAs(filePath)
Dim status As FileUpdateStatus = Await CachedFileManager.CompleteUpdatesAsync(file)
If status = FileUpdateStatus.Complete Then
OutputTextBlock.Text = "File " & file.Name & " was saved."
ElseIf status = FileUpdateStatus.CompleteAndRenamed Then
OutputTextBlock.Text = "File " & file.Name & " was renamed and saved."
Else
OutputTextBlock.Text = "File " & file.Name & " couldn't be saved."
End If
Else
OutputTextBlock.Text = "Operation cancelled."
End If
End Sub

Related

Google Drive API v3 VB.NET Upload To Spesific Folder

Please Help, i'm trying to upload file to specific folder in my google drive using Vb.net. but, i'm googling for hours and not get working code. i cant sleep because this. here is my code:
Private Sub UploadFile(FilePath As String)
Try
If Service.ApplicationName <> "Google Drive VB Dot Net" Then CreateService()
Dim TheFile As New File()
TheFile.Name = "Database Sekretariat.accdb"
TheFile.Description = "A test document"
'TheFile.MimeType = "text/plain"
TheFile.Parents(0) = "1uMeTMRtvhm5_98udPmV8kp19aGtrmeQj"
Dim ByteArray As Byte() = System.IO.File.ReadAllBytes(FilePath)
Dim Stream As New System.IO.MemoryStream(ByteArray)
Dim UploadRequest As FilesResource.CreateMediaUpload = Service.Files.Create(TheFile, Stream, TheFile.MimeType)
UploadRequest.Upload()
Dim file As File = UploadRequest.ResponseBody
MsgBox("Upload Selesai " & file.Name & "")
Catch ex As Exception
MsgBox("Upload Gagal")
End Try
End Sub
use it in the following way, it is functional
First, i look for the ID folder
Public Sub SearchFolder()
IDFolderSave = String.Empty 'Global Variable
Try
Dim findrequest As FilesResource.ListRequest = Service.Files.List
Dim listFolder As Data.FileList = findrequest.Execute
For Each item As File In listFolder.Files
If item.MimeType = "application/vnd.google-apps.folder" Then
If item.Name = "NameFolder" Then
IDFolderSave = item.Id.ToString
Exit For
End If
End If
Next
Catch ex As Exception
Throw ex
End Try
'MsgBox("Folder id: " + idFolder)
End Sub
Second, upload file
Public Sub UploadFileInFolder()
Dim FilePath As String = String.Empty
FilePath = "C:\Icons\Loadding.gif"
Dim plist As List(Of String) = New List(Of String)
SearchFolder()
plist.Add(IDFolderSave) 'Set parent folder
If (System.IO.File.Exists(FilePath)) Then
Dim fileMetadata = New File() With {
.Name = "Test",
.Parents = plist
}
Dim request As FilesResource.CreateMediaUpload
Using stream = New System.IO.FileStream(FilePath, System.IO.FileMode.Open)
request = Service.Files.Create(fileMetadata, stream, "application/octet-stream")
request.Fields = "id, parents"
request.Upload()
End Using
Dim file As File = request.ResponseBody
IDFileShared = file.Id
SharedFile()
MsgBox("File upload: " + file.Id)
Else
MsgBox("File does not exist: " + FilePath)
End If
End Sub
I hope it helps you

Needs to get default program association on remote computers

I am using the below code to get some information on remote computers. Basically, I need to get the OS version (which is working well) and the default program for .pdf files and the default browser. I can get the OS version but the code fails to get the default program association. The Remote Registry is enabled and started but even though I am getting an "access is denied" error message. Any clue guys? Hope you could help me. Thanks
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Const HKEY_LOCAL_MACHINE As String = "80000002"
Const HKEY_current_user1 As String = "80000001"
'Dim remoteRegistryController As New System.ServiceProcess.ServiceController("RemoteRegistry", computerNameTB.Text)
'remoteRegistryController.Start()
Dim osName, pdf, browser As String
Dim options As New ConnectionOptions
options.Impersonation = ImpersonationLevel.Impersonate
options.EnablePrivileges = True
options.Username = "hd_juann"
options.Password = "Diosteamo42="
Dim myScope As New ManagementScope("\\" & computerNameTB.Text & "\root\default", options)
Dim mypath As New ManagementPath("StdRegProv")
Dim mc As New ManagementClass(myScope, mypath, Nothing)
Try
Dim inParams As ManagementBaseObject = mc.GetMethodParameters("GetDWORDValue")
inParams("hDefKey") = UInt32.Parse(HKEY_LOCAL_MACHINE, System.Globalization.NumberStyles.HexNumber) 'RegistryHive.LocalMachine
inParams("sSubKeyName") = "Software\Microsoft\Windows NT\currentVersion"
inParams("sValueName") = "ProductName"
'Dim osName As String
Dim outParams As ManagementBaseObject = mc.InvokeMethod("GetStringValue", inParams, Nothing)
If (outParams("ReturnValue").ToString() = "0") Then
'MessageBox.Show(outParams("sValue").ToString())
osName = outParams("sValue").ToString()
Else
MessageBox.Show("Error retrieving value : " + outParams("ReturnValue").ToString())
End If
'get pdf
Dim inParamsPDF As ManagementBaseObject = mc.GetMethodParameters("GetDWORDValue")
inParamsPDF("hDefKey") = UInt32.Parse(HKEY_current_user1, System.Globalization.NumberStyles.HexNumber) 'RegistryHive.LocalMachine
inParamsPDF("sSubKeyName") = "Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.pdf\UserChoice"
inParamsPDF("sValueName") = "ProgId"
'Dim pdf As String
Dim outParamsPDF As ManagementBaseObject = mc.InvokeMethod("GetStringValue", inParamsPDF, Nothing)
If (outParamsPDF("ReturnValue").ToString() = "0") Then
pdf = outParamsPDF("sValue").ToString()
Else
pdf = "No value Set"
End If
'MessageBox.Show(pdf)
'remoteRegistryController.Stop()
'get browser
Dim inParamsBrowser As ManagementBaseObject = mc.GetMethodParameters("GetDWORDValue")
inParamsBrowser("hDefKey") = UInt32.Parse(HKEY_current_user1, System.Globalization.NumberStyles.HexNumber) 'RegistryHive.LocalMachine
inParamsBrowser("sSubKeyName") = "SOFTWARE\Microsoft\Windows\Shell\Associations\URLAssociations\https\UserChoice"
inParamsBrowser("sValueName") = "ProgId"
'Dim browser As String
Dim outParamsBrowser As ManagementBaseObject = mc.InvokeMethod("GetStringValue", inParamsBrowser, Nothing)
If (outParamsBrowser("ReturnValue").ToString() = "0") Then
browser = outParamsBrowser("sValue").ToString()
Else
browser = "No value Set"
End If
MsgBox(osName & " is installed on computer " & computerNameTB.Text & vbCrLf & "PDF Default App: " & pdf & vbCrLf & "Default Browser: " & browser,, "ComputerInfo W10 Upgrade Project")
Catch err As Exception
If osName <> "" Then
MsgBox(osName & " is installed on computer: " & computerNameTB.Text & ". No default program association information could be accessed " & err.Message,, "ComputerInfo W10 Upgrade Project")
Else
MsgBox("It was no possible to query computer: " & computerNameTB.Text,, "ComputerInfo W10 Upgrade Project")
End If
'MsgBox("It was no possible to query computer: " & computerNameTB.Text,, "ComputerInfo W10 Upgrade Project")
End Try
End Sub
eoor

How to search for files and attach them to a Email

I have an CheckedListbox (imported from mysql Database) that lists all my folders where my files are saved. And what I need to do is for every checked item in the CheckListbox, to search the folder and then attach the file from that folder to a Mail.
What I have done is to create an Email and to send it with only one attachment.
Just with the: "e_mail. Attachments. Add". The Mail will be generated and that found file will be attached and send.
But when I do that in a FOR EACH LOOP then no file will be selected and added to my Mail. The Mail will be generated and send without any errors, but there are no attached files.
Private Sub SendMail()
Dim Smtp_Server As New SmtpClient
Dim e_mail As New MailMessage()
Smtp_Server.UseDefaultCredentials = False
Smtp_Server.Credentials = New Net.NetworkCredential("MAIL", "PASS")
Smtp_Server.Port = 587
Smtp_Server.EnableSsl = True
Smtp_Server.DeliveryMethod = SmtpDeliveryMethod.Network
Smtp_Server.Host = "HOST"
If MonthTextBox.Text = "" Or MonthTextBox.ForeColor = Color.Silver Then
MsgBox("Input month please", Title:="MO Text Box")
Else
Dim MOTextValue As String = MonthTextBox.Text
Dim nowYear As Integer = Date.Now.Year
For Each itemchecked As DataRowView In CheckedListBoxWO.CheckedItems
Dim File_path As String = "C:\Test\" & itemchecked.Item(1) & "\" & nowYear & "\" & MOTextValue & "\"
Dim File_Name As String = Dir("C:\Test\" & itemchecked.Item(1) & "\" & nowYear & "\" & MOTextValue & "\File " & MOTextValue & "*.xlsx")
Dim attachmentFile As Net.Mail.Attachment = New Net.Mail.Attachment(File_path & File_Name)
e_mail.Attachments.Add(attachmentFile)
Next
Dim sb As New System.Text.StringBuilder
sb.AppendLine("Hello,<br />")
sb.AppendLine("<br />")
sb.AppendLine("Test Attachment,<br />")
sb.AppendLine("<br />")
sb.AppendLine("------------------------------------------<br />")
e_mail.From = New MailAddress("MY MAIL")
e_mail.To.Add("EMAIL")
e_mail.Subject = ("TESTFILE - " & MOTextValue & "")
e_mail.SubjectEncoding = System.Text.Encoding.UTF8
e_mail.IsBodyHtml = True
e_mail.Priority = MailPriority.Normal
e_mail.Body = sb.ToString()
e_mail.BodyEncoding = System.Text.Encoding.UTF8
Smtp_Server.Send(e_mail)
End If
MsgBox("Mails was sent", Title:="Mail")
End Sub
Like I told with this code the Mail will be created and send, but there is no Attachment file in it.
If I do it without the "FOR EACH"... loop, then one File will be added without a problem. But I need to add more files, actually for every checked Item in the CheckedListBox my program should search that folder and if there is a file than attach it in the Mail, and look in the other folder and so on...
Your adding attachments then newing up your e_mail object again, this will wipe your existing data, try removing the indicated line below:
sb.AppendLine("<br />")
sb.AppendLine("------------------------------------------<br />")
e_mail = New MailMessage() <--- remove this line
e_mail.From = New MailAddress("MY MAIL")
e_mail.To.Add("EMAIL")
The code is actually working, my problem was that the reference to this CheckListBox was incorrect, I have multiple CheckListBoxes, and that one in the Code was not the one I was actually using... But looking it from the bright side, THE CODE IS WORKING :)

Search For ID number In TextFile vb.net

This is what i need to do, I click on the openfile button and brings up the openfile dialog box. I open a textfile and it gets displayed in the informationbox.text field, at the same time i would like to search that file for an ID number and display it in the IDbox.text field.
i have searched other forums, but they just use the Replace method or other methods that i don't know about. It becomes too confusing.
This is what i have so far -
Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click
Dim oReader As StreamReader
OpenFileDialog1.CheckFileExists = True
OpenFileDialog1.CheckPathExists = True
OpenFileDialog1.DefaultExt = "txt"
OpenFileDialog1.FileName = ""
OpenFileDialog1.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
OpenFileDialog1.Multiselect = False
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
oReader = New StreamReader(OpenFileDialog1.FileName, True)
InformationBox.Text = oReader.ReadToEnd
My.Forms.Home.TextBox5.AppendText(Environment.NewLine & "Opened Customer : " & OpenFileDialog1.FileName & " File")
oReader.Close()
End If
IDBox.Text = ""
Label11.Text = OpenFileDialog1.FileName
End Sub
example of textfile :
Name of customer : Name
Surname of customer :Surname
ID number : 12345678910
Record number : 001
Address of Customer : Address
Can anyone help me please?
In your example code you use StreamReader to read the text file.
The "drawback" of Streams is that you have to manage their disposing manually.
In your example, if an error occurs in oReader.ReadToEnd the line oReader.Close will not be hit and the Stream might remain undisposed thus causing trouble.
So you´d better enclosure your Stream in a Using scope (another option would be to use static System.IO.File.ReadAllLines|ReadAllText methods).
Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click
'Dim oReader As StreamReader <-- DELETE THIS
OpenFileDialog1.CheckFileExists = True
OpenFileDialog1.CheckPathExists = True
OpenFileDialog1.DefaultExt = "txt"
OpenFileDialog1.FileName = ""
OpenFileDialog1.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
OpenFileDialog1.Multiselect = False
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
'MY CODE STARTS HERE:
Dim customerInfo As String
Using sr = New StreamReader(OpenFileDialog1.FileName, True)
customerInfo = sr.ReadToEnd()
End Using 'Close the stream early since we have all data needed
'Write all lines into a string array
Dim lines As String() = customerInfo.Split({Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
'Get the line where the ID Number is in
Dim idLine As String = lines.Where(Function(l) l.StartsWith("ID number")).FirstOrDefault()
Dim id As String = String.Empty
If Not String.IsNullOrEmpty(idLine) Then
Dim aIdLine() = idLine.Split(":"c) 'Split the ID line by :
If aIdLine.Length >= 1 Then
id = aIdLine(1) 'This should be the actual ID
End If
End If
'Set UI
My.Forms.Home.TextBox5.AppendText(Environment.NewLine & "Opened Customer : " & OpenFileDialog1.FileName & " File")
InformationBox.Text = customerInfo
IDBox.Text = id
Label11.Text = OpenFileDialog1.FileName
End If

VB.net Could not find directory

This is the full code.
http://pastebin.com/cx9Tk0n3
I'm having a problem that, after downloading the mod, all works perfectly, the RAR file is located into the document folder while the extraxted content (#Mod) is under LauncherArma under Documents folder.
While clicking on the button to install the mod, starting from line 184, I've this error:
Private Sub FlatButton6_Click(sender As Object, e As EventArgs) Handles FlatButton6.Click
If My.Computer.FileSystem.DirectoryExists(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) & "\LauncherArma") Then
My.Computer.FileSystem.DeleteDirectory(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) & "\LauncherArma", FileIO.DeleteDirectoryOption.DeleteAllContents)
End If
If My.Computer.FileSystem.FileExists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\LauncherArma\modsname.txt") Then
My.Computer.FileSystem.DeleteFile(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\LauncherArma\modsname.txt")
End If
My.Computer.FileSystem.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) & "\LauncherArma")
UnRar(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) & "\Addon.rar", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) & "\LauncherArma")
Dim ligne As String
My.Computer.Network.DownloadFile("FTP ADDRESS. Hidden for security. Don't worry, the download files works!/modsname.txt", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\LauncherArma\modsname.txt")
Dim sr As New StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\LauncherArma\modsname.txt")
While sr.Peek <> -1
ligne = sr.ReadLine()
My.Computer.FileSystem.CopyDirectory(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) & "\LauncherArma\" & ligne, directory & "\" & ligne, True)
End While
PictureBox1.Visible = True
FlatButton6.Visible = False
FlatProgressBar1.Visible = False
FlatLabel1.Visible = False
FlatLabel2.Visible = False
FlatLabel3.Visible = False
End Sub
I don't know how to solve this problem.
Waiting your reply!
Regards