POST Method in wcf Rest Service - c++

i am getting the same error:
protected void Button1_Click(object sender, EventArgs e)
{
BasicHttpBinding binding = new BasicHttpBinding();
binding.ReaderQuotas.MaxStringContentLength = 2000000;
binding.MaxBufferSize = 2147483647;
binding.MaxReceivedMessageSize = 2147483647;
binding.ReaderQuotas.MaxNameTableCharCount = 2147483647;
binding.Security.Transport.ClientCredentialTypeHttpClientCredentialType.Windows;
binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
binding.CloseTimeout = new TimeSpan(4, 0, 0);
binding.OpenTimeout=new TimeSpan(4, 0, 0);
binding.ReceiveTimeout=new TimeSpan(2, 0, 0);
binding.SendTimeout = new TimeSpan(5, 0, 0);
EndpointAddress endpoint = new EndpointAddress(new Uri("http://localhost:35798/RestServiceImpl.svc"));
RestPostService.RestServiceImplClient obj = new RestPostService.RestServiceImplClient(binding, endpoint);
RestPostService.EmailDetails obj1 = new RestPostService.EmailDetails();
obj.ClientCredentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
RestPostService.EmailDetails obj2=obj.SendMail(obj1);
}
**web.config**
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="webHttpBinding" maxBufferSize="2147483647" maxBufferPoolSize="524288" maxReceivedMessageSize="2147483647" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:10:00"/>
</webHttpBinding>
</bindings>
<services>
<service name="RestService.RestServiceImpl" behaviorConfiguration="ServiceBehaviour">
<endpoint address ="http://localhost:35798/RestServiceImpl" binding="webHttpBinding" contract="RestService.IRestServiceImpl" behaviorConfiguration="webHttp"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="webHttp">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="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="true"/>
<dataContractSerializer maxItemsInObjectGraph="6553600"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
What changes should i made in order to make the code working.
Error: The server did not provide a meaningful reply; this might be caused by a contract mismatch, a premature session shutdown or an internal server error.
Please help in the indiacted issue.

You are using the wrong WCF binding in you code. The config XML shows the WCF service using the WebHttpBinding. Refactor your client creation code to something like:
WebHttpBinding binding = new WebHttpBinding();
// The rest of the configuration
Don't know if all the properties you are setting will be valid for this binding but the compiler will know :)

Related

how to add bindingExtensions in webconfig?

i just wanna add bindingExtensions , i dont know what should i write in type attribute when add bindingExtensions. this is my config :
<system.serviceModel>
<extensions>
<bindingExtensions>
<add name="MaxClockSkewBinding" type="Microsoft.ServiceModel.Samples.MaxClockSkewBinding, MaxClockSkewBinding,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</bindingExtensions>
</extensions>
<bindings>
<customBinding>
<binding name="MaxClockSkewBinding">
<transactionFlow />
<security authenticationMode="SecureConversation">
<secureConversationBootstrap authenticationMode="UserNameOverTransport">
<localClientSettings maxClockSkew="00:30:00" />
</secureConversationBootstrap>
<localClientSettings maxClockSkew="00:30:00" />
</security>
<httpsTransport />
</binding>
</customBinding>
when i run my program , error is :
Configuration binding extension 'system.serviceModel/bindings/MaxClockSkewBinding' could not be found. Verify that this binding extension is properly registered in system.serviceModel/extensions/bindingExtensions and that it is spelled correctly
and this is how i use my service :
channelFactory = new ChannelFactory<TProxy>("*");
channelFactory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
//channelFactory.Credentials.ServiceCertificate.Authentication.RevocationMode = X509RevocationMode.NoCheck;
//channelFactory.Credentials.ClientCertificate.Certificate = new X509Certificate2(Certificate, CertificatePass);
channelFactory.Credentials.UserName.UserName = UserName;
channelFactory.Credentials.UserName.Password = PassWord;
var proxy = (IClientChannel)channelFactory.CreateChannel();
In Visual Studio open Tools > WCF Service Configuration Editor:
It can help you a lot with creating new WCF service configs and editing an existing one.

Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata[reply]

