Solved

Winforms VB.NET save images in Azure Blob

Posted on 2014-03-31
8
2,014 Views
Last Modified: 2014-11-12
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
Comment
Question by:Acusu
8 Comments
 
LVL 16

Expert Comment

by:Kalpesh Chhatrala
ID: 39968690
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
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 39969873
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
 

Author Comment

by:Acusu
ID: 39970193
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
 
LVL 16

Assisted Solution

by:Kalpesh Chhatrala
Kalpesh Chhatrala earned 150 total points
ID: 39970209
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 

Author Comment

by:Acusu
ID: 39975966
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
 
LVL 69

Accepted Solution

by:
Éric Moreau earned 150 total points
ID: 39976095
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
 

Author Comment

by:Acusu
ID: 39976222
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
 

Author Closing Comment

by:Acusu
ID: 39976227
Thanks again to you both :)
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Companies keep a much closer eye on costs today, so changing to new Technology – Microsoft Office 365 is the smartest move to take.
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

914 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now