• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2389
  • Last Modified:

Winforms VB.NET save images in Azure Blob

Been hunting a while.... seems to be loads in C# however need VB.NET,

need a simple method to save an image into Azure blob storage from a WinForms application

all documentation I see says about making a connection in the data connections etc, but this looks like it is for Web only

please help
0
Acusu
Asked:
Acusu
2 Solutions
 
Kalpesh ChhatralaSoftware ConsultantCommented:
Hi,

you can store Image file in SQL Server like below.

    Public Sub Store2Sql(ByVal img As Image)

        'for sql server
        Dim conn As SqlConnection = New SqlConnection()
        conn.ConnectionString = "Your SQL Server Connection String"

        'for SQL 
        Dim sql As String = "insert into MyTable values(1,@imgData)"
        Dim command1 As SqlCommand = New SqlCommand(sql, conn)
        Dim sqlpara As New SqlParameter("imgData", SqlDbType.Image)

        Dim mStream As MemoryStream = New MemoryStream()
        img.Save(mStream, ImageFormat.Jpeg)
        sqlpara.SqlValue = mStream.GetBuffer

        command1.Parameters.Add(sqlpara)
        conn.Open()
        command1.ExecuteNonQuery()
        conn.Close()
    End Sub

    Public Function LoadFromSql(ByVal id As Integer) As Image
        'for sql server
        Dim conn As SqlConnection = New SqlConnection()
        conn.ConnectionString = "Your SQL Server Connection String"

        'for SQL 
        Dim sql As String = "select blobfield from MyTable where id = " & id
        Dim command1 As SqlCommand = New SqlCommand(sql, conn)
        conn.Open()
        Dim reader As SqlDataReader = command1.ExecuteReader
        reader.Read()
        Dim bitPic() As Byte = CType(reader.GetValue(0), Byte())

        conn.Close()
        Dim mStream As MemoryStream = New MemoryStream(bitPic)
        Dim img As Image = Image.FromStream(mStream)

        Return img

    End Function

Open in new window

0
 
CodeCruiserCommented:
Let me introduce you to a good free tool

http://converter.telerik.com/

Using this tool, I converted the code from

http://blogs.msdn.com/b/sqlazure/archive/2010/06/17/streaming-blobs-to-and-from-sql-azure.aspx

as below

Read Image:
Using sqlConnection As New SqlConnection("Server=tcp:yourServer.database.windows.net;" + "Database=AdventureWorksLTAZ2008R2;" + "User ID=yourLogin@yourServer;Password=yourPassword;" + "Trusted_Connection=False;Encrypt=True;")
	sqlConnection.Open()

	Using sqlStream As New SqlStream(sqlConnection, "SalesLT", "Product", "ThumbNailPhoto", "ProductID", SqlDbType.Int, _
		884)
		Dim buffer As [Byte]() = New [Byte](1023) {}
		Dim read As Int32 = 0

		Using binaryReader As New BinaryReader(sqlStream)
			Using fileStream As New FileStream("c:\temp\image.jpg", FileMode.Create)
				Using binaryWriter As New BinaryWriter(fileStream)
					Do
						read = binaryReader.Read(buffer, 0, 1024)
						binaryWriter.Write(buffer, 0, read)
					Loop While read > 0
				End Using
			End Using
		End Using
	End Using
End Using

Open in new window



Write Image:
Using sqlConnection As New SqlConnection("Server=tcp:yourServer.database.windows.net;" + "Database=AdventureWorksLTAZ2008R2;" + "User ID=yourLogin@yourServer;Password=yourPassword;" + "Trusted_Connection=False;Encrypt=True;")
	sqlConnection.Open()

	Using sqlStream As New SqlStream(sqlConnection, "SalesLT", "Product", "ThumbNailPhoto", "ProductID", SqlDbType.Int, _
		884)
		Dim buffer As [Byte]() = New [Byte](1023) {}
		Dim read As Int32 = 0

		Using binaryWriter As New BinaryWriter(sqlStream)
			Using fileStream As New FileStream("c:\temp\image.jpg", FileMode.Open)
				Using binaryReader As New BinaryReader(fileStream)
					Do
						read = binaryReader.Read(buffer, 0, 1024)
						binaryWriter.Write(buffer, 0, read)
					Loop While read > 0
				End Using
			End Using
		End Using
	End Using
End Using

Open in new window

0
 
AcusuAuthor Commented:
Apologies, I mean to upload images into Blob Storage not into SQL Database, I have my container and provate key, I just need to work out a VB.NET winforms easy put/get
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
Kalpesh ChhatralaSoftware ConsultantCommented:
0
 
AcusuAuthor Commented:
Thanks for that Kalpesh, but this is for Websites, in WinForms the connection string does not work in the same way.

If anyone has a simple few lines of code with simply the connection string pre filled it would be great, (VB.NET of course)
0
 
Éric MoreauSenior .Net ConsultantCommented:
I just created a Windows Forms project, I have added the WindowsAzure.Storage nuget package and used this code:

Imports Microsoft.WindowsAzure.Storage.Blob
Imports Microsoft.WindowsAzure.Storage

Public Class Form1

    Private Sub button1_Click(sender As Object, e As EventArgs) Handles button1.Click
        Dim cs As String = "DefaultEndpointsProtocol=https;AccountName=YourAccountName;AccountKey=YourAccountKey"
        Dim storageAccount As CloudStorageAccount = CloudStorageAccount.Parse(cs)
        Dim blobClient As CloudBlobClient = storageAccount.CreateCloudBlobClient()

        '// Retrieve reference to a previously created container.
        Dim container As CloudBlobContainer = blobClient.GetContainerReference("TheNameOfYourContainer")

        '// Loop over items within the container and output the length and URI.
        For Each item As IListBlobItem In container.ListBlobs(Nothing, False)
            'else if (item.GetType() == typeof(CloudPageBlob))
            If TypeOf item Is CloudPageBlob Then
                Dim pageBlob As CloudPageBlob = DirectCast(item, CloudPageBlob)
                Trace.WriteLine(String.Format("Page blob of length {0}: {1}", pageBlob.Properties.Length, pageBlob.Uri))
            End If
        Next
    End Sub
End Class
0
 
AcusuAuthor Commented:
Thanks all for your help, between you both: Kalpesh & Eric I got there in the end :)

Here is the final lump, (upload and download example)
 Dim cs As String = "DefaultEndpointsProtocol=https;AccountName=AccountName;AccountKey=GHJKGHJKGHJKGHJKGHJKGHJGHJKGHJKGHJK=="
        Dim storageAccount As CloudStorageAccount = CloudStorageAccount.Parse(cs)
        Dim blobClient As CloudBlobClient = storageAccount.CreateCloudBlobClient()


        'UPLOAD FILE TO BLOB
        Dim container As CloudBlobContainer = blobClient.GetContainerReference("microbore-tradeinvoices")
        ' Retrieve reference to a blob named "myblob".
        Dim NewBlob As CloudBlockBlob = container.GetBlockBlobReference("FileNameUploading.html")
        ' Create or overwrite the "myblob" blob with contents from a local file.
        Using fileStream = System.IO.File.OpenRead("C:\UploadFolder\temp.html")
            NewBlob.UploadFromStream(fileStream)
        End Using



        'DOWNLOAD FILE FROM SERVER
        Dim NewBlob2 As CloudBlockBlob = container.GetBlockBlobReference("10838-03-04-2014--19-12-32.pdf")
        NewBlob2.DownloadToFile("c:\Folder\LocalFilename.pdf", IO.FileMode.CreateNew)
0
 
AcusuAuthor Commented:
Thanks again to you both :)
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now