unable to load wcf restful help page after changing transferMode to "Streamed" - wcf-binding

In my project, a wcf restful service, which allow users to upload photos to the web service.
After changing config settings to allow large file upload. (add binding configuration, i.e. "TransferMode", "BufferSize", etc.)
All Operation contracts are all working as expected.
However, the service help page for the endpoint stopped working.
The help page comes back, once I remove the binding config setting on my endpoint
How can I fixed this?? where did i missed
thank you all
<bindings>
<webHttpBinding>
<!-- buffer: 64KB; max size: 64MB -->
<binding name="StreamedBinding" closeTimeout="00:01:00" openTimeout="00:01:00"
receiveTimeout="00:10:00" sendTimeout="00:01:00" transferMode="Streamed"
maxBufferPoolSize="67108864" maxBufferSize="65536" maxReceivedMessageSize="67108864">
</binding>
</webHttpBinding>
</bindings>
<service name="WCFRestFul.ApiRestful">
<endpoint address="" binding="webHttpBinding"
bindingConfiguration="StreamedBinding" bindingName="StreamedBinding"
contract="WCFRestFul.IApiRestful" behaviorConfiguration="web" />
</service>
Update:
I think it is not just because of the transfer mode, but maybe some other setting as well.
The service help page comes back once I remove the "bindingConfiguration" in the code above.
I have 2 endpoints. The other endpoint don't have the "bindingConfiguration", and the service help page works fine on that.
I definitely missed some thing here, maybe some thing simple.
any help will be greatly appreciated

I took carlosfigueira advice, painfully removed my config setting one at a time.
I changed my config settings from
OLD Code
<bindings>
<webHttpBinding>
<!-- buffer: 64KB; max size: 64MB -->
<binding name="StreamedBinding" closeTimeout="00:01:00" openTimeout="00:01:00"
receiveTimeout="00:10:00" sendTimeout="00:01:00" transferMode="Streamed"
maxBufferPoolSize="67108864" maxBufferSize="65536" maxReceivedMessageSize="67108864">
</binding>
</webHttpBinding>
</bindings>
To Final working version (transferMode="Streamed" is removed)
<bindings>
<webHttpBinding>
<binding name="StreamedBinding" maxReceivedMessageSize="67108864" />
</webHttpBinding>
</bindings>
finally the service help page is back.
However I can't understand why it is back same as why it was turned off.
anyway, this is the working solution for my case.
hope someone would find it helpful.

What do you mean by saying that it stops working? In the example below the help page is still returned by the service (and I tried using both IE and Chrome, and they were able to see the page).
public class StackOverflow_5937029
{
[ServiceContract]
public interface ITest
{
[WebGet]
int Add(int x, int y);
}
public class Service : ITest
{
public int Add(int x, int y)
{
return x + y;
}
}
static void SendRequest(string address)
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(address);
req.Method = "GET";
HttpWebResponse resp;
try
{
resp = (HttpWebResponse)req.GetResponse();
}
catch (WebException e)
{
resp = (HttpWebResponse)e.Response;
}
Console.WriteLine("HTTP/{0} {1} {2}", resp.ProtocolVersion, (int)resp.StatusCode, resp.StatusDescription);
foreach (string headerName in resp.Headers.AllKeys)
{
Console.WriteLine("{0}: {1}", headerName, resp.Headers[headerName]);
}
Console.WriteLine();
Stream respStream = resp.GetResponseStream();
Console.WriteLine(new StreamReader(respStream).ReadToEnd());
Console.WriteLine();
Console.WriteLine(" *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* ");
Console.WriteLine();
}
public static void Test()
{
string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
WebHttpBehavior behavior = new WebHttpBehavior
{
HelpEnabled = true
};
WebHttpBinding binding = new WebHttpBinding
{
TransferMode = TransferMode.Streamed
};
host.AddServiceEndpoint(typeof(ITest), binding, "").Behaviors.Add(behavior);
host.Open();
Console.WriteLine("Host opened");
SendRequest(baseAddress + "/Add?x=4&y=8");
SendRequest(baseAddress + "/help");
Console.Write("Press ENTER to close the host");
Console.ReadLine();
host.Close();
}
}

