Email attachment Drag and Drop to C drive - vb.net

I am trying to add drag and drop functionality to my form so that I can drag an attachment from an email and it will save the attachment.
I get an error saying Required Privileges not held by client. I want to get around this.
Here is my code:
If e.Data.GetDataPresent("FileGroupDescriptor") Then
Dim theStream As Stream = DirectCast(e.Data.GetData("FileGroupDescriptor"), Stream)
Dim fileGroupDescriptor As Byte() = New Byte(511) {}
theStream.Read(fileGroupDescriptor, 0, 512)
Dim fileName As New StringBuilder("")
Dim i As Integer = 76
While fileGroupDescriptor(i) <> 0
fileName.Append(Convert.ToChar(fileGroupDescriptor(i)))
i += 1
End While
theStream.Close()
Dim theFile As String = "c:\" + fileName.ToString() 'change the c:\ to any path you want
Dim ms As MemoryStream = DirectCast(e.Data.GetData("FileContents", True), MemoryStream)
Dim fileBytes As Byte() = New Byte(ms.Length - 1) {}
ms.Position = 0
ms.Read(fileBytes, 0, CInt(ms.Length))
Dim fs As New FileStream(theFile, FileMode.OpenOrCreate)
fs.Write(fileBytes, 0, CInt(fileBytes.Length))
fs.Close()
End If

You most certainly do not have permissions to write to c:\.
I suggest writing to your desktop or somewhere using the My.Computer.FileSystem.SpecialDirectories object:-
Dim theFile As String = IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.Desktop, filename.ToString)
Check this article out for all the options available to you: https://msdn.microsoft.com/en-us/library/microsoft.visualbasic.fileio.specialdirectories.aspx

Related

How to convert encoding of FTP Getlisting array of strings?

I am using the following vb code to get the list of files in a ftp directory and populate a database table with it to be used in another integration process. Please forgive my bad bad programming skills (I am not a vb.net developer).
Public Sub Main()
Dim StrFolderArrary As String() = Nothing
Dim StrFileArray As String() = Nothing
Dim fileName As String
Dim RemotePath As String
RemotePath = Dts.Variables("User::FTPFullPath").Value.ToString()
Dim ADODBConnection As SqlClient.SqlConnection
ADODBConnection = DirectCast(Dts.Connections("DB_Connection").AcquireConnection(Dts.Transaction), SqlClient.SqlConnection)
Dim cm As ConnectionManager = Dts.Connections("FTP_Connection") 'FTP connection manager name
Dim ftp As FtpClientConnection = New FtpClientConnection(cm.AcquireConnection(Nothing))
ftp.Connect() 'Connecting to FTP Server
ftp.SetWorkingDirectory(RemotePath) 'Provide the Directory on which you are working on FTP Server
ftp.GetListing(StrFolderArrary, StrFileArray) 'Get all the files and Folders List
'If there is no file in the folder, strFile Arry will contain nothing, so close the connection.
If StrFileArray Is Nothing Then
ftp.Close()
'If Files are there, Loop through the StrFileArray arrary and insert into table
Else
For Each fileName In StrFileArray
'MessageBox.Show(fileName)
Dim SQLCommandText As String
SQLCommandText = "INSERT INTO dbo._FTPFileList ([DirName],[FileName]) VALUES (N'" + RemotePath + "', N'" + fileName + "')"
'MessageBox.Show(SQLCommandText)
Dim cmdDatabase As SqlCommand = New SqlCommand(SQLCommandText, ADODBConnection)
cmdDatabase.ExecuteNonQuery()
Next
ftp.Close()
End If
' Add your code here
'
Dts.TaskResult = ScriptResults.Success
End Sub
It works fine and I get the results in the database table. The problem is that the encoding of the strings coming from FTP makes the file names with accentuation to be written incorrectly as shown in the example below.
database table
The correct file name is Razão and I know that the db collation is correct since it can be written like this.
So I tried to convert the strings using this code for each file name in the string array but without any success.
For Each fileName In StrFileArray
Dim utf8 As UTF8Encoding = New UTF8Encoding(True, True)
Dim bytes As Byte() = New Byte(utf8.GetByteCount(fileName) + utf8.GetPreamble().Length - 1) {}
Array.Copy(utf8.GetPreamble(), bytes, utf8.GetPreamble().Length)
utf8.GetBytes(fileName, 0, fileName.Length, bytes, utf8.GetPreamble().Length)
Dim fileName2 As String = utf8.GetString(bytes, 0, bytes.Length)
I believe it is coming with different encoding from the FTP side so I would like to know how to convert the strings during the GetListing method.
Or do you have any ideas how to deal with this?
Thanks in advance.
edit:
I also tried the following code without success.
Dim utf8 As Encoding = Encoding.UTF8
Dim w1252 As Encoding = Encoding.GetEncoding(1252)
Dim w1252Bytes As Byte() = w1252.GetBytes(fileName)
Dim utf8Bytes As Byte() = Encoding.Convert(w1252, utf8, w1252Bytes)
Dim utf8Chars As Char() = New Char(utf8.GetCharCount(utf8Bytes, 0, utf8Bytes.Length) - 1) {}
utf8.GetChars(utf8Bytes, 0, utf8Bytes.Length, utf8Chars, 0)
Dim fileName2 As String = New String(utf8Chars)

