WCF service host cannot find any service

This is my first WCF.

I've looked everywhere but I could not read English at a sufficient level could not find the solution.

How can I solve this error?

I've added the rest of the code

Service1.cs:

namespace WcfJsonRestService
{
    public class Service1 : IService1
    {
        [WebInvoke(Method = "GET", 
                   ResponseFormat = WebMessageFormat.Json,
                   UriTemplate = "data/{Data}")]
        public DTResult GetData(string Data)
        { 
            DTResult result = new DTResult();
            try
            {
                result.Error = false;                                          
                string connectionString = ConfigurationManager.ConnectionStrings["db"].ToString(); 
                DTResponse ResponseData = JsonConvert.DeserializeObject<DTResponse>(DecodeFrom64(Data));
                result.DataSet = tvCore.Exec(connectionString, ResponseData.storedProcedure, ResponseData.parameters);

            }
            catch (Exception e)
            {
                result.DataSet = null;
                result.Error = true;
                result.ErrorMsg = e.Message;
            }
            return result;

        }

        static public string DecodeFrom64(string encodedData)
        {
          byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData);
          string returnValue = System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes);
          return returnValue;
        } 
    }



    /*
     *  MSSql Connect Class
     */
    public class tvCore
    {

        static public string Exec(string cntStr, string SP, dynamic[] param)
        {
            SqlConnection Cnt = new SqlConnection(cntStr); 
            DataTable Qry = new DataTable();
            DataSet DSet = new DataSet();
            SqlDataAdapter SqlDataAdp = new SqlDataAdapter();
            SqlCommand SqlCmd = new SqlCommand(SP, Cnt);
            SqlCmd.CommandType = CommandType.StoredProcedure;
            Cnt.Open();
            SqlCommandBuilder.DeriveParameters(SqlCmd);

            if (param.Length != SqlCmd.Parameters.Count-1)
                throw new Exception("Parameters lenght not match.");

            SqlCmd.Parameters.RemoveAt(0);

            for (int i = 0; i < SqlCmd.Parameters.Count; i++)
                if (SqlCmd.Parameters[i].SqlDbType == SqlDbType.DateTime)
                    SqlCmd.Parameters[i].Value = param[i] == null ? DBNull.Value : DateTime.ParseExact(param[i], "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture); 
                else
                    SqlCmd.Parameters[i].Value = param[i] == null ? DBNull.Value : param[i];  

            SqlDataReader reader = SqlCmd.ExecuteReader();
            //DataTable schema = reader.GetSchemaTable();
            //schema.PrimaryKey = new DataColumn[] { schema.Columns["ColumnOrdinal"] };

            string result = JsonConvert.SerializeObject(reader, new DTConvert());

            reader.Close();
            Cnt.Close();
           // SqlDataAdp.SelectCommand = SqlCmd;
           // SqlDataAdp.FillSchema(DSet, SchemaType.Mapped);
           // SqlDataAdp.Fill(Qry);

            return result;        
        }
    }


    /* 
     * DataTable To JSon Class
     */
    public class DTConvert : JsonConverter
    {
        public override bool CanConvert(System.Type objectType)
        {
            //Return objectType = GetType(DataTable)
            return typeof(SqlDataReader).IsAssignableFrom(objectType);
        } 

        public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
        {

            SqlDataReader reader = value as SqlDataReader;
            int ncols = reader.FieldCount;
            DataTable schema = reader.GetSchemaTable();

            writer.WriteStartObject();

            #region Columns
            writer.WritePropertyName("Columns");
            writer.WriteStartArray();
            foreach( DataRow col in schema.Rows )
            {
                writer.WriteStartObject();
                string field = "AllowDBNull";

                writer.WritePropertyName(field);
                writer.WriteValue(col[field]);

                field = "IsAutoincrement";
                writer.WritePropertyName(field);
                writer.WriteValue(col[field]);

                field = "ColumnName";
                writer.WritePropertyName(field);
                writer.WriteValue(col[field]);

                field = "DataType";
                writer.WritePropertyName(field);
                writer.WriteValue((col[field] as Type).Name);

                field = "ColumnSize";
                writer.WritePropertyName(field);
                writer.WriteValue(col[field]);

                field = "isReadOnly";
                writer.WritePropertyName(field);
                writer.WriteValue(col[field]);

                field = "isUnique";
                writer.WritePropertyName(field);
                writer.WriteValue(col[field]);

                writer.WriteEndObject();

            }

            writer.WriteEndArray();
            #endregion

            #region Rows     
            writer.WritePropertyName("Rows");
            writer.WriteStartArray();
            while (reader.Read())
            {
                writer.WriteStartObject();
                for (int i = 0; i < reader.FieldCount; i++)
                {
                    writer.WritePropertyName(reader.GetName(i));
                    writer.WriteValue(reader[i]);
                }
                writer.WriteEndObject();
            }         
            writer.WriteEndArray();
            #endregion

            writer.WriteEndObject();

        }


        public override object ReadJson(Newtonsoft.Json.JsonReader reader, System.Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            JObject jObject = JObject.Load(reader);
            DataTable table = new DataTable();            
            return table;
        }   
    }

    public class DTResult
    {
        public string DataSet { get; set; }
        public bool Error { get; set; }
        public string ErrorMsg { get; set; } 
    }

    public class DTResponse
    {
        public string storedProcedure { get; set; }
        public dynamic[] parameters { get; set; } 
    }
}