Related

FaultException is not working correct when using BasicHttpBinding

So, I noticed FaultException is not giving me the proper result when I use the BasicHttpBinding. When I use WSHttpBinding it works file.
The issue is, From WCF Service if I throw the FaultException like below,
var translations = new List<FaultReasonText> { new FaultReasonText("FaultReasonText 1"), new FaultReasonText("FaultReasonText 2") };
throw new FaultException<MessageServiceFault>(MessageServiceFault.Fault1, new FaultReason(translations));
When it reaches to the client the fault.Reason.Translations count is 1. That means the first one (FaultReasonText 1) only is getting back to client.
But when I use WSHttpBinding the count is 2. Where the issue is? Can anyone help me on this.
It gives me different result when I test the below code with BasicHttpBinding & WSHttpBinding bindings.
class Program
{
static void Main(string[] args)
{
try
{
string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
ServiceHost host = new ServiceHost(typeof(MessageService), new Uri(baseAddress));
host.AddServiceEndpoint(typeof(IMessageService), new WSHttpBinding(), "");
host.Open();
Console.WriteLine("Host opened");
ChannelFactory<IMessageService> myChannelFactory = new ChannelFactory<IMessageService>(new WSHttpBinding(), new EndpointAddress(baseAddress));
IMessageService channel = myChannelFactory.CreateChannel();
var response = channel.GetMessage();
}
catch (FaultException fault)
{
fault.Reason.Translations.ToList().ForEach(i => Console.WriteLine(i.Text));
Console.WriteLine(false);
}
}
}
[ServiceContract]
public interface IMessageService
{
[OperationContract]
[FaultContract(typeof(MessageServiceFault))]
string GetMessage();
}
public class MessageService : IMessageService
{
public string GetMessage()
{
var translations = new List<FaultReasonText> { new FaultReasonText("FaultReasonText 1"), new FaultReasonText("FaultReasonText 2") };
throw new FaultException<MessageServiceFault>(MessageServiceFault.Fault1, new FaultReason(translations));
}
}
[DataContract]
public enum MessageServiceFault
{
[EnumMember]
Fault1,
[EnumMember]
Fault2
}
EDIT:
But, this article says, You can supply a number of different text strings that get picked from depending on the user's language settings. The Translations bucket holds all of the different text strings and their associated cultural identifiers (tied together by a FaultReasonText). When no culture is specified for a fault reason or a translation search, the assumed culture is the current thread culture. For example, if you want a translation to "en-UK", we'll first look for "en-UK" and then we'll look for "en". If we still can't find a match, then we'll take the first translation in the list, which could be anything.
If so, Why in case of WsHttpBinding it returns me the 2 FaultReasonText ?
To use FaultException, you need to activate SOAP 1.2 on your web service.
BasicHttpBinding uses SOAP 1.1, WSHttpBinding uses SOAP 1.2. That's why it works with WSHttpBinding and not with BasicHttpBinding.
Instead of using BasicHttpBinding, you should better use customBindings, with textMessageEncoding and httpTransport :
<customBinding>
<binding name="simpleBinding">
<textMessageEncoding messageVersion="Soap12" writeEncoding="utf-8" />
<httpTransport />
</binding>
</customBinding>
If you convert a default basicHttpBinding with this tool : you will obtain :
<!-- generated via Yaron Naveh's http://webservices20.blogspot.com/ -->
<customBinding>
<binding name="NewBinding0">
<textMessageEncoding MessageVersion="Soap11" />
<httpTransport />
</binding>
</customBinding>
<!-- generated via Yaron Naveh's http://webservices20.blogspot.com/ -->
Source binding :
<bindings>
<basicHttpBinding>
<binding name="NewBinding0" />
</basicHttpBinding>
</bindings>
Try to activate SOAP 12 to your service, and it will work

