Click here to Skip to main content
15,888,610 members
Home / Discussions / C#
   

C#

 
GeneralRe: Multiple reads of a file when it is open in another application ? Pin
BillWoodruff2-Jan-15 2:22
professionalBillWoodruff2-Jan-15 2:22 
QuestionReference to array element Pin
Krishnakumartg31-Dec-14 22:55
Krishnakumartg31-Dec-14 22:55 
AnswerRe: Reference to array element Pin
OriginalGriff31-Dec-14 23:56
mveOriginalGriff31-Dec-14 23:56 
GeneralRe: Reference to array element Pin
BillWoodruff1-Jan-15 4:24
professionalBillWoodruff1-Jan-15 4:24 
GeneralRe: Reference to array element Pin
OriginalGriff1-Jan-15 4:34
mveOriginalGriff1-Jan-15 4:34 
GeneralRe: Reference to array element Pin
harold aptroot1-Jan-15 4:44
harold aptroot1-Jan-15 4:44 
GeneralRe: Reference to array element Pin
Krishnakumartg26-Jan-15 18:52
Krishnakumartg26-Jan-15 18:52 
Question[Solved]C# Database Image Manager Pin
rattlerrFx31-Dec-14 10:44
rattlerrFx31-Dec-14 10:44 
My Database Development book includes a program for inserting Images into a database after studying the code and modifying just the connection string and image's directory. When i run the program even with Administrator it produces a Run Time error of "Denied" in the message box. Now the program does connect to the database and does insert values into the Primary Key column and 2 other columns. The problem is that it is not reading the Folder that contains the images and is not inserting them into the database image column.

I have modified the folder's permissions for Full Control but during execution of the software it automatically produces the error message of Denied.The Database has been setup for FILESTREAM and Filestream access level has been modified for level 2 and setup in the Sql Server Properties under FileStream.

Any idea's on what may be causing this issue? I am running Windows 8.1 Pro 64Bit

Class
C#
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.IO;

namespace MusicStoreImageManager
{
    class ProductDB
    {
        // define the directory for the images
        static string imagesPath = "C:/Users/Rattlerr/Pictures/Images/";

        public static SqlConnection GetConnection()
        {
            SqlConnection connection = new SqlConnection();
            connection.ConnectionString =
                "Data Source=RATTLERR;Initial Catalog=Test;Integrated Security=False;User ID=sa;Password=SomePassword";
            return connection;
        }

        public static void WriteImage(int productID, string imageName)
        {
            SqlConnection connection = null;
            SqlTransaction transaction = null;
            try
            {
                // 1. Set up the input stream from the image file
                string filepath = imagesPath + imageName;
                if (File.Exists(filepath) == false)
                    throw new Exception("File Not Found: " + filepath);

                FileStream sourceStream = new FileStream(
                    filepath,
                    FileMode.Open,
                    FileAccess.Read);

                // 2. Initialize the row in the table
                connection = GetConnection();

                SqlCommand command = new SqlCommand();
                command.Connection = connection;
                command.CommandText =
                    "INSERT INTO ProductImages " +
                    "VALUES (@ProductID, " +
                    "        CAST(@RowID AS uniqueidentifier), 0)";

                Guid rowID = Guid.NewGuid();
                command.Parameters.AddWithValue("@ProductID", productID);
                command.Parameters.AddWithValue("@RowID", rowID);

                connection.Open();
                command.ExecuteNonQuery();

                // 3. Get a reference to the BLOB
                transaction = connection.BeginTransaction();
                command.Transaction = transaction;
                command.CommandText =
                    "SELECT ProductImage.PathName(), " +
                    "       GET_FILESTREAM_TRANSACTION_CONTEXT() " +
                    "FROM ProductImages " +
                    "WHERE RowID = CAST(@RowID AS uniqueidentifier)";
                command.Parameters.Clear();
                command.Parameters.AddWithValue("@RowID", rowID);

                SqlDataReader reader = command.ExecuteReader();
                if (reader.Read() == false)
                    throw new Exception("Unable to get path and context for BLOB.");
                string path = (string)reader[0];
                byte[] context = (byte[])reader[1];
                reader.Close();

                // 4. Set up the output stream to the database
                SqlFileStream targetStream = new SqlFileStream(path, context, FileAccess.Write);                

                // 5. Read from file and write to database
                int blockSize = 1024 * 512;
                byte[] buffer = new byte[blockSize];
                int bytesRead = sourceStream.Read(buffer, 0, buffer.Length);
                while (bytesRead > 0)
                {
                    targetStream.Write(buffer, 0, bytesRead);
                    bytesRead = sourceStream.Read(buffer, 0, buffer.Length);
                }

                targetStream.Close();
                sourceStream.Close();
                transaction.Commit();
            }
            catch (Exception e)
            {
                if (transaction != null)
                    transaction.Rollback();
                throw e;
            }
            finally
            {
                if (connection != null)
                    connection.Close();
            }
        }

        public static Byte[] ReadImage(int imageID) 
        {
            SqlConnection connection = null;
            SqlTransaction transaction = null;
            try 
            {
                connection = GetConnection();
                connection.Open();
                transaction = connection.BeginTransaction();

                SqlCommand command = new SqlCommand();
                command.Connection = connection;
                command.Transaction = transaction;
                command.CommandText =
                    "SELECT ProductImage.PathName(), " +
                    "       GET_FILESTREAM_TRANSACTION_CONTEXT() " +
                    "FROM ProductImages " +
                    "WHERE ImageID = @ImageID";

                command.Parameters.AddWithValue("@ImageID", imageID);

                SqlDataReader reader = command.ExecuteReader();
                if (reader.Read() == false)
                    throw new Exception("Unable to get path and context for BLOB.");
                string path = (string)reader[0];
                byte[] context = (byte[])reader[1];
                reader.Close();

                // Set up the input stream from the database
                SqlFileStream sourceStream = new SqlFileStream(path, context, FileAccess.Read);                

                int blockSize = 1024 * 512;
                byte[] buffer = new byte[blockSize];
                List<byte> imageBytes = new List<byte>();
                int bytesRead = sourceStream.Read(buffer, 0, buffer.Length);
                while (bytesRead > 0)
                {
                    bytesRead = sourceStream.Read(buffer, 0, buffer.Length);
                    foreach(byte b in buffer)
                        imageBytes.Add(b);                        
                }
                sourceStream.Close();

                return imageBytes.ToArray();
            }
            catch (Exception e) 
            {
                throw e;
            }
            finally 
            {
                if (connection != null)
                    connection.Close();
            }
        }

