Solved

Winforms VB.NET save images in Azure Blob

Posted on 2014-03-31
8
2,050 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
Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

 
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

NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
.net and XML report from SCCM 5 23
Javascript to set controls visibility 5 34
Accelerate Windows Explorer network searches 1 33
VB.NET 2008 - SQL Timeout 9 24
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
Or at least that’s the word according to a new blog from Tech Target on AWS’s new Managed Services (MS) offering. According to the blog, AWS is launching their AWS MS program to expedite the adoption of cloud by Fortune 1000 and Global 2000 companie…
This tutorial gives a high-level tour of the interface of Marketo (a marketing automation tool to help businesses track and engage prospective customers and drive them to purchase). You will see the main areas including Marketing Activities, Design …
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…

770 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