How to use ServiceRoutes while defining maxReceivedMessageSize for non-custom bindings in WCF

Editing this to refocus on the actual issue. I've preserved the origional question at the bottom of the message but changing the title and content to reflect what was really happening.
I need to override the maxReceivedMessageSize for a WCF service added to an MVC3 project via the ServiceRoute mechanism. Specifing the binding in the web.config doesn't work. How does one do this.
Initial question is below this line but is misleading based on lots of false positives I was seeing.
Hi I have used some examples to add a file streaming upload service to my MVC3 project. If I use the default bindings (i.e., not defined in web.config) the service works as long as I don't exceed the 64k default size. When I try and define my own binding to increase the size I get a content-type mismatch in my trace and a HTTP415 Unsupported Media Type in the response. I'm trying to call this via fiddler via HTTP and am not using a WCF client.
Here is the error in the trace:
Content Type image/jpeg was sent to a service expecting multipart/related;type="application/xop+xml". The client and service bindings may be mismatched.
Here is the web.config service model section
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="NewBehavior0" />
</endpointBehaviors>
</behaviors>
<services>
<service name="AvyProViewer.FileService">
<endpoint address="UploadFile" binding="basicHttpBinding" bindingConfiguration=""
contract="AvyProViewer.FileService" />
</service>
</services>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
<bindings>
<basicHttpBinding>
<binding name="NewBinding0" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"
messageEncoding="Mtom" transferMode="StreamedRequest">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
</binding>
</basicHttpBinding>
</bindings>
Here is the service:
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class FileService
{
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "UploadFile")]
public string UploadFile(Stream fileStream)
{
string path = HostingEnvironment.MapPath("~");
string fileName = Guid.NewGuid().ToString() + ".jpg";
FileStream fileToupload = new FileStream(path + "\\FileUpload\\" + fileName, FileMode.Create);
byte[] bytearray = new byte[10000];
int bytesRead, totalBytesRead = 0;
do
{
bytesRead = fileStream.Read(bytearray, 0, bytearray.Length);
totalBytesRead += bytesRead;
} while (bytesRead > 0);
fileToupload.Write(bytearray, 0, bytearray.Length);
fileToupload.Close();
fileToupload.Dispose();
return fileName;
}
}
And here is where I expose it in my MVC3 routes:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.Add(new ServiceRoute("FileService", new WebServiceHostFactory(), typeof(FileService)));
. . .
}
I think the issue is with the mtom declaration for messageEncoding in your binding. Try changing messageEncoding to Text.
Answer ended up being a combination of three different stack overflow posts. None by themselves solved the question but each provided crucial clues as to what was happing.
It seems that if you add a ServiceRoute the web.config binding information is ignored. This SO post clued me in to what seems to be undocumented behavior of this function: Unable to set maxReceivedMessageSize through web.config
I then used this post to determine how to programatically override the maxreceivedmesssagesize for the binding: Specifying a WCF binding when using ServiceRoute.
Unfortunately the code form #2 didn't work out of the box (not sure if the binding behavior for ServiceRoute has changed or what makes the difference). Turns out that if you specify a ServiceRoute its automatically created as a CustomBinding which can't be cast to the WebHTTPBinding type used in #2. So this post: How to set the MaxReceivedMessageSize programatically when using a WCF Client? helped me determine how to change the code in #2 to add this capability to a custom binding.

Cannot connect to a WCF service hosted in a Worker Role