add password in a pdf file using vb.net

i just want to ask how can i add a password on a existing PDF file, i just created a pdf file using crystal reports and i kinda need to add some security features for the report. Thank you very much in advance.
lets say the file "c:\Folder1\sample.pdf" already exist. i have seen codes like the one below, but i don't know if it works because i don't know what to add in my reference to make it work
' Define input and output files path.
Dim intputFilePath As String = Program.RootPath + "\\" + "1.pdf"
Dim outputFilePath As String = Program.RootPath + "\\" + "1_with_pw.pdf"
' Set passwords for user and owner.
Dim userPassword As String = "you"
Dim ownerPassword As String = "me"
' Create password setting.
Dim setting As PasswordSetting = New PasswordSetting(userPassword, ownerPassword)
' Add password to plain PDF file and output a new file.
Dim errorCode As Integer = PDFDocument.AddPassword(intputFilePath, outputFilePath, setting)
If errorCode = 0 Then
Console.WriteLine("Success")
Else
Console.WriteLine("Failed")
End If
Dim WorkingFolder As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
Dim InputFile As String = Path.Combine(WorkingFolder, "PSNOs.pdf")
Dim OutputFile As String = Path.Combine(WorkingFolder, "PSNOs_enc.pdf")
Using input As Stream = New FileStream(InputFile, FileMode.Open, FileAccess.Read, FileShare.Read)
Using output As Stream = New FileStream(OutputFile, FileMode.Create, FileAccess.Write, FileShare.None)
Dim reader As New PdfReader(input)
PdfEncryptor.Encrypt(reader, output, True, Nothing, "secret", PdfWriter.ALLOW_SCREENREADERS)
End Using
End Using
the word "PdfReader" have an error message but it doesn't ask to import something..

image in the SQL_database in vb.net

