Solved

Winforms VB.NET save images in Azure Blob

Posted on 2014-03-31
8
1,977 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
0
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 

Author Comment

by:Acusu
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Thanks again to you both :)
0

Featured Post

Backup Your Microsoft Windows Server®

Backup all your Microsoft Windows Server – on-premises, in remote locations, in private and hybrid clouds. Your entire Windows Server will be backed up in one easy step with patented, block-level disk imaging. We achieve RTOs (recovery time objectives) as low as 15 seconds.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Expando 4 33
Clone Visual studio 2013 solution 5 15
Setting runtime form location 4 18
Calling stored proc in EDMX 11 17
Monitoring systems evolution, cloud technology benefits and cloud cost calculators business utility.
Disabling the Directory Sync Service Account in Office 365 will stop directory synchronization from working.
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…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

763 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

6 Experts available now in Live!

Get 1:1 Help Now