I've created a WCF service and hosted it in cloud through a worker role. Unfortunately when I try to connect to the worker role service I get an exception with the message:
"No DNS entries exist for host 3a5c0cdffcf04d069dbced5e590bca70.cloudapp.net."
3a5c0cdffcf04d069dbced5e590bca70.cloudapp.net is the address for the worker role deployed in azure staging environment.
The workerrole.cs has the following code to expose the WCF service:
public override void Run()
{
using (ServiceHost host = new ServiceHost(typeof(MyService)))
{
string ip = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["tcppoint"].IPEndpoint.Address.ToString();
int tcpport = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["tcppoint"].IPEndpoint.Port;
int mexport = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["mexinput"].IPEndpoint.Port;
// Add a metadatabehavior for client proxy generation
// The metadata is exposed via net.tcp
ServiceMetadataBehavior metadatabehavior = new ServiceMetadataBehavior();
host.Description.Behaviors.Add(metadatabehavior);
Binding mexBinding = MetadataExchangeBindings.CreateMexTcpBinding();
string mexlistenurl = string.Format("net.tcp://{0}:{1}/MyServiceMetaDataEndpoint", ip, mexport);
string mexendpointurl = string.Format("net.tcp://{0}:{1}/MyServiceMetaDataEndpoint", RoleEnvironment.GetConfigurationSettingValue("Domain"), 8001);
host.AddServiceEndpoint(typeof(IMetadataExchange), mexBinding, mexendpointurl, new Uri(mexlistenurl));
// Add the endpoint for MyService
string listenurl = string.Format("net.tcp://{0}:{1}/MyServiceEndpoint", ip, tcpport);
string endpointurl = string.Format("net.tcp://{0}:{1}/MyServiceEndpoint", RoleEnvironment.GetConfigurationSettingValue("Domain"), 9001);
host.AddServiceEndpoint(typeof(IMyService), new NetTcpBinding(SecurityMode.None), endpointurl, new Uri(listenurl));
host.Open();
while (true)
{
Thread.Sleep(100000);
Trace.WriteLine("Working", "Information");
}
}
}
The tcppoint and mexinput are configured with the ports 8001 and 9001. Also Domain is configured with worker role deployment url:3a5c0cdffcf04d069dbced5e590bca70.cloudapp.net
On the client part(a console app), we are using the following configuration in app.config::
<bindings>
<netTcpBinding>
<binding name="NetTcpBinding_IMyService" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
transactionFlow="false" transferMode="Buffered" transactionProtocol="OleTransactions"
hostNameComparisonMode="StrongWildcard" listenBacklog="10"
maxBufferPoolSize="524288" maxBufferSize="65536" maxConnections="10"
maxReceivedMessageSize="65536">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<reliableSession ordered="true" inactivityTimeout="00:50:00"
enabled="false" />
<security mode="None">
<transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
<message clientCredentialType="Windows" />
</security>
</binding>
</netTcpBinding>
</bindings>
<client>
<endpoint address="httpp:\\3a5c0cdffcf04d069dbced5e590bca70.cloudapp.net:9001/MyServiceEndpoint" binding="netTcpBinding"
bindingConfiguration="NetTcpBinding_IMyService" contract="ServiceReference1.IMyService"
name="NetTcpBinding_IMyService" />
</client>
<behaviors>
<serviceBehaviors>
<behavior name="behave">
<serviceMetadata httpGetEnabled="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<system.net>
<defaultProxy useDefaultCredentials="true">
<proxy autoDetect="False" usesystemdefault="False" bypassonlocal="True" />
</defaultProxy>
The following code is built using the sample code available in msdn as background. Locally it is working fine. Unfortunately when i deploy it to cloud, the exception occurs. Moreover, when i use the virtual ip instead of the url, a connection time out occurs with the exception the remote machine did not respond.
Looks like you have your service setup to listen on net.tcp (TCP) and your client using http bindings. I would not expect that to work even locally. I am assuming you have actually opened port 9000 in the ServiceDefinition. Remember that will be a load-balanced endpoint. Are you trying to communicate to this instance from within the deployment (inter-role) or from outside the cloud?
I have found it is a lot easier to setup the host and client (when communicating within a role) through code. Try this:
http://dunnry.com/blog/2010/05/28/HostingWCFInWindowsAzure.aspx
If you are trying to hit the service from a client outside the deployment, this still applies, but for the client building part. You will need to use the external DNS name and port defined in ServiceDefinition.
I have also seen DNS errors if you try to hit the endpoint too soon before the role was ready. It can take a bit to propogate the DNS and you should try not to resolve it until it is ready, lest you cache a bogus DNS entry. If you can resolve that DNS name however to your VIP address, that is not the issue.
public void CallWebService(string data)
{
try
{
string uri = "url"+data;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream str = response.GetResponseStream();
StreamReader sr = new StreamReader(str);
String IResponse = sr.ReadToEnd();
}
catch (Exception ex)
{
System.Console.WriteLine("Message: "+ex.Message);
}
}
Hope it helps you.