I write simple WCF web service(application).
I have the error: Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata.
Please help me.
My Web Service:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using WCF;
namespace ValyutaService
{
public class ValyutaService : IValyutaService
{
List<string> IValyutaService.ParaBirimleriniGetir()
{
List<String> paraBirimleri = new List<string>();
paraBirimleri.Add("AZN");
paraBirimleri.Add("USD");
paraBirimleri.Add("EURO");
paraBirimleri.Add("TL");
paraBirimleri.Add("RUBL");
return paraBirimleri;
}
public List<double> KurlariGetir(string kurTipi)
{
Random randomKur = new Random();
ist<Double> kurlarListesi = new List<Double>();
for (int i = 0; i < 15; i++)
{
kurlarListesi.Add(randomKur.NextDouble() + 2);
}
return kurlarListesi;
}
}
}
Interface:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace WCF
{
// 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 IValyutaService
{
[OperationContract]
List<string> ParaBirimleriniGetir();
[OperationContract]
List<Double> KurlariGetir(string kurTipi);
}
}
Web Config:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</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>
</configuration>

Call WebService in https

I create a webService to generate pdf file. In debug mode with VisualStudio 2012. It's Ok. I can call it from other IntranetSite.
I try to put it on my test server. But I need to add https instead of http.
I find this
I try to adapted like this my web.config
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="GenerationCourriersSoap" >
<security mode="Transport">
<transport clientCredentialType="None" proxyCredentialType="None" realm="" />
<message clientCredentialType="Certificate" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="secureBehaviours">
<serviceMetadata httpsGetEnabled="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<client>
<endpoint address="https://localhost:52999/GenerationCourrier.asmx"
binding="basicHttpBinding" bindingConfiguration="GenerationCourriersSoap"
contract="WSCourrier.GenerationCourriersSoap" name="GenerationCourriersSoap" />
</client>
</system.serviceModel>
But I've message
Unable to establish a trust for the secure channel SSL / TLS with authority 'localhost: 52999'.
I used an auto-certicate buid by IIS directly.
I verify, this certificate is on my root and secure folder
Someone have an idea?
Finally I find this enter link description here
It seems good. now I can reach the webService.
The Idea is to force the validation of all certificate. Just the time of test period like that
Imports System
Imports System.Net
Imports System.Security.Cryptography.X509Certificates
Public Class clsSSL
Public Function AcceptAllCertifications(ByVal sender As Object, ByVal certification As System.Security.Cryptography.X509Certificates.X509Certificate, ByVal chain As System.Security.Cryptography.X509Certificates.X509Chain, ByVal sslPolicyErrors As System.Net.Security.SslPolicyErrors) As Boolean
Return True
End Function
End Class
And call function just before call WebService function
ServicePointManager.ServerCertificateValidationCallback = AddressOf AcceptAllCertifications

Error obtaining the response from a Web Service call