App.config

    <?xml version="1.0"?>
<configuration> 
<connectionStrings>
        <add name="db" connectionString="Server=SERVERNAME;Database=DBNAME;User Id=USERNAME;Password=PASSWORD;" providerName="System.Data.SqlClient"/>
    </connectionStrings> 
    <system.serviceModel>
        <services>
            <service name="WcfJsonRestService.Service1">
                <endpoint address="http://localhost/iPadWcf"
                          binding="webHttpBinding"
                          contract="WcfJsonRestService.IService1"/>
            </service>
        </services>
        <behaviors>
            <endpointBehaviors>
                <behavior> 
                    <webHttp />
                </behavior>
            </endpointBehaviors>
        </behaviors>

    </system.serviceModel>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
    </startup>
</configuration>

Answers


I'm assuming, that you are looking for a way to create RESTful WebService. Here is a little help, I've created as one of my practices.

If you have a store, and willing to get informations about products, you have to send a request by the client to the WebService to serve it. You have to define few things in the Web.config.

In the add

<services>
      <service name="RestService_Production.RestService">
        <endpoint address="" behaviorConfiguration="web" binding="webHttpBinding" contract="RestService_Production.IRestService" />
      </service>
</services

and

<endpointBehaviors>
    <behavior name="web">
      <webHttp />
    </behavior>
</endpointBehaviors>

Assume, you have a method like this

public interface IRestService
{

    [OperationContract]
    [WebInvoke(Method = "GET",
                ResponseFormat = WebMessageFormat.Json,
                BodyStyle = WebMessageBodyStyle.Wrapped,
                UriTemplate = "product/{id}")]
    Product GetProductInformations(string id);
}

And in the .svc, you have to define it like this

public Product GetProductInformations(string id)
    {
        return new Product();
    }

You can make a request to the Rest service, by

private static void Main(string[] args)
    {
        Remote remote = new Remote(endPoint, methodType, methodName, methodData);

        string requestUri = remote.GetEndPoint() + remote.GetMethodName() + remote.GetDataPost();
        var request = (HttpWebRequest)WebRequest.Create(requestUri);

        request.Method = remote.GetMethodType();
        request.ContentLength = 0;
        request.ContentType = "text/xml";

        Console.WriteLine("Wait until the WebService starts and then press a key to continue!");
        Console.ReadKey();

        try
        {
            var response = request.GetResponse();
            Stream getResponseStream = response.GetResponseStream();
            StreamReader sr = new StreamReader(getResponseStream);
            string friendlyResponse = GenerateFriendlyJson(sr.ReadToEnd());

            var jss = new JavaScriptSerializer();
            var product = jss.Deserialize<Dictionary<string, string>>(friendlyResponse);

            Console.WriteLine("Name: " + product["Name"] +
                            ", Description: " + product["Description"] +
                            ", Price: " + product["Price"] +
                            ", Quantity: " + product["Quantity"]);
        }
        catch (WebException wEx)
        {
            Console.WriteLine("Could not access to network through protocol: \n" + wEx.ToString());
        }
        catch (Exception cEx)
        {
            Console.WriteLine("Some common excepion happened: \n" + cEx.ToString());
        }
        finally
        {
            Console.ReadKey();
        }
    }

Where the GET methodType is a "GET", "POST", "PUT" or "DELETE" string, the name is like "product/", and the data is like anything that fits to a string. The endPoint should look like this: "ht.tp://(your host):10064/RestService.svc/" (I had to change it, because SO didn't allow links)

I hope it helped. If you have any problems, I will upload that project to Git or something.


Need Your Help

Gradle - hibernate tool not working

hibernate gradle ant

I'm trying to create a task to convert cfg to sql and I'm using hibernate 3.

OBIEE Time Difference between two columns

oracle timestamp obiee

Can anyone help me as to why this formula isn't working?