How to create a WCF client without settings in config file?

I just start work on WCF a month ago. Please forgive me if I ask something already answered. I try to search first but found nothing.
I read this article, WCF File Transfer: Streaming & Chunking Channel Hosted In IIS. It works great. Now I like to integrate client side code to be part of my application, which is a dll running inside AutoCAD. If I want to work with config file, I have to change acad.exe.config which I don't think is a good idea. So I think if it possible, I want to move all code in config file to code.
Here is config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IService" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
messageEncoding="Mtom" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://10.1.13.15:88/WCFStreamUpload/service.svc/ep1"
binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IService"
contract="MGFileServerClient.IService"
name="BasicHttpBinding_IService" />
</client>
</system.serviceModel>
Could you please help me to make this change?
You can do all the setting up from within code, assuming that you don't need the flexibility to change this in the future.
You can read about setting up the endpoint on MSDN. Whilst this applies to the server the configuration of the endpoint and bindingd apply to the client as well, its just that you use the classes differently.
Basically you want to do something like:
// Specify a base address for the service
EndpointAddress endpointAdress = new EndpointAddress("http://10.1.13.15:88/WCFStreamUpload/service.svc/ep1");
// Create the binding to be used by the service - you will probably want to configure this a bit more
BasicHttpBinding binding1 = new BasicHttpBinding();
///create the client proxy using the specific endpoint and binding you have created
YourServiceClient proxy = new YourServiceClient(binding1, endpointAddress);
Obviously you'll probably want to configure the binding with security, timeouts etc the same as your config above (you can read about the BasicHttpBinding on MSDN), but this should get you going in the right direction.
This is totally code based configuration and working code. You dont need any configuration file for client. But at least you need one config file there (may be automatically generated, you dont have to think about that). All the configuration setting is done here in code.
public class ValidatorClass
{
WSHttpBinding BindingConfig;
EndpointIdentity DNSIdentity;
Uri URI;
ContractDescription ConfDescription;
public ValidatorClass()
{
// In constructor initializing configuration elements by code
BindingConfig = ValidatorClass.ConfigBinding();
DNSIdentity = ValidatorClass.ConfigEndPoint();
URI = ValidatorClass.ConfigURI();
ConfDescription = ValidatorClass.ConfigContractDescription();
}
public void MainOperation()
{
var Address = new EndpointAddress(URI, DNSIdentity);
var Client = new EvalServiceClient(BindingConfig, Address);
Client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.PeerTrust;
Client.Endpoint.Contract = ConfDescription;
Client.ClientCredentials.UserName.UserName = "companyUserName";
Client.ClientCredentials.UserName.Password = "companyPassword";
Client.Open();
string CatchData = Client.CallServiceMethod();
Client.Close();
}
public static WSHttpBinding ConfigBinding()
{
// ----- Programmatic definition of the SomeService Binding -----
var wsHttpBinding = new WSHttpBinding();
wsHttpBinding.Name = "BindingName";
wsHttpBinding.CloseTimeout = TimeSpan.FromMinutes(1);
wsHttpBinding.OpenTimeout = TimeSpan.FromMinutes(1);
wsHttpBinding.ReceiveTimeout = TimeSpan.FromMinutes(10);
wsHttpBinding.SendTimeout = TimeSpan.FromMinutes(1);
wsHttpBinding.BypassProxyOnLocal = false;
wsHttpBinding.TransactionFlow = false;
wsHttpBinding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
wsHttpBinding.MaxBufferPoolSize = 524288;
wsHttpBinding.MaxReceivedMessageSize = 65536;
wsHttpBinding.MessageEncoding = WSMessageEncoding.Text;
wsHttpBinding.TextEncoding = Encoding.UTF8;
wsHttpBinding.UseDefaultWebProxy = true;
wsHttpBinding.AllowCookies = false;
wsHttpBinding.ReaderQuotas.MaxDepth = 32;
wsHttpBinding.ReaderQuotas.MaxArrayLength = 16384;
wsHttpBinding.ReaderQuotas.MaxStringContentLength = 8192;
wsHttpBinding.ReaderQuotas.MaxBytesPerRead = 4096;
wsHttpBinding.ReaderQuotas.MaxNameTableCharCount = 16384;
wsHttpBinding.ReliableSession.Ordered = true;
wsHttpBinding.ReliableSession.InactivityTimeout = TimeSpan.FromMinutes(10);
wsHttpBinding.ReliableSession.Enabled = false;
wsHttpBinding.Security.Mode = SecurityMode.Message;
wsHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
wsHttpBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
wsHttpBinding.Security.Transport.Realm = "";
wsHttpBinding.Security.Message.NegotiateServiceCredential = true;
wsHttpBinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
wsHttpBinding.Security.Message.AlgorithmSuite = System.ServiceModel.Security.SecurityAlgorithmSuite.Basic256;
// ----------- End Programmatic definition of the SomeServiceServiceBinding --------------
return wsHttpBinding;
}
public static Uri ConfigURI()
{
// ----- Programmatic definition of the Service URI configuration -----
Uri URI = new Uri("http://localhost:8732/Design_Time_Addresses/TestWcfServiceLibrary/EvalService/");
return URI;
}
public static EndpointIdentity ConfigEndPoint()
{
// ----- Programmatic definition of the Service EndPointIdentitiy configuration -----
EndpointIdentity DNSIdentity = EndpointIdentity.CreateDnsIdentity("tempCert");
return DNSIdentity;
}
public static ContractDescription ConfigContractDescription()
{
// ----- Programmatic definition of the Service ContractDescription Binding -----
ContractDescription Contract = ContractDescription.GetContract(typeof(IEvalService), typeof(EvalServiceClient));
return Contract;
}
}
Are you looking to retain your custom config and reference it within your application? You may try this article: Reading WCF Configuration from a Custom Location (In regards to WCF)
Otherwise, you can use ConfigurationManager.OpenExeConfiguration.