I am trying to consume a Web Service and, though apparently all my parameters seem to be okay, I keep getting an erro page as response instead of an array of bytes which is what I am expecting and what the WebService is supposed to return.
My objective is to Seal a file in order to make them only readable for the right people. I am using the IRM Oracle Web Services to acomplish that, but, though all my parameters semm alright, I can't get the reponse properly.
Acording to the Oraclel support, my request is fine, so it must be something on IIS I guess. Any help?
Exception Message:
The content type multipart/related;start="";type="application/xop+xml";boundary="uuid:ab73a894-eaf4-4293-aa4e-c3358b95ec73";start-info="text/xml" of the response message does not match the content type of the binding (text/xml; charset=utf-8). If using a custom encoder, be sure that the IsContentTypeSupported method is implemented properly. The first 748 bytes of the response were: '--uuid:ab73a894-eaf4-4293-aa4e-c3358b95ec73 Content-Id: Content-Type: application/xop+xml;charset=utf-8;type="text/xml" Content-Transfer-Encoding: binary '.
Exception Stacktrace:
Server stack trace: at System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory factory, WebException responseException, ChannelBinding channelBinding) at System.ServiceModel.Channels.HttpChannelFactory.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 HTMLToPDFComponenteConverter.sealing_services.SealingServices.Seal(SealRequest request) at HTMLToPDFComponenteConverter.sealing_services.SealingServicesClient.HTMLToPDFComponenteConverter.sealing_services.SealingServices.Seal(SealRequest request) at HTMLToPDFComponenteConverter.sealing_services.SealingServicesClient.Seal(Byte[] stream, String mimeType, SealingOptions options) at HTMLToPDFComponenteConverter.ConvertToPDF.Page_Load(Object sender, EventArgs e)
Exception Data:
System.Collections.ListDictionaryInternal
Exception Source:
mscorlib
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.ContentType = "application/vnd.sealedmedia.softseal.pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=Relatorio.spdf");
SealingServicesClient sealingServicesClient =
new SealingServicesClient("SealingServices");
sealingServicesClient.ClientCredentials.UserName.UserName =
ConfigurationManager.AppSettings["Irm-user"];
sealingServicesClient.ClientCredentials.UserName.Password =
ConfigurationManager.AppSettings["Irm-password"];
// Create the classification details used in the sealing options
SealingOptions sealingOptions = new SealingOptions();
// This just set several parameters which the WebService validates. (They're all okay)
sealingOptions.classification = GetClassificationSetUp();
String mimeType = "application/pdf";
// Here is where everything goes wrong. I keep getting an error message.
byte[] sealedFile = sealingServicesClient.Seal(file, mimeType, sealingOptions);
if (sealedFile != null && sealedFile.Length > 0)
{
Response.AddHeader("Content-Length", sealedFile.Length.ToString());
Response.BinaryWrite(sealedFile);
Response.Flush();
Response.End();
}
Meu WebConfig está desse jeito:
<system.serviceModel>
<client>
<endpoint address="https://url:porta/irm_sealing/sealing_services"
binding="basicHttpBinding" bindingConfiguration="SealingServicesBinding"
contract="sealing_services.SealingServices" name="SealingServices"
behaviorConfiguration="IrmSealingAbril">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
</client>
<behaviors>
<endpointBehaviors>
<behavior name="IrmSealingAbril">
<clientCredentials>
<clientCertificate storeLocation="LocalMachine"
storeName="Root"
x509FindType="FindByThumbprint"
findValue="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX">
</clientCertificate>
</clientCredentials>
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding name="SealingServicesBinding" closeTimeout="00:05:00"
openTimeout="00:05:00" receiveTimeout="00:10:00" sendTimeout="00:05:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="2097152" maxBufferPoolSize="524288" maxReceivedMessageSize="2097152"
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="Transport">
<transport clientCredentialType="Basic" realm="weblogic" />
</security>
</binding>
</basicHttpBinding>
</bindings>
</system.serviceModel>
Where am I going wrong?
Additional information: The request apparently is correct as confirmed by oracle support. However, I can't get the returning response. I thought it could be something related to the IIS, but I do not have mush skill at configuring it.
Thanks in advance.
I found the answer for my problem here:
Error consuming webservice, content type "application/xop+xml" does not match expected type "text/xml"
Thanks anyway

Adding web service bindings into SharePoint web.config using SPWebConfigModification

I have a SharePoint web part which uses a WCF service. To be able to consume the web service in my web part, I need to modify the SharePoint web.config to include bindings and end points.
What's the best way to do this?
This was very useful but it missed a bit. Whereas the code can be deployed, it can't be retracted because a name wasn't assigned.
Use:
modification.Name = "bindings";
Also, having said that this is bindings, you (probably) can't still can't apply the settings if there are already settings there for:
serviceHostingEnvironment aspNetCompatibilityEnabled="true"
... inside the system.serviceModel
I've used the technique to insert the bindings and then the client end point gets inserted separately as this can change according to installation and in my case is set via a sharepoint list entry.
To be able to do this, I put my web service configuration into a text file as a template. The text file (BindingTemplate.txt) content is as the following:
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_AuthenticationInterface" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10: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://{0}/MyWebService/AuthenticationService.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_AuthenticationInterface" contract="AuthenticationService.AuthenticationInterface" name="BasicHttpBinding_AuthenticationInterface" />
</client>
I used the C# following code to modify the web.config:
string content;
string WebServiceServer = "example.com"; // <=== your host-name here
using (TextReader tr = File.OpenText(bindingFilePath))
{
content = String.Format(tr.ReadToEnd(), WebServiceServer);
}
SPWebConfigModification modification = new SPWebConfigModification("system.serviceModel", "configuration");
modification.Value = content;
modification.Sequence = 0;
modification.Type =SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
modification.Owner = OWNER_CONSTANT;
webApp.WebConfigModifications.Add(modification);
I spent some time figuring it out. Hope this will help someone.