Solved

Winforms VB.NET save images in Azure Blob

Posted on 2014-03-31
8
2,189 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

 
LVL 16

Assisted Solution

by:Kalpesh Chhatrala
Kalpesh Chhatrala earned 150 total points
ID: 39970209
0
 

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 70

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

Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

Question has a verified solution.

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

The following article is comprised of the pearls we have garnered deploying virtualization solutions since Virtual Server 2005 and subsequent 2008 RTM+ Hyper-V in standalone and clustered environments.
This article shows the steps required to install WordPress on Azure. Web Apps, Mobile Apps, API Apps, or Functions, in Azure all these run in an App Service plan. WordPress is no exception and requires an App Service Plan and Database to install
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…
In this video, viewers are given an introduction to using the Windows 10 Snipping Tool, how to quickly locate it when it's needed and also how make it always available with a single click of a mouse button, by pinning it to the Desktop Task Bar. Int…

717 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