3

I am creating a WCF service that will be consumed by plain JavaScript on the client side and some jQuery JavaScript on the client side as well.

1) How can I implement the plain client JavaScript so that it will invoke the WCF Service in such a way that it will retrieve a collection of System.IO.Stream at once? Moreover, how would I iterate through the collection that was received on the plain JavaScript side in such a way that I can associate each of the System.IO.Stream objects in the collection to an HTML image element?

2) Is it possible to implement the JavaScript code that uses jquery so that it will invoke the WCF Service in such a way that it will retrieve a collection of System.IO.Stream at once? Moreover, how would I iterate through the collection that was received by the JavaScript that uses jQuery in such a way that I can associate each of the System.IO.Stream objects in the collection to an HTML image element?

 /*********Start of Excerpt from the Interface Code of a WCF Service

 Contract*****************/

 using System;

 using System.Collections.Generic;

 using System.Linq;

 using System.Runtime.Serialization;

 using System.ServiceModel;

 using System.ServiceModel.Activation;

 using System.Text;

 using System.ServiceModel.Web;

 using System.IO;

 using ConsoleForWCFServiceTutorial.PerlsDataContracts;

 using ConsoleForWCFServiceTutorial.DataAccessObjectsDAO;


 namespace ConsoleForWCFServiceTutorial

 {

    [ServiceContract(Namespace =

 "http://ConsoleForWCFServiceTutorial.CarService")]

    public interface ICarService

    {

   [OperationContract]

   [WebInvoke(Method = "GET",

                   BodyStyle = WebMessageBodyStyle.WrappedRequest)]

        Stream[] getImagesList();




    }

 }

 /*********End of Excerpt from the Interface Code of a WCF Service
 Contract*****************/




 /*********Start of Excerpt of the code associated with the Class that
 implements the WCF Service Contract*****************/

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Collections;
 using System.ServiceModel.Activation;
 using System.Configuration;
 using System.Data;
 using System.IO;
 using System.ComponentModel;
 using ConsoleForWCFServiceTutorial.PerlsDataContracts;
 using ConsoleForWCFServiceTutorial.DataAccessObjectsDAO;


 namespace ConsoleForWCFServiceTutorial
 {
      [AspNetCompatibilityRequirements(RequirementsMode =
      AspNetCompatibilityRequirementsMode.NotAllowed)]
 class CarService : ICarService
 {

       public Stream[] getImagesList()
        {


            List<Stream> myImagesList = new List<Stream>();

            string fileName = Path.Combine("BMWpicture.jpg");

            FileStream fileStream =
              new FileStream(fileName, FileMode.Open, FileAccess.Read);
            // Set the content type as image/ jpeg
            System.ServiceModel.Web.WebOperationContext.
              Current.OutgoingResponse.ContentType = "image/jpeg";


            myImagesList.Add(fileStream);

            string fileName2 = Path.Combine("MercedesBenzpicture.jpg");

            FileStream fileStream2 =
              new FileStream(fileName2, FileMode.Open, FileAccess.Read);
            // Set the content type as image/ jpeg
            System.ServiceModel.Web.WebOperationContext.
              Current.OutgoingResponse.ContentType = "image/jpeg";


            myImagesList.Add(fileStream2);

            return myImagesList.ToArray();
        }
    }
 }
 /*********End of Excerpt of the code associated with the Class that
 implements the WCF Service Contract*****************/


 <!--Start of Excerpt of the plain JavaScript client code that
 invokes one of the Methods in the WCF Service
 Contract-->

 <script type="text/javascript">

 function getImagesList2() {

   var listOfStreams =
 'http://localhost:8732/Design_Time_Addresses/ConsoleForWCFServiceTutorial/carService     /getImagesList'

   document.getElementById("image11").onload = function () {
     }; // img.onload = function()


      document.getElementById("image11").src = listOfStreams[0];



   document.getElementById("image12").onload = function () {
        }; // img.onload = function()


      document.getElementById("image12").src = listOfStreams[1];

 }
 </script>
 <!--End of Excerpt of the plain JavaScript client code that
 invokes one of the Methods in the WCF Service
 Contract-->

 <!--Start of Excerpt of the HTML code that is affected by the
 JavaScript client and WCF Service interaction-->
 <body>
    <form id="form1" runat="server">
    <div>


                 <img src=""  id="image11" alt="Smiley face" />     

               <img src=""  id="image12" alt="Smiley face" />


         <br />
         <a class="large blue button" id="A7"
 onClick="getImagesList2()">getImagesList2</a>


        </div>
    </form>
 </body>
 </html>

 <!--End of Excerpt of the HTML code that is affected by the
 JavaScript client and WCF Service interaction-->

