?
Solved

Downloading varbinary data into a variable or file

Posted on 2013-06-18
7
Medium Priority
?
305 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
[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
  • 4
  • 3
7 Comments
 
LVL 1

Accepted Solution

by:
PeterInStingbert earned 2000 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 2000 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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 1

Assisted Solution

by:PeterInStingbert
PeterInStingbert earned 2000 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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

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

ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
Have you created a query with information for a calendar? ... and then, abra-cadabra, the calendar is done?! I am going to show you how to make that happen. Visualize your data!  ... really see it To use the code to create a calendar from a q…
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses

752 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