Get value from sql database and bind to binary image..

8 posts, 0 answers
  1. Wired_Nerve
    Wired_Nerve avatar
    163 posts
    Member since:
    Oct 2007

    Posted 07 May 2015 Link to this post

    I have a table in sql server with a field called imageData  type is nvarbinary(max)

    I have a binary image in a radwindow.

    I use the radAsyncUploader to save the image in the database.

    Once the image is saved, I want to display the image to the user next to the radAsyncUploader tool (right side).

    I try setting the DataValue property of the binaryImage control but that does not seem to work.. Any ideas?

     

    protected void LinkButtonSaveImage_Click(object sender, EventArgs e)
           {
               //Handle Uploaded images
               if (!Object.Equals(Context.Cache.Get(Session.SessionID + "UploadedFile"), null))
               {
                 var fileType =   this.AsyncUpload1.UploadedFiles[0].ContentType;
     
                   User user = (User)Session["currentUser"];
                   AttachmentRepository attachmentRepo = new AttachmentRepository();
     
                   Stream fileStream = ((MemoryStream)Context.Cache.Remove(Session.SessionID + "UploadedFile"));
                   byte[] attachmentBytes = new byte[fileStream.Length];
                   
                   fileStream.Read(attachmentBytes, 0, Convert.ToInt32(fileStream.Length));
                   var attachmentService = new AttachmentService(attachmentRepo, user);
                   attachmentService.SetAttachment(attachmentBytes, fileStream, fileType);
     
     
                   RadBinaryImage1.DataValue = attachmentBytes;
     
               }
     
           }

  2. Wired_Nerve
    Wired_Nerve avatar
    163 posts
    Member since:
    Oct 2007

    Posted 08 May 2015 in reply to Wired_Nerve Link to this post

    I still have not figured this issue  out yet.
  3. UI for ASP.NET Ajax is Ready for VS 2017
  4. Viktor Tachev
    Admin
    Viktor Tachev avatar
    1488 posts

    Posted 12 May 2015 Link to this post

    Hi,

    I tried to replicate the behavior you describe, however, I was unable to. Check out the attached project that I used for testing. When you click the button a byte array is generated from an image and is set as DataValue for the RadBinaryImage. Give the sample a try and let me know how it works for you.

    In case there is AJAX on the page try to disable it and see if the behavior changes.

    Regards,
    Viktor Tachev
    Telerik
     

    See What's Next in App Development. Register for TelerikNEXT.

     
  5. Wired_Nerve
    Wired_Nerve avatar
    163 posts
    Member since:
    Oct 2007

    Posted 14 May 2015 Link to this post

    Viktor thanks for the example you provided, but it is for a image stored on a disk, my image has been saved to a sql server database as mentioned above...   "I have a table in sql server with a field called imageData  type is nvarbinary(max)"

    I can get it to work for a image file saved to a disk... It is the process of getting it from the database and getting the RadBinaryImage to display it.  It seems to want an actual physical location... etc.. etc..

     

  6. Wired_Nerve
    Wired_Nerve avatar
    163 posts
    Member since:
    Oct 2007

    Posted 14 May 2015 in reply to Viktor Tachev Link to this post

    So I have the image saving now and I found some documentation on your site, but I am having an issue retrieving the image from the database and then displaying it again.. I am not sure I am approach this correct...  I will attach a zip of the code too...

     

     

     

    Here is a bit more code to help understand what I am attempting.

    SQL Create Statement to create the table...

    /****** Object:  Table [dbo].[tblTechAttachments]    Script Date: 5/14/2015 2:59:48 PM ******/
    SET ANSI_NULLS ON
    GO
     
    SET QUOTED_IDENTIFIER ON
    GO
     
    SET ANSI_PADDING ON
    GO
     
    CREATE TABLE [dbo].[tblTechAttachments](
        [AttachmentUID] [INT] IDENTITY(1,1) NOT NULL,
        [Name] [NVARCHAR](100) NULL,
        [ApplicationArea] [NVARCHAR](100) NULL,
        [Type] [NVARCHAR](50) NOT NULL,
        [Data] [VARBINARY](MAX) NULL,
        [CreatedByUserID] [INT] NOT NULL,
        [CreatedDate] [DATETIME] NOT NULL DEFAULT (GETDATE()),
     CONSTRAINT [PK_tblTechAttachments] PRIMARY KEY CLUSTERED
    (
        [AttachmentUID] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
     
    GO
     
    SET ANSI_PADDING ON
    GO

     

    The Service that saves the data to the database....

    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data;
    using System.Data.Linq;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Web.UI;
    using TIPWebITLibrary.BLL.AttachmentManagement.Repository;
    using TIPWebITLibrary.BLL.UserManagement;
    using TIPWebITLibrary.DAL;
     
    namespace TIPWebITLibrary.BLL.AttachmentManagement.Services
    {
        /// <summary>
        /// Controls the process of adding and removing attachments
        /// </summary>
        public class AttachmentService
        {
            private readonly IUser _user;
            private readonly IAttachmentRepository _attachmentRepository;
     
            public AttachmentService(IUser user)
            {
                _user = user;
                _attachmentRepository = new AttachmentRepository();
            }
     
            public AttachmentService(IAttachmentRepository attachmentRepository, IUser user)
            {
                _user = user;
                _attachmentRepository = attachmentRepository;
            }
     
            public void GetAttachment(int attachmentId)
            {
                throw new NotImplementedException();
            }
     
            public byte[] GetAttachment(string applicaitonArea, out string type)
            {
                if (string.IsNullOrEmpty(applicaitonArea)) throw new ArgumentNullException("applicaitonArea", "You must provide an application area, example: {HomePageImage}");
                IAttachmentRepository attachmentRepository = new AttachmentRepository();
                var result = attachmentRepository.Select(applicaitonArea);
                if (result == null)
                {
                    type = string.Empty; return null;
                }
                type = result.Type;
                return result.Data.ToArray();
            }
     
            public bool SetAttachment(byte[] attachmentBytes, string fileType)
            {
     
                try
                {
     
                    if (attachmentBytes.Length > 0)
                    {
                        Binary binaryObj = new Binary(attachmentBytes);
     
                        var entity = new tblTechAttachment()
                         {
                             ApplicationArea = "HomePageArea",   //TODO: use Enum instead. no magic strings
                             Type = fileType,
                             CreatedByUserID = this._user.UserID,
                             CreatedDate = DateTime.Now,
                             Data = binaryObj
                         };
     
                        IAttachmentRepository attachmentRepository = new AttachmentRepository();
                        return attachmentRepository.Insert(entity);
     
     
                    }
     
                }
                catch (Exception)
                {
                    throw;
                }
                return false;
     
     
            }
        }
     
     
     
     
    }

     

     My repository that this service uses to access the sql database...

    using System;
    using System.Data.Linq;
    using System.Linq;
    using TIPWebITLibrary.DAL;
     
    namespace TIPWebITLibrary.BLL.AttachmentManagement.Repository
    {
        public class AttachmentRepository : IAttachmentRepository
        {
            public tblTechAttachment Select(int id)
            {
                throw new NotImplementedException();
            }
     
            public tblTechAttachment Select(string applicationArea)
            {
                if (string.IsNullOrEmpty(applicationArea)) throw new ArgumentNullException("applicationArea", "You must provide an applicationarea.  Example: {HomePageImage}");
                using (var db = new TIPWebITLibrary.DAL.TIPWebITDataContext())
                {
                    return db.tblTechAttachments.FirstOrDefault(x => x.ApplicationArea.Contains(applicationArea));
                }
            }
            public bool Insert(tblTechAttachment entity)
            {
                int recordInserted = 0;
                try
                {
     
                    using (var db = new TIPWebITLibrary.DAL.TIPWebITDataContext())
                    {
                        db.GetChangeSet();
                        if (entity != null)
                        {
                            db.tblTechAttachments.InsertOnSubmit(entity);
                            recordInserted = db.GetChangeSet().Inserts.Count;
                            db.SubmitChanges();
                        }
                    }
                }
                catch (Exception)
                {
                    throw;
                }
                return recordInserted != 0;
            }
     
            public bool Update(tblTechAttachment entity)
            {
                throw new NotImplementedException();
            }
     
            public bool Delete(tblTechAttachment entity)
            {
                throw new NotImplementedException();
            }
        }
    }
     

     

     My UI code behind that uses the service that saves and loads the image the user selected..

    protected void LinkButtonDisplayImage_Click(object sender, EventArgs e)
          {
              //Called from javascript to update binary image control on UI side to display to user
              var fileType = imageMediaType.Value;
              var bitImage = RadBinaryImage1.DataValue;
              User user = (User)Session["currentUser"];
              AttachmentRepository attachmentRepo = new AttachmentRepository();
              // Stream fileStream = ((MemoryStream)Context.Cache.Remove(Session.SessionID + "UploadedFile"));
              byte[] attachmentBytes = RadBinaryImage1.DataValue;
     
     
              var attachmentService = new AttachmentService(attachmentRepo, user);
              attachmentService.SetAttachment(attachmentBytes, fileType);
          }
     
          public void LinkButtonSaveImage_Click(object sender, EventArgs e)
          {
             //Handle Uploaded images
              if (!Object.Equals(Context.Cache.Get(Session.SessionID + "UploadedFile"), null))
              {
                  var fileType = imageMediaType.Value;
     
                  User user = (User)Session["currentUser"];
                  AttachmentRepository attachmentRepo = new AttachmentRepository();
                  Stream fileStream = ((MemoryStream)Context.Cache.Remove(Session.SessionID + "UploadedFile"));
                  byte[] attachmentBytes = new byte[fileStream.Length];
     
                  fileStream.Read(attachmentBytes, 0, Convert.ToInt32(fileStream.Length));
                  var attachmentService = new AttachmentService(attachmentRepo, user);
                  attachmentService.SetAttachment(attachmentBytes, fileType);
              }
     
     
              Context.Cache.Remove(Session.SessionID + "UploadedFile");
     
     
     
     
     
     
          }
     
          private void getHomePageImage()
          {
              User user = (User)Session["currentUser"];
              string imageType = string.Empty;
              AttachmentRepository attachmentRepo = new AttachmentRepository();
              var attachmentService = new AttachmentService(attachmentRepo, user);
              Byte[] buffer = attachmentService.GetAttachment("HomePageArea",out imageType);
     
     
              MemoryStream memStream = new MemoryStream(buffer);
     
              //TODO:  Codes is not working, it says parameter is invalid.. grrrr
              var resutl = Image.FromStream(memStream,true,true);
     
     
     
          }
     
          private void RadAsyncUpload1_FileUploaded(object sender, FileUploadedEventArgs e)
          {
              LinkButtonSaveImage.Enabled = true;
              imageMediaType.Value = e.File.ContentType;
     
              Bitmap bitmapImage = ResizeImage(RadAsyncUpload1.UploadedFiles[0].InputStream);
              System.IO.MemoryStream stream = new System.IO.MemoryStream();
              bitmapImage.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
              RadBinaryImage1.DataValue = stream.ToArray();
              // Add to session cache
              Context.Cache.Insert(Session.SessionID + "UploadedFile", stream, null, DateTime.Now.AddMinutes(20), TimeSpan.Zero);
          }
     
          public Bitmap ResizeImage(Stream stream)
          {
              System.Drawing.Image originalImage = Bitmap.FromStream(stream);
     
              int height = 100;
              int width = 400;
     
              Bitmap scaledImage = new Bitmap(width, height);
     
              using (Graphics g = Graphics.FromImage(scaledImage))
              {
                  g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                  g.DrawImage(originalImage, 0, 0, width, height);
     
                  return scaledImage;
              }
     
          }

     

    The UI aspx stuff

    <div style="height: 125px; padding-top: 5px; padding-left: 3px; padding-bottom: 10px !important; padding-right:  3px">
        <div style="float: left; width: 225px">
            <asp:HiddenField runat="server" ID="imageMediaType" Value="" />
            <div style="float: left;">
                <label class="Text Bold">Home Page Image</label>
                <telerik:RadAsyncUpload ID="RadAsyncUpload1" runat="server"
                    OnClientFileUploaded="onClientFileUploaded"
                    AllowedFileExtensions="jpg,png,gif,bmp"
                    MaxFileInputsCount="1" PostbackTriggers="LinkButtonDisplayImage"
                    MaxFileSize="2097152" Localization-Select="Browse">
                </telerik:RadAsyncUpload>
                <label class="TextXXSmall">Recommended image size is 400X100 pixels</label>
            </div>
            <asp:Button runat="server" ID="LinkButtonDisplayImage" OnClick="LinkButtonDisplayImage_Click" CssClass="DisplayNone" />
            <div style="float: left;">
                <asp:Button runat="server" ID="LinkButtonSaveImage" OnClick="LinkButtonSaveImage_Click" Text="Upload Image" Enabled="False" />
            </div>
            <div style="float: left; padding-left: 2px;">
                <asp:Button ID="LinkButtonRemove" Enabled="False" runat="server" Text="Remove Image" />
            </div>
            <div style="clear: both;"></div>
        </div>
     
        <div style="float: right; padding-right: 2px;">
            <telerik:RadBinaryImage ID="RadBinaryImage1" runat="server" AutoAdjustImageControlSize="False" Height="100px" ImageStorageLocation="Cache" ResizeMode="Fit" Width="400px" />
     
        </div>
     
    </div>
     

     The java script:

    //<![CDATA[
             Sys.Application.add_load(function () {
     
     
                 window.upload = $find("<%=RadAsyncUpload1.ClientID %>");
     
                 setting.initialize();
             });
     
     
             //]]>

    The JS file included on the page:

    (function () {
        var $;
        var serverID;
        var upload;
        var setting = window.setting = window.setting || {};
     
        setting.initialize = function () {
            $ = $telerik.$;
     
            upload = window.upload;
        };
     
        window.onClientFileUploaded = function (sender, args) {
            if (upload.getUploadedFiles().length > 0) {
                __doPostBack('LinkButtonDisplayImage', 'LinkButtonDisplayImageArgs');
            }
            else {
                alert("Please select a picture");
            }
        };
     
        window.updatePictureAndInfo = function () {
            if (upload.getUploadedFiles().length > 0) {
                __doPostBack('LinkButtonSaveImage', 'LinkButtonSaveImageArgs');
            }
            else {
                alert("Please select a picture");
            }
        };
     
     
    })();

  7. Wired_Nerve
    Wired_Nerve avatar
    163 posts
    Member since:
    Oct 2007

    Posted 14 May 2015 in reply to Wired_Nerve Link to this post

    Here is a link to the zip file   http://1drv.ms/1IBeeiS
  8. Wired_Nerve
    Wired_Nerve avatar
    163 posts
    Member since:
    Oct 2007

    Posted 14 May 2015 in reply to Wired_Nerve Link to this post

    Here is the Demo I am following

     

    http://demos.telerik.com/aspnet-ajax/asyncupload/examples/persistuploadedfiles/defaultcs.aspx?show-source=true

  9. Wired_Nerve
    Wired_Nerve avatar
    163 posts
    Member since:
    Oct 2007

    Posted 14 May 2015 Link to this post

    Ok, I figured out the problems so I figured I would post the simple solution here...

    First, I was saving the data in an incorrect format which was not allowing me to pull it back out of the database.. 

    Here are the core methods to saving and getting.. (Still need to clean up and make sure objects are disposed and null checks...etc..etc..)

    This code pulls the image from the database and connects it to the RadBinaryImage control

    private void getHomePageImage()
           {
               User user = (User)Session["currentUser"];
               string imageType = string.Empty;
               AttachmentRepository attachmentRepo = new AttachmentRepository();
               var attachmentService = new AttachmentService(attachmentRepo, user);
               Byte[] buffer = attachmentService.GetAttachment("HomePageArea", out imageType);
                                             // SEE link to attached code for the GetAttachment function
               if (buffer == null) return;
     
               
               RadBinaryImage1.DataValue = buffer;
     
     
           }

    This code saves it with the correct format...

    public void LinkButtonSaveImage_Click(object sender, EventArgs e)
          {
              //Handle Uploaded images
              //if (!Object.Equals(Context.Cache.Get(Session.SessionID + "UploadedFile"), null))
              //{
              //    var fileType = imageMediaType.Value;
     
              User user = (User)Session["currentUser"];
              //    AttachmentRepository attachmentRepo = new AttachmentRepository();
              //    Stream fileStream = ((MemoryStream)Context.Cache.Remove(Session.SessionID + "UploadedFile"));
     
              //    System.Drawing.Image originalImage = Bitmap.FromStream(fileStream);
              //    originalImage.Save(fileStream, ImageFormat.Gif);
     
     
              //    byte[] attachmentBytes = new byte[fileStream.Length];
     
              //    fileStream.Read(attachmentBytes, 0, Convert.ToInt32(fileStream.Length));
              //    var attachmentService = new AttachmentService(attachmentRepo, user);
              //    attachmentService.SetAttachment(attachmentBytes, fileType);
              //}
     
     
              //Context.Cache.Remove(Session.SessionID + "UploadedFile");
     
              string contenttype = imageMediaType.Value;
              Stream fs = ((MemoryStream)Context.Cache.Remove(Session.SessionID + "UploadedFile"));
              BinaryReader br = new BinaryReader(fs);
              br.BaseStream.Position = 0;
              int fsLength = (int)fs.Length;
              Byte[] bytes = br.ReadBytes(fsLength);
     
              //insert the file into database
              var entity = new tblTechAttachment()
                  {
                      ApplicationArea = "HomePageArea",   //TODO: use Enum instead. no magic strings
                      Type = contenttype,
                      CreatedByUserID = user.UserID,
                      CreatedDate = DateTime.Now,
                      Data = bytes
                  };
     
              //TODO: Refactor to BLL layer
              using (var db = new TIPWebITLibrary.DAL.TIPWebITDataContext())
              {
                  db.tblTechAttachments.InsertOnSubmit(entity);
                  db.SubmitChanges();
              }
     
          }

     

     

Back to Top
UI for ASP.NET Ajax is Ready for VS 2017