0

I have an application that accepts ID and show product image associated with a company. There are 2 tables, one for oldproducts called ImagesArchive and new product in NewImages. According to requirement an ID can only have one product in the NewImages table. So iam able to successfully do that in my code. But in the ImagesArchive table, since i am recording all the old products from this company there is one to many relationship between ID & product. How can I show a list using iframe & MVC GetOld(ID)?? What's the best way to trap errors and show when Images are not found i.e. URL for product is not working?

--Images Model

 public class Images   
       {
           public int ID { get; set; }
           public string URL_FilePath { get; set; }
        }

HTML file

   <head>
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
       <script type="text/javascript">
           function Imagepreview() {
               var ID = document.getElementById("ID").value;
               document.getElementById("companyImage").src = "api/Images/GetNew/" + ID;
               old();       
           }
           function old() {
               var ID = document.getElementById("KeyID").value;
               document.getElementById("companyOldImage").src = "api/Images/GetOld/" + ID;

           }
       </script>
       <style type="text/css">
           #companyImage {
               width: 181px;
           }
           #archiveImage {
               margin-left: 17px;
           }
       </style>
   </head>
    <body ">
      <div class="jumbotron" align="center">
         <h1>Images API</h1>    
         <p class="lead"></p>        
         <div class="col-md-4" align="center">       
            <input type="text" name="ID" id="ID"/>          
             <input type="button" value="Show Image" onclick="Imagepreview()"/>
             <br>
             <br>
              <iframe src="" id="companyImage" height="200" width="200"> </iframe>
              <iframe src="" id="companyOldImage" height="200" width="200"> </iframe>
         </div>
         <div id="response">
         </div>
      </div>
   </body>
</html>

----------------------Controller Get function----------

 [System.Web.Mvc.AcceptVerbs("GET")]
        public HttpResponseMessage GetNew(int ID)     
        {
            Images newImages = new Images();
            GetSettingsInfo();
            HttpResponseMessage result = null;

            string sql = "select id,url_filepath from [dbo].[NewImages]  WHERE ID = @ID";
            using (SqlConnection connection = new SqlConnection(ConnectionString))
             {
                using (SqlCommand query = new SqlCommand(sql, connection))
                {
                    SqlDataReader rdr;
                    query.Parameters.Add(new SqlParameter("@ID", ID));
                    query.CommandType = CommandType.Text;
                    connection.Open();
                    query.CommandTimeout = 240;
                    rdr = query.ExecuteReader();
                    if (rdr != null)
                    {
                        while (rdr.Read())
                        {
                            newImages.ID = ConvertFromDBVal<int>(rdr["ID"]);
                            newImages.URL_FilePath = ConvertFromDBVal<string>(rdr["URL_FilePath"]);               
                        }
                    }
                }
            }
         if (newImages.KeyID != 0)
            {
                if (!(newImages.URL_FilePath.Contains("http")))
                    newImages.URL_FilePath = "http://" + newImages.URL_FilePath;
                HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(newImages.FilePath);           
                HttpWebResponse httpWebReponse = (HttpWebResponse)httpWebRequest.GetResponse();
                Stream stream = httpWebReponse.GetResponseStream();
                Image img = Image.FromStream(stream);
                MemoryStream ms = new MemoryStream();
                img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                result = new HttpResponseMessage(HttpStatusCode.OK);
                result.Content = new ByteArrayContent(ms.ToArray());
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
            }
            else
            {
                result = new HttpResponseMessage(HttpStatusCode.NotFound);
            }
                return result;     
        }

 [System.Web.Mvc.AcceptVerbs("GET")]
        public HttpResponseMessage GetOld(int ID)     
        {
            Images newImages = new Images();
  //queries ImagesArchive table instead of ImagesTable
}
newbieCSharp
  • 181
  • 2
  • 22
  • I see you are manually pulling out the image from the filesystem and then pushing it down in the HTML. Are you able to just reference the directory where it exists instead? You'd save a lot of processing and IIS does all the work instead of the ASP.NET pipeline? – Dominic Zukiewicz Jul 04 '14 at 11:55
  • Also - do you have a "No Image Available" image, which could be used as a fallback if it does not exist in the old/new items – Dominic Zukiewicz Jul 04 '14 at 11:56
  • And one more off-topic tidy up - you are using jQuery, so use the simplified syntax up manipulate the DOM - `document.getElementById("companyImage").src = "api/Images/GetNew/" + ID;` becomes `$("#companyImage").attr("src","api/Images/GetNew/" + ID);` – Dominic Zukiewicz Jul 04 '14 at 11:58
  • @DominicZukiewicz, for example, the URL_FilePath has value"http://www.generalmills.com/images/logo_home.gif" in DB. How can I show the image other than using MemoryStream? I also do not have a "No Image AVailable" image. – newbieCSharp Jul 04 '14 at 12:01
  • You just return the URL directly and the browser will load it automatically – Dominic Zukiewicz Jul 04 '14 at 12:17
  • From [http://stackoverflow.com/questions/12240713/put-content-in-httpresponsemessage-object] : `Request.CreateResponse(HttpStatusCode.OK, newImages.URL_FilePath);` – Dominic Zukiewicz Jul 04 '14 at 12:19
  • @DominicZukiewicz, I couldn't get the image to display with Request.CreateResponse(HttpStatusCode.OK, newImages.URL_FilePath); and also how can I return a list of images to iframe? – newbieCSharp Jul 05 '14 at 10:23

1 Answers1

0

Here is how I pictured you using the API. You pass the ID up to the service and return 2 URLs for the images from the service:

public class ImageData
{
   public string OldUrl { get; set; }
   public string NewUrl { get; set; }
}

public class ImageController : ApiController
{
   // Gets 2 images - old and new
   public ImageData GetNew(string id)
   {
      return new ImageData
      {
         OldUrl = "/images/old/" + id,
         NewUrl = "/images/new/" + id,
      };
   }
}

Now define some functions to retrieve the new URL from the API. Here I have 2 functions: 1 to do the API retrieve and one for the click event:

/// Gets image URLs from the API

function getImagesFor(idForImage) {
       var imageUrl = $.get('api/Image/GetNew/' + idForImage)
            .done(function(data) {

               // Retrieve 'OldUrl' and 'NewUrl' from the JSON returned

               $("#oldImage").attr('src', data.OldUrl);
               $("#newImage").attr('src', data.NewUrl);
       });
}


// Hooks up the events - 'click' extracts the info and calls the service.
$(document).ready( function() {

   $("#imageButton").click(function() {
      var imageId = $("#imageId").text();
      getImagesFor(imageId);
      return false;
   });
}

And heres a basic HTML to see the results:

<script type="text/javascript">
   <!-- As above -->
</script>

<div>
  <input type="text" id="imageId"/>
  <input type="button"  id="imageButton"/><br/>
  <iframe src="" id="oldImage"/>
  <iframe src="" id="newImage"/>
</div>
Dominic Zukiewicz
  • 8,258
  • 8
  • 43
  • 61