1) How can I implement the plain client JavaScript so that it will invoke the WCF Service in such a way that it will retrieve a collection of System.IO.Stream at once? Moreover, how would I iterate through the collection that was received on the plain JavaScript side in such a way that I can associate each of the System.IO.Stream objects in the collection to an HTML image element?

2) Is it possible to implement the JavaScript code that uses jquery so that it will invoke the WCF Service in such a way that it will retrieve a collection of System.IO.Stream at once? Moreover, how would I iterate through the collection that was received by the JavaScript that uses jQuery in such a way that I can associate each of the System.IO.Stream objects in the collection to an HTML image element?

crazyTech
  • 1,379
  • 3
  • 32
  • 67

1 Answers1

2

You need to create a WCF service, enabling CORS, that would return a list of Base64String's(converted from byte arrays of images you want to recieve). Then by this answer --> https://stackoverflow.com/a/9464137/1488207 you can set them into img tags one by one traversing through the list you recieve in jquery. I am not going to provide you with exactly what you want(i guess you would be able to convert your images to byte array and then return Base64Strings ), but I can copy my WCF service's config and code files to save your time (it took me a lot of time to successfully consume my WCF from jquery).

<?xml version="1.0"?>

<system.web>
    <compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
    <services>
        <service  name="EmployeeService.EmployeeSearchService/*Your service name replaces EmployeeService.EmployeeSearchService */" behaviorConfiguration="DefaultServiceBehavior">
            <endpoint binding="webHttpBinding" contract="EmployeeService.IEmployeeSearchService"      behaviorConfiguration="DefaultEPBehavior" />
        </service>
    </services>
    <behaviors>
        <endpointBehaviors>
            <behavior name="DefaultEPBehavior">
                <webHttp />
            </behavior>
        </endpointBehaviors>
        <serviceBehaviors>
            <behavior name="DefaultServiceBehavior">
                <serviceMetadata httpGetEnabled="true" />
                <serviceDebug includeExceptionDetailInFaults="true" />
            </behavior>
        </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
    To browse web app root directory during debugging, set the value below to true.
    Set to false before deployment to avoid disclosing web app folder information.
  -->
    <directoryBrowse enabled="true"/>
</system.webServer>
<connectionStrings>
    <add name="myConnString" connectionString=""/>
</connectionStrings>

IMPLEMENTATION

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Web.Script.Serialization;

namespace EmployeeService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the             class name "Service1" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
public class EmployeeSearchService : IEmployeeSearchService
{
    public List<Customer> GetAllImages()
    {
        WebOperationContext.Current.OutgoingResponse.Headers.Add(
            "Access-Control-Allow-Origin", "*"); WebOperationContext.Current.OutgoingResponse.Headers.Add(
            "Access-Control-Allow-Methods", "POST"); WebOperationContext.Current.OutgoingResponse.Headers.Add(
            "Access-Control-Allow-Headers", "Content-Type, Accept");
        List<Base64String> s = new List<Base64String>();
        //DO YOUR IMAGE CONVERSION TO BYTE ARRAY AND THEN TO BASE64STRINGS AND ADD THEM TO THE LIST ABOVE
        var jsonData = new
        {
            totalImages = s.Count,
            Images = (
                from row in s
                select new
                {
                    imgString = row
                }
         ).ToArray()
        };
        return (new JavaScriptSerializer()).Serialize(jsonData);
    }
}
}

INTERFACE

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using EmployeeSearchService.BE;
namespace EmployeeService
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
[ServiceContract]
public interface IEmployeeSearchService
{
    [OperationContract]
    [WebInvoke(Method = "GET",
       ResponseFormat = WebMessageFormat.Json,
       RequestFormat = WebMessageFormat.Json,
       BodyStyle = WebMessageBodyStyle.Bare)]
    object GetAllImages();
}
}

Now you can call this service from jquery by the below code, in success event you will get an object which would contain count and a property Image, you will have to traverse the array by "result.Image[0]"

$.support.cors = true;
var methodName = '/GetAllImages';
var urlService = 'some http service url';
$.ajax({
    type: "GET",
    url: urlService + methodName,
    data: {},
    dataType: "Json",
    processdata: "false",
    success: function (result) {
        if (result != null) {
            images = $.parseJSON(result);
            for(var i = 0 ; i < result.totalImages ; i++)
               $('<img>').src('data:image/png;base64,' + result.Image[i]).insertAfter('#myDiv');
        }
        else { }
    },
    error: function (msg) {
        alert(msg);
    }
});

Tell if you need more help.

Community
  • 1
  • 1
Taha Rehman Siddiqui
  • 2,441
  • 5
  • 32
  • 58