0
votes

Using WCF test client to invoke the following method

Service1.svc

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

namespace ShoppingCartService
{
    // 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 Service1 : IService1
    {
        DigitalXDBEntities _db = new DigitalXDBEntities();

        //Fetches Images from SQL Database
        public string GetImage(object Picture)
        {
            return "data:image/jpg;base64," + Convert.ToBase64String((byte[])Picture);
        }

        //Fetches popular products 
        public List<Product> GetTopProducts()
        {
            var query = (from p in _db.Products
                         orderby p.Price
                         select p).Take(5);

            return query.ToList();
        }

        //Fetches all DVD  using subcategory product id
        public List<Product> GetDvds()
        {

            List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8 };
            var query = (from p in _db.Products
                         where list.Contains(p.SubCategoryID)
                         select p);

            return query.ToList();

        }

        //Fetches all components  using subcategory product id
        public List<Product> GetComponents()
        {
            IEnumerable<int> list = new List<int>() { 25, 31, 29, 30 };
            List<Product> query = (from p in _db.Products
                                   where list.Contains(p.SubCategoryID)
                                   select p).ToList();
            return query;

        }

        //Fetches all Consoles using product id
        public List<Product> GetConsoles()
        {
            IEnumerable<int> list = new List<int>() { 21, 23 };
            List<Product> query = (from p in _db.Products
                                   where list.Contains(p.SubCategoryID)
                                   select p).ToList();
            return query;

        }

        //Fetches all games  using subcategory product id
        public List<Product> GetGames()
        {

            IEnumerable<int> list = new List<int>() { 9, 10, 11, 12, 14, 15 };
            List<Product> query = (from p in _db.Products
                                   where list.Contains(p.SubCategoryID)
                                   select p).ToList();
            return query;

        }

        //Fetches all handbooks  using subcategory product id
        public List<Product> GetHandbooks()
        {
            IEnumerable<int> list = new List<int>() { 27, 28 };
            List<Product> query = (from p in _db.Products
                                   where list.Contains(p.SubCategoryID)
                                   select p).ToList();
            return query;

        }

        //Fetches all pc parts  using subcategory product id
        public List<Product> GetPcParts()
        {
            IEnumerable<int> list = new List<int>() { 26 };
            List<Product> query = (from p in _db.Products
                                   where list.Contains(p.SubCategoryID)
                                   select p).ToList();
            return query;

        }

    }
}

My Iservice.cs

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

namespace ShoppingCartService
{
    // 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 IService1
    {
        [OperationContract]
        List<Product> GetDvds();

        [OperationContract]
        List<Product> GetTopProducts();

        [OperationContract]
        List<Product> GetComponents();

        [OperationContract]
        List<Product> GetGames();

        [OperationContract]
        List<Product> GetHandbooks();

        [OperationContract]
        List<Product> GetPcParts();

    }


    // Use a data contract as illustrated in the sample below to add composite types to service operations.


}

And my webconfig

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1" />
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
      <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" 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="DigitalXDBEntities" connectionString="metadata=res://*/DigitalX.csdl|res://*/DigitalX.ssdl|res://*/DigitalX.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=DESKTOP-D4D7MNA;initial catalog=DigitalXDB;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework&quot;" providerName="System.Data.EntityClient" /></connectionStrings>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

Full error message

Failed to invoke the service. Possible causes: The service is offline or inaccessible; the client-side configuration does not match the proxy; the existing proxy is invalid. Refer to the stack trace for more detail. You can try to recover by starting a new proxy, restoring to default configuration, or refreshing the service.

An error occurred while receiving the HTTP response to http://localhost:56504/Service1.svc. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.

Server stack trace: at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout) at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout) at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation) at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Exception rethrown at [0]: at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) at IService1.GetDvds() at Service1Client.GetDvds()

Inner Exception: The underlying connection was closed: An unexpected error occurred on a receive. at System.Net.HttpWebRequest.GetResponse() at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)

Inner Exception: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size) at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead)

Inner Exception: An existing connection was forcibly closed by the remote host at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags) at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)

I came across a previous post that mentioned changing IEnumerable list to a generic list, unfortunately that didn't work

EDIT: Post has been updated with full code and namespace

EDIT: Using the default method provided by the service (shown below) works just fine in the test client, however my own methods, that connect to the DB doesn't invoke at all and shows the above Error Message

public string GetData(int value) { return string.Format("You entered: {0}", value); }

1
Added some more details to my postinvrt

1 Answers

0
votes

In your config file check the part for WCF configuration and you will see that you don't have any configuration for endpoint and service contract as well. Essentially you are completely missing the services section under <system.serviceModel> and I believe that's the issue here

  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
      <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>

It should be something like below per your edited post

<services> 
<service name="ShoppingCartService.Service1"> 
<endpoint address="" binding="basicHttpBinding" contract="ShoppingCartService.IService1" /> 
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> 
</service> 
</services>