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
Solved

Downloading varbinary data into a variable or file

Posted on 2013-06-18
7
292 Views
Last Modified: 2013-10-04
I am looking to download varbinary data into a sqlbinary variable in C# but I am not sure how to get this to work.  I have a class method that is running the transaction from the database and then another small chunk of code that is actully implementing the method.  How am I supposed to get this to work?  I have attached some code below.  Thanks!


 public System.Data.SqlTypes.SqlBinary GetProfilePicture(Guid profileid)
        {
            Profile profile = new Profile();

            SqlBinary profilepic;

            SqlConnection objConnection = new SqlConnection();
            DataSet objDataset = new DataSet();
            SqlDataAdapter objAdapter = new SqlDataAdapter();

            SqlCommand objCommand = new SqlCommand("spGetProfilePictureByProfileId");
            objCommand.CommandType = CommandType.StoredProcedure;

            profile.ProfileId = profileid;


            objConnection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
            objConnection.Open();
            objCommand.Connection = objConnection;
            objCommand.Parameters.Add(new SqlParameter("@ProfileId", profile.ProfileId));

            SqlParameter sqlparam = new SqlParameter();

            sqlparam.ParameterName = "@ProfilePictureUrl";
            sqlparam.Direction = ParameterDirection.Output;
            sqlparam.Size = -1;

            objCommand.Parameters.Add(sqlparam.ParameterName, SqlDbType.VarBinary);
            //objCommand.Parameters.Add(sqlparam);



            //SqlDataReader reader;
            //objCommand.ExecuteNonQuery();

           // reader = objCommand.ExecuteReader();

            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();

            using (var reader = objCommand.ExecuteReader())
            {
                while (reader.Read())
                {
                    byte[] raw = (byte[])reader.GetSqlBytes(0).Buffer;
                    profilepic = raw;

                    profile.ProfilePictureUrl = profilepic;
                }

                
            }

          return profile.ProfilePictureUrl;
            
        }      

Open in new window


and below is how I am attempting to retrieve the data from the database:

profileid = Guid.Parse(Session["ProfileId"].ToString());

SqlBinary ProfileImage = profile.GetProfilePicture(profileid);

Open in new window



unfortunately my retrieval process is not working.  How do I do this correctly?  The varbinary data that I am trying to retrieve from the database is an image.  Thanks!
0
Comment
Question by:VBBRett
  • 4
  • 3
7 Comments
 
LVL 1

Accepted Solution

by:
PeterInStingbert earned 500 total points
ID: 39257486
Hi
read a Byte[] within a datareader:

int fieldIndex = 0

if (reader.IsDBNull(fieldIndex ))
    return new byte[0];
else
{
    Byte[] b = new Byte[(reader.GetBytes(fieldIndex , 0, null, 0, int.MaxValue))];
     if (b.Length <= 0)
          return new byte[0];
     else
      {
           this.reader.GetBytes(fieldIndex , 0, b, 0, b.Length);
            return b;
       }
}

Open in new window


Create the Image from Byte[]

Byte[] imageStream = ...

System.Drawing.ImageConverter ic = new System.Drawing.ImageConverter();
image = (System.Drawing.Image)(ic.ConvertFrom(this._imageStream));

Open in new window

0
 
LVL 1

Assisted Solution

by:PeterInStingbert
PeterInStingbert earned 500 total points
ID: 39257575
Sorry typing error in Create Image from...

Byte[] imageStream = ...

System.Drawing.ImageConverter ic = new System.Drawing.ImageConverter();
image = (System.Drawing.Image)(ic.ConvertFrom(imageStream)); 

Open in new window

0
 

Author Comment

by:VBBRett
ID: 39257590
So how would I change my code?
0
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 1

Assisted Solution

by:PeterInStingbert
PeterInStingbert earned 500 total points
ID: 39257660
Hi,
It is a Problem to test w/o Information about Profil
but try this:

public System.Data.SqlTypes.SqlBinary GetProfilePicture(Guid profileid)
        {
            Profile profile = new Profile();

            SqlBinary profilepic;

            SqlConnection objConnection = new SqlConnection();
            DataSet objDataset = new DataSet();
            SqlDataAdapter objAdapter = new SqlDataAdapter();

            SqlCommand objCommand = new SqlCommand("spGetProfilePictureByProfileId");
            objCommand.CommandType = CommandType.StoredProcedure;

            profile.ProfileId = profileid;


            objConnection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
            objConnection.Open();
            objCommand.Connection = objConnection;
            objCommand.Parameters.Add(new SqlParameter("@ProfileId", profile.ProfileId));

            SqlParameter sqlparam = new SqlParameter();

            sqlparam.ParameterName = "@ProfilePictureUrl";
            sqlparam.Direction = ParameterDirection.Output;
            sqlparam.Size = -1;

            objCommand.Parameters.Add(sqlparam.ParameterName, SqlDbType.VarBinary);
            //objCommand.Parameters.Add(sqlparam);



            //SqlDataReader reader;
            //objCommand.ExecuteNonQuery();

           // reader = objCommand.ExecuteReader();

            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();

            using (var reader = objCommand.ExecuteReader())
            {
               
                while (reader.Read())
                {

                    int fieldIndex = 0;
                    Byte[] raw;

                    if (reader.IsDBNull(fieldIndex))
                        raw = new byte[0];
                    else
                    {
                        raw = new Byte[(reader.GetBytes(fieldIndex, 0, null, 0, int.MaxValue))];
                        if (raw.Length > 0)
                            reader.GetBytes(fieldIndex, 0, raw, 0, raw.Length);
                    }

                    profilepic = raw;
                    profile.ProfilePictureUrl = profilepic;
                }                
            }

          return profile.ProfilePictureUrl;
            
        }       

Open in new window

0
 

Author Comment

by:VBBRett
ID: 39257839
There seems to be a problem with the code not reading the reader.  It appears to drop out of the loop when it gets to that point.  I don't understand, it completely skipped the using (var reader) or the while (reader) loop.  Why would it do that?
0
 
LVL 1

Expert Comment

by:PeterInStingbert
ID: 39265015
Your original code is:

 using (var reader = objCommand.ExecuteReader())
            {
                while (reader.Read())
                {
                    byte[] raw = (byte[])reader.GetSqlBytes(0).Buffer;
                    profilepic = raw;

                    profile.ProfilePictureUrl = profilepic;
                }
            }

          return profile.ProfilePictureUrl;

Open in new window


Reader.Read()  works strictly Forward
--> The default position of a data reader is before the first record. Therefore, you must call Read to begin accessing data.

If there is no result (no records) in your "select Statement"

  while (reader.Read())
{
}

never Loop.
0
 

Author Comment

by:VBBRett
ID: 39302835
So is it better to throw into a file in a file directory or stream it to a file in a website?
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used.

791 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