I have a problem to record the image in the SQL_database in vb.net.Enter as a file without a problem but I can not write in SQL.ABCreateNewBarcode is a PictureBox. I have a problem to take BackgroundImage from PictureBox to save in SQL. I save BackgroundImage in BarcodeImg folder but I can not save in SQl
Private Sub btnSaveBarcode_Click(sender As Object, e As EventArgs) Handles btnSaveBarcode.Click
'Create Image Object
Dim ABCreateNewBarcode As Object
ABCreateNewBarcode = CreateObject("BARCODE.BarcodeCtrl.1")
ABCreateNewBarcode.Text = txtNewBarcode.Text
ABCreateNewBarcode.typename = "Code128"
DirBarcodeImg = Application.StartupPath & "\barcodeimg"
'Save Image
If txtNewBarcode.Text = "" Then
MsgBox("Click the Create Button to create a New Barcode")
ElseIf Directory.Exists(DirBarcodeImg) = False Then
Call Directory.CreateDirectory(DirBarcodeImg)
Else
ABCreateNewBarcode.SaveAsBySize(DirBarcodeImg & "\" & txtInsertPartName.Text & ".png", 300, 130)
Dim ImageToSave As Image = ABCreateNewBarcode.BackgroundImage
Dim ms As New MemoryStream
ImageToSave.Save(ms, ImageToSave.RawFormat)
Dim buffer As Byte() = MS.GetBuffer()
'Add SQL Parameters
SQL.AddParam("#name", txtInsertPartName.Text)
SQL.AddParam("#image", buffer)
'Run Imsert Command
SQL.ExecQuery("INSERT INTRO information (PartName,BarcodeImg) " &
"VALUES (#name,#image) ")
End If
End Sub
After chaging you request "INTO" instead of "INTRO" try this line:
SQL.Parameters.AddWithValue("#image", txtInsertPartName.Text).SqlDbType = SqlDbType.Image
and replace :
Dim ms As New MemoryStream
ImageToSave.Save(ms, ImageToSave.RawFormat)
Dim buffer As Byte() = MS.GetBuffer()
by this:
Dim fs As FileStream
fs = New FileStream(imagename, FileMode.Open, FileAccess.Read)
'a byte array to read the image
Dim picbyte As Byte() = New Byte(fs.Length - 1) {}
fs.Read(picbyte, 0, System.Convert.ToInt32(fs.Length))
fs.Close()
'open the database using odp.net and insert the data
Dim buffer As Byte() =picbyte

automatically download a report

This is the code that i have made but now working to save the report to the directory:
As you see i follow pretty much a lot of microsoft tutorials of how use this class of reporting service, but still dont get how get it working
'objetos de reporting
Dim rs As New reportingservice.ReportingService2010
Dim rsExec As New ReportExecution.ReportExecutionService
rs.Credentials = System.Net.CredentialCache.DefaultCredentials
'datos generales
Dim historyID As String = Nothing
Dim deviceInfo As String = Nothing
Dim format As String = "PDF"
Dim results As Byte()
Dim encoding As String = String.Empty
Dim mimeType As String = String.Empty
Dim extension As String = String.Empty
Dim warnings As ReportExecution.Warning() = Nothing
Dim streamIDs As String() = Nothing
Dim filename As String = "C:/Users/gdedieu/Desktop/reporte.pdf" ' Change to where you want to save
Dim _reportName As String = "per_anexo_1"
Dim _historyID As String = Nothing
Dim _forRendering As Boolean = False
Dim _values As ReportExecution.ParameterValue() = Nothing
Dim _credentials As reportingservice.DataSourceCredentials() = Nothing
Dim ei As ReportExecution.ExecutionInfo = rsExec.LoadReport(_reportName, historyID)
'definimos el parámetro
_values(0).Name = "an1_id"
_values(0).Value = 1
rsExec.SetExecutionParameters(_values, "en-us")
results = rsExec.Render(format, deviceInfo, extension, mimeType, encoding, warnings, streamIDs)
Dim stream As New System.IO.FileStream(filename, IO.FileMode.OpenOrCreate)
stream.Write(results, 0, results.Length)
stream.Close()
Try setting up a subscription via the Report Manager and specifying the Report Delivery Options value for 'Delivered By:' as 'Report Server File Share'.
This lets you specify a path for a report file to be written to - you will need to ensure that the Reporting Services server has write access to the destination.

streamwriter in windows store app - write text to file in VB

Does anybody have VB code to emulate Streamwriter for Windows Store?
I know it's been replaced by StorageFolder class but there is no VB sample in MSDN and I can't seem to translate properly from c# examples. Any help would be appreciated. I am just trying to write text (CSV) to a file and save it to the documents folder. In the code below windows store want a stream instead of strPath when I try dim-ing a streamwriter. (been playing with pickerdialog too, but that might be the next hurdle).
Dim strpath As String = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary & "\" & strFileName
'Build String for file*******************
Dim swExport As StreamWriter = New StreamWriter(strpath)
swExport.Flush()
For x = 0 To intCount - 1
strLine = "WriteSomeText"
swExport.WriteLine(strLine)
Next x
Possibly the simplest approach would be to use a MemoryStream if you like StreamWriter, so something like:
Dim sessionData As New MemoryStream()
' TODO: stage data in sessionData
Dim swExport As StreamWriter = New StreamWriter(sessionData)
swExport.Flush()
For x = 0 To intCount - 1
strLine = "WriteSomeText"
swExport.WriteLine(strLine)
Next x
Dim file As StorageFile = await ApplicationData.Current.RoamingFolder.CreateFileAsync("towns.json", CreationCollisionOption.ReplaceExisting)
Using (fileStream As Stream = await file.OpenStreamForWriteAsync())
sessionData.Seek(0, SeekOrigin.Begin)
await sessionData.CopyToAsync(fileStream)
await fileStream.FlushAsync()
End Using
I was making it too difficult. To write to a file I just needed to use storagefolder and storagefile. I have also included the FileSavePicker in the code (note that filetypechoices is mandatory)
Private Async Function btnExport_Click(sender As Object, e As RoutedEventArgs) As Task
'Calls Filepicker to determine location
'Calls Sqlite to select ALL
'Creates CSV file to be saved at location chosen
'save to file
Dim intCount As Integer = "5"
Dim x As Integer
Dim strLine As String 'hold each line for export file
'Create FileName based on date
Dim strDate As String = Date.Today.ToString("MMddyyyy")
Dim strFileName As String = "Export" & strDate & ".csv"
' Configure save file dialog box
Dim dlgPicker As New Windows.Storage.Pickers.FileSavePicker
'add types for picker (manditory field)
Dim types = New List(Of String)
types.Add(".csv")
types.Add(".txt")
'set picker parameters
dlgPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Downloads
dlgPicker.SuggestedFileName = strFileName '"Document" '
dlgPicker.FileTypeChoices.Add("CSV/TXT", types) 'manditory
dlgPicker.DefaultFileExtension = ".csv" 'Filter files by extension
dlgPicker.CommitButtonText = "Save"
' Show save file dialog box
Dim SaveCSV = Await dlgPicker.PickSaveFileAsync()
'************************get data************
Dim sbExport As Text.StringBuilder = New Text.StringBuilder
sbExport.AppendLine(strHeader)
For x = 0 To intCount - 1
strLine = "Get the text you want to write here"
sbExport.AppendLine(strLine)
Next x
'************************************
'write data to file
Await FileIO.WriteTextAsync(SaveCSV, sbExport.ToString)
Dim mb As MessageDialog = New MessageDialog("Done")
Await mb.ShowAsync()
End Function