        public static List<int> GetImageIDList()
        {
            SqlConnection connection = null;
            try
            {
                connection = GetConnection();

                SqlCommand command = new SqlCommand();
                command.Connection = connection;
                command.CommandText = 
                    "SELECT ImageID FROM ProductImages " +
                    "ORDER BY ImageID";

                connection.Open();
                SqlDataReader reader = command.ExecuteReader();
 
                List<int> imageIDList = new List<int>();
                while (reader.Read())
                {
                    int imageID = (int)reader[0];
                    imageIDList.Add(imageID);
                }
                reader.Close();

                return imageIDList;
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                if (connection != null)
                    connection.Close();
            }
        }
    }
}

Main Form Code
C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.IO;

namespace MusicStoreImageManager
{
    public partial class ImageManagerForm : Form
    {
        public ImageManagerForm()
        {
            InitializeComponent();
        }

        private void LoadImageIDComboBox()
        {
            // load the combo box
            List<int> imageIDList = ProductDB.GetImageIDList();
            foreach (int i in imageIDList)
                imageIDComboBox.Items.Add(i);
        }

        private void ImageManagerForm_Load(object sender, EventArgs e)
        {
            this.LoadImageIDComboBox();
            imageIDComboBox_SelectedIndexChanged(sender, e);
        }

        private void imageIDComboBox_SelectedIndexChanged(
            object sender, EventArgs e)
        {
            try
            {
                int imageID = Convert.ToInt32(imageIDComboBox.Text);

                // read image bytes from the database and display in picture box
                Byte[] imageByteArray = ProductDB.ReadImage(imageID);
                MemoryStream ms = new MemoryStream(imageByteArray);
                imagePictureBox.Image = System.Drawing.Image.FromStream(ms);
                ms.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error");
            }
        }

        private void uploadButton_Click(object sender, EventArgs e)
        {
            try
            {
                int productID = Convert.ToInt32(productIDTextBox.Text);
                string filename = filenameTextBox.Text;
                ProductDB.WriteImage(productID, filename);
                MessageBox.Show(this, "Image upload was successful!", 
                    "Upload Confirmation");

                // refresh combo box
                imageIDComboBox.Items.Clear();
                this.LoadImageIDComboBox();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error");
            }
        }
    }
}


modified 3-Jan-15 12:31pm.

AnswerRe: C# Database Image Manager Pin
Richard Andrew x6431-Dec-14 11:13
professionalRichard Andrew x6431-Dec-14 11:13 
GeneralRe: C# Database Image Manager Pin
rattlerrFx31-Dec-14 11:25
rattlerrFx31-Dec-14 11:25 
AnswerRe: C# Database Image Manager Pin
Richard Andrew x6431-Dec-14 11:27
professionalRichard Andrew x6431-Dec-14 11:27 
GeneralRe: C# Database Image Manager Pin
rattlerrFx31-Dec-14 11:36
rattlerrFx31-Dec-14 11:36 
AnswerRe: C# Database Image Manager Pin
Richard Andrew x6431-Dec-14 11:39
professionalRichard Andrew x6431-Dec-14 11:39 
GeneralRe: C# Database Image Manager Pin
rattlerrFx31-Dec-14 11:45
rattlerrFx31-Dec-14 11:45 
AnswerRe: C# Database Image Manager Pin
Richard Andrew x6431-Dec-14 12:00
professionalRichard Andrew x6431-Dec-14 12:00 
GeneralRe: C# Database Image Manager Pin
rattlerrFx31-Dec-14 12:08
rattlerrFx31-Dec-14 12:08 
AnswerRe: C# Database Image Manager Pin
Richard Andrew x6431-Dec-14 12:11
professionalRichard Andrew x6431-Dec-14 12:11 
GeneralRe: C# Database Image Manager Pin
rattlerrFx31-Dec-14 12:20
rattlerrFx31-Dec-14 12:20 
GeneralRe: C# Database Image Manager Pin
Richard Andrew x6431-Dec-14 12:24
professionalRichard Andrew x6431-Dec-14 12:24 
GeneralRe: C# Database Image Manager Pin
rattlerrFx31-Dec-14 12:24
rattlerrFx31-Dec-14 12:24 
AnswerRe: C# Database Image Manager Pin
Richard Andrew x6431-Dec-14 12:27
professionalRichard Andrew x6431-Dec-14 12:27 
GeneralRe: C# Database Image Manager Pin
rattlerrFx31-Dec-14 12:29
rattlerrFx31-Dec-14 12:29 
GeneralRe: C# Database Image Manager Pin
rattlerrFx31-Dec-14 12:42
rattlerrFx31-Dec-14 12:42 
GeneralRe: C# Database Image Manager Pin
SledgeHammer0131-Dec-14 12:30
SledgeHammer0131-Dec-14 12:30 
GeneralRe: C# Database Image Manager Pin
rattlerrFx31-Dec-14 12:34
rattlerrFx31-Dec-14 12:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.