WCF 405 webmethod not found issue

I have a requirement of creating a webservice where the client and the service will talk in Simple Soap (that request and response will be soap), I tried all to find a sample example on net where this thing is already done or some code sample so that I can get started but I think I am bad in searching google, that is why can't find any one so far, Some one suggested to use WCF so get an article
http://csharping.com/wcf/building-a-soap-response-envelope-manually-with-the-message-class/
But again my problem is not solved, I tried to create an application with this sample (with so many issues :( )
Created a console application and the Program.cs is
using System;
using System.IO;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.Text;
using System.Runtime.Serialization;
namespace ServiceConsole
{
public class Program
{
static void Main(string[] args)
{
using (ServiceHost serviceHost = new ServiceHost(typeof(ServiceClient), new Uri("http://localhost:2000/")))
{
ServiceEndpoint serviceEndpoint = new ServiceEndpoint(
ContractDescription.GetContract(typeof(IService)));
ServiceEndpoint metadataEndpoint = new ServiceEndpoint(
ContractDescription.GetContract(typeof(IMetadataExchange)));
ServiceMetadataBehavior metadataBehavior = serviceHost.Description.Behaviors.Find<ServiceMetadataBehavior>();
if (metadataBehavior == null)
{
metadataBehavior = new ServiceMetadataBehavior();
metadataBehavior.HttpGetEnabled = true;
serviceHost.Description.Behaviors.Add(metadataBehavior);
}
serviceHost.AddServiceEndpoint(typeof(IService), new BasicHttpBinding(), "http://localhost:2000/");
serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "http://localhost:2000/WCFService/mex");
serviceHost.Open();
string requestData = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Header><h:HeaderItem xmlns:h=\"http://tempuri.org/\">a header item</h:HeaderItem><ActivityId CorrelationId=\"090c553b-bfcc-4e4f-94cd-1b4333fe82a9\" xmlns=\"http://schemas.microsoft.com/2004/09/ServiceModel/Diagnostics\">377a454b-b543-4c6f-b4ac-3981029b60e6</ActivityId></s:Header><s:Body><string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">a body item</string></s:Body></s:Envelope>";
byte[] requestDataBytes = Encoding.UTF8.GetBytes(requestData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/WCFService/");
request.Method = "POST";
request.ContentType = "text/xml; charset=utf-8";
request.Headers.Add("SOAPAction", "http://tempuri.org/IWebService/GetMessage");
request.ContentLength = requestDataBytes.Length;
StreamWriter streamWriter = new StreamWriter(request.GetRequestStream());
streamWriter.Write(requestData);
streamWriter.Flush();
streamWriter.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader streamReader = new StreamReader(response.GetResponseStream());
string responseBody = streamReader.ReadToEnd();
Console.WriteLine("Service returned the following response...");
Console.WriteLine("");
Console.WriteLine(responseBody);
Console.ReadKey();
serviceHost.Close();
}
}
}
}
the app.config which I generated using svcutil.exe is like this
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IService" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:2000/WebService/Service.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService"
contract="IService" name="BasicHttpBinding_IService" />
</client>
</system.serviceModel>
</configuration>
My webservioce is like (it is a WCF website in which the port is provided by me and is 2000
Service contract is
[ServiceContract]
public interface IService
{
[OperationContract]
Message GetMessage(Message s);
}
[ServiceBehavior]
public class Service : IService
{
public Message GetMessage(Message message)
{
string body = message.GetBody<string>();
return Message.CreateMessage(MessageVersion.Soap11, "http://tempuri.org/IWebService/GetMessageResponse", "body is " + body);
}
}
and the web.config is
<system.serviceModel>
<services>
<service behaviorConfiguration="ServiceBehavior" name="Service">
<endpoint address="http://localhost:2000/WebService/Service.svc" binding="basicHttpBinding" bindingConfiguration=""
contract="IService" >
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<timeouts closeTimeout="00:01:10" />
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true" policyVersion="Policy15" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
My issue is 405 webmethod not body can anyone please tell me what is an issue in this, I am new to WCF before this created a sample and this is my second application
You do not need to create the SOAP message manually, just use basic http binding and that will rturn SOAP.
When you have a WCF service, the whole point is that you can define e.g. parameters like strings, int and so forth - and you don't have to mess with loads of XML and SOAP headers and bodies.
So basically, your service contract should be something like:
[ServiceContract]
public interface IService
{
[OperationContract]
int DoSomeMathAddTowNumbers(int num1, int num2);
}
and your service implementation would then just implement that method, add the two numbers, and return the result:
public class Service : IService
{
int DoSomeMathAddTowNumbers(int num1, int num2)
{
return num1 + num2;
}
}
No mess with Message or XML manipulation or anything.
A client that wants to call your service would create a WCF client-side proxy using svcutil or the Visual Studio Add Service Reference method, and it would get a proxy class that has the same methods as the service it connects to - and you would call them, using the straight, easy parameters - something like:
ServiceClient client = new ServiceClient();
int result = client.DoSomeMathAddTwoNumbers(42, 100);
So basically, I think you need to get back to the drawing board and read up on the WCF basics again - it should not be that difficult, really! (that's the whole point - it should make services easy ...)
Check out the Beginner's Guide at the WCF Developer Center at MSDN - it contains lots of really good videos, screencasts, articles on how to get started with WCF.-
You might also want to check out the DotNet Rocks TV episode #135: Keith Elder Demystifies WCF