An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail - dynamics-crm

When I try to execute a CRM CRUD operation using a Console App, I'm getting the following error:
System.ServiceModel.Security.MessageSecurityException
  HResult=0x80131501
  Message=An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail.
  Source=mscorlib
class Program
{
static void Main(string[] args)
{
IOrganizationService _serviceProxy = crmConnection();
Entity con = new Entity("contact");
con["lastname"] = "test";
_serviceProxy.Create(con);
}
private static IOrganizationService crmConnection()
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Uri oUri = new Uri("https://XXXXXXXX.api.crm.dynamics.com/XRMServices/2011/Organization.svc");
ClientCredentials clientCredentials = new ClientCredentials();
clientCredentials.UserName.UserName = "XXXXXXXXXXXX";
clientCredentials.UserName.Password = "XXXXXXXXXXXXXXXXXX";
OrganizationServiceProxy _serviceProxy = new OrganizationServiceProxy(oUri, null,clientCredentials,null);
_serviceProxy.Timeout = new TimeSpan(0, 10, 0);
return _serviceProxy;
}
}
Thanks in advance.
An unsecured or incorrectly secured fault was received from the other party

Try using Connection String with XrmTooling this way you can avoid call directly to the Organization.svc and handle the redirection to the SDK
var conn = new CrmServiceClient("AuthType=Office365;Username=xxx#xxx.com; Password=yyyyyy;Url=https://xxxx.crm.dynamics.com;RequireNewInstance=True");
IOrganizationService _orgService = conn.OrganizationWebProxyClient ?? (IOrganizationService)conn.OrganizationServiceProxy;
return _orgService;
If the error continues could be related to differences between your PC time and the Dynamics Server ajusted +-4 minutes and try again.
Hope it helps

Related

SSPI negotiation failed with WtrustChannelFactory

This one has me for a while now, I am trying to build a console app that can call a .net web/wcf service SP, the first leg is to get a token from the idP (ADFS4.0) the pasted code was working fine for a whole day, at some point it stopped working with the following error:
SOAP security negotiation with 'https://adfs.domain.in/adfs/services/trust/13/windowsmixed' for target 'https://adfs.domain.in/adfs/services/trust/13/windowsmixed' failed. See inner exception for more details.
The inner error is:
The Security Support Provider Interface (SSPI) negotiation failed.
NativeErrorCode: 0x80090350 -> SEC_E_DOWNGRADE_DETECTED
I have tried /13/windows and /windowstransport as well as the endpoint.
private static GenericXmlSecurityToken RequestSecurityToken()
{
// set up the ws-trust channel factory
var factory = new Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannelFactory(new WindowsWSTrustBinding(
SecurityMode.TransportWithMessageCredential), new EndpointAddress(new Uri("https://adfs.domain.in/adfs/services/trust/13/windowsmixed"), EndpointIdentity.CreateSpnIdentity("adfs#domain.in")));
factory.TrustVersion = TrustVersion.WSTrust13;
var rst = new RequestSecurityToken
{
RequestType = RequestTypes.Issue,
KeyType = KeyTypes.Bearer,
AppliesTo = new System.ServiceModel.EndpointAddress(endpoint_address)
};
// request token and return
return factory.CreateChannel().Issue(rst) as GenericXmlSecurityToken;
}

WebRequest returns 404 when switching to SSL

Having built an app using PCL method in Xamarin and have had it working 100% using standard HTTP I now changed the remote test server to use SSL with self signed certs.
The app contacts a custom API for logging onto a server and querying for specific data.
I've changed the app to look at SSL now and initially got an error regarding Authentication not working or something but turned off SSL related errors for testing using:
ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) => true;
in my AppDelegate files FinishedLaunching method which got over that error.
I'm now getting a 404 / protocol error when trying to do my Login POST to the given URL.
I am using HttpWebRequest for my RESTful calls and this works fine if I change back to plain http.
Not sure why but some articles suggested using ModernHttpClient, which I did. I imported the component (also added the package using NuGet) to no avail.
Am I missing something else that I should be configuring in my code related to httpwebresponse when contacting the SSL server or is this component simply incapable of speaking to an SSL server?
My login function is as follows (Unrelated code removed/obfuscated):
public JsonUser postLogin(string csrfToken, string partnerId, string username, string password){
string userEndPoint = SingletonAppSettngs.Instance ().apiEndPoint;
userEndPoint = userEndPoint.Replace ("druid/", "");
var request = WebRequest.CreateHttp(string.Format(this.apiBaseUrl + userEndPoint + #"user/login.json"));
// Request header collection set up
request.ContentType = "application/json";
request.Headers.Add ("X-CSRF-Token", csrfToken);
// Add other configs
request.Method = "POST";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string json_body_content = "{\"username\":\"" + username + "\",\"password\":\"" + password + "\"}";
streamWriter.Write(json_body_content);
streamWriter.Flush();
streamWriter.Close();
}
try{
HttpWebResponse httpResponse = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader (httpResponse.GetResponseStream ())) {
var content = reader.ReadToEnd ();
content = content.Replace ("[],", "null,");
content = content.Replace ("[]", "null");
if (content == null) {
throw new Exception ("request_post_login - content is NULL");
} else {
JsonSerializerSettings jss = new JsonSerializerSettings();
jss.NullValueHandling = NullValueHandling.Ignore;
JsonUser deserializedUser = JsonConvert.DeserializeObject<JsonUser>(content, jss);
if(content.Contains ("Hire company admin user")){
deserializedUser.user.roles.__invalid_name__5 = "Hire company admin user";
deserializedUser.user.roles.__invalid_name__2 = "authenticated user";
}
return deserializedUser;
}
}
}catch(Exception httpEx){
Console.WriteLine ("httpEx Exception: " + httpEx.Message);
Console.WriteLine ("httpEx Inner Exception: " + httpEx.InnerException.Message);
JsonUser JsonUserError = new JsonUser ();
JsonUserError.ErrorMessage = "Error occured: " + httpEx.Message;
return JsonUserError;
}
}
When making a Web Request using ModernHttpClient, I generally follow the pattern below. Another great library created by Paul Betts is refit, and can be used to simplify rest calls.
using (var client = new HttpClient(new NativeMessageHandler(false, false)))
{
client.BaseAddress = new Uri(BaseUrl, UriKind.Absolute);
var result = await Refit.RestService.For<IRestApi>(client).GetData();
}
The second parameter for NativeMessageHandler should be set to true if using a customSSLVerification.
Here's a look at IRestApi
public interface IRestApi
{
[Get("/foo/bar")]
Task<Result> GetMovies();
}
Number of things I had to do to get this to work.
The Self Signed Cert had to allow TLS 1.2
As the API is Drupal based, HTTPS had to be enabled on the server and a module installed to manage the HTTP specific pages.

CRM 2016 OrganizationServiceProxy.EnableProxyTypes seems to hang

We're currently changing the architecture of our back end systems and we've discovered that we need to enable proxy types for use in CodeActivities for Workflows, using the OrganizationServiceProxy.EnableProxyTypes method.
However, whenever I include this method call it makes the Workflow run extremely slow before eventually failing.
Here is the code we use to call the method:
var service = serviceFactory.CreateOrganizationService(context.UserId);
if (service is OrganizationService)
{
tracingService.Trace("Enabling proxy types");
((OrganizationServiceProxy)((OrganizationService)service).InnerService).EnableProxyTypes(assembly);
tracingService.Trace("Proxy types enabled");
}
Any ideas?
Thanks
I've never had to pass an assembly in as a parameter to EnableProxyTypes. Did you try it without passing the assembly?
Also, there's another way to enable proxy types by adding to the Behaviors collection. Here's an example:
public static IOrganizationService GetOrganizationService(Guid userId)
{
ClientCredentials credentials = new ClientCredentials();
credentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
Uri homeRealmUri = null;
using (OrganizationServiceProxy _serviceProxy = new OrganizationServiceProxy(new Uri(GetOrganizationUri()),
homeRealmUri, credentials, null))
{
_serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
_serviceProxy.CallerId = userId;
IOrganizationService _service = (IOrganizationService)_serviceProxy;
return _service;
}
}

Windows Phone sends more than one web requests in order in a call

Reccently, I am working on a project in Windows Phone. and In this project, to validate a user, I need to check at 3 web API, the logic is like below:
Step 1: access web api 1 to get the token
Step 2: access web api 2 to get the username/password by the token retrieved in Step 1
Step 3: access web API 3 to validate the user name/password in step 2
you can see we need to access those 3 API in order. as well know, window phone now access the network asynchronously, which causes a big challenge on make those API access in order, and which make the soure code hard to maintainace.
I also consider the synchronous source code like below, but I found there are some problems to access the network,many exeption will be thrown. For example, when an exception is thrown, I try to use asynchronous web request to access the same URL, it is OK. I am strugglig in it now. And I have to introduce thread to call it to avoid to block the UI thread.
internal static class HttpWebRequestExtensions
{
public const int DefaultRequestTimeout = 60000;
public static bool IsHttpExceptionFound = false;
public static WebResponse GetResponse(this WebRequest request, int nTimeOut = DefaultRequestTimeout)
{
var dataReady = new AutoResetEvent(false);
HttpWebResponse response = null;
var callback = new AsyncCallback(delegate(IAsyncResult asynchronousResult)
{
try
{
response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
dataReady.Set();
}
catch(Exception e)
{
IsHttpExceptionFound = true;
}
});
request.BeginGetResponse(callback, request);
if (dataReady.WaitOne(nTimeOut))
{
return response;
}
return null;
}
public static WebResponse PostRequest(this HttpWebRequest request, String postData, int nTimeOut = DefaultRequestTimeout)
{
var dataReady = new AutoResetEvent(false);
HttpWebResponse response = null;
var callback = new AsyncCallback(delegate(IAsyncResult asynchronousResult)
{
Stream postStream = request.EndGetRequestStream(asynchronousResult); //End the operation.
byte[] byteArray = Encoding.UTF8.GetBytes(postData); //Convert the string into a byte array.
postStream.Write(byteArray, 0, postData.Length); //Write to the request stream.
postStream.Close();
dataReady.Set();
});
request.BeginGetRequestStream(callback, request);
if (dataReady.WaitOne(nTimeOut))
{
response = (HttpWebResponse)request.GetResponse(nTimeOut);
if (IsHttpExceptionFound)
{
throw new HttpResponseException("Failed to get http response");
}
return response;
}
return null;
}
}
Any suggestion on using asynchronous web request to solve my case?
There's an example here of using asynchronous web services in a chained manner to call the Microsoft Translator service on WP7
Maybe it will give you some pointers?
http://blogs.msdn.com/b/translation/p/wp7translate.aspx

SOAP Parsing in windows phone 7

I will searching since 10 days but i have not succeed in soap parsing in wp7.
My code is below. I get the The remote server returned an error: NotFound. and System.Net.WebException.
code is below :
private const string AuthServiceUri = "http://manarws.org/WS/manarService.asmx";
private const string AuthEnvelope =
#"<?xml version=""1.0"" encoding=""utf-8""?>
<soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
<soap:Body>
<fnGetNewsResponse xmlns=""http://tempuri.org/"">
<fnGetNewsResult></fnGetNewsResult>
</fnGetNewsResponse>
</soap:Body>
</soap:Envelope>";
public void Authenticate()
{
HttpWebRequest spAuthReq = HttpWebRequest.Create(AuthServiceUri) as HttpWebRequest;
spAuthReq.Headers["SOAPAction"] = "http://tempuri.org/fnGetNews";
spAuthReq.ContentType = "text/xml; charset=utf-8";
spAuthReq.Method = "POST";
spAuthReq.BeginGetRequestStream(new AsyncCallback(spAuthReqCallBack), spAuthReq);
}
private void spAuthReqCallBack(IAsyncResult asyncResult)
{
UTF8Encoding encoding = new UTF8Encoding();
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
System.Diagnostics.Debug.WriteLine("REquest is :" + request.Headers);
Stream _body = request.EndGetRequestStream(asyncResult);
string envelope = string.Format(AuthEnvelope,"","");
System.Diagnostics.Debug.WriteLine("Envelope is :" + envelope);
byte[] formBytes = encoding.GetBytes(envelope);
_body.Write(formBytes, 0, formBytes.Length);
_body.Close();
request.BeginGetResponse(new AsyncCallback(ResponseCallback), request);
}
private void ResponseCallback(IAsyncResult asyncResult)
{
System.Diagnostics.Debug.WriteLine("Async Result is :" + asyncResult);
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
System.Diagnostics.Debug.WriteLine("Response is :::::::::::::::::::----" + request.EndGetResponse(asyncResult));
if (request != null && response != null)
{
if (response.StatusCode == HttpStatusCode.OK)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseString = reader.ReadToEnd();
}
}
}
I get the error in HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult); line...
So, Please help me.
Thanks.
Maybe I am missing something but why not just adding a service reference ?
The service located at 'http://manarws.org/WS/manarService.asmx' is a classic web service and you can browse wsdl. You can add a reference in Visual Studio. It will generate a proxy class to call this webservice. Manual soap parsing is quite painful.
EDIT :
1) Right clic on service reference in your project.
2) Enter your service url. Then click Go.
3) You will have new classes in your project.
Just use them as you want. Exemple :
public void GetBranches()
{
ManarServiceReference.manarServiceSoapClient client = new ManarServiceReference.manarServiceSoapClient();
client.fnGetBranchesCompleted += new EventHandler<ManarServiceReference.fnGetBranchesCompletedEventArgs>(client_fnGetBranchesCompleted);
client.fnGetBranchesAsync();
}
void client_fnGetBranchesCompleted(object sender, ManarServiceReference.fnGetBranchesCompletedEventArgs e)
{
//TODO
}
Follow these steps to know how to use a SOAP service
-- Create a new project.
-- Right-click on the Project name and click on "Add Service Reference"...
Then provide address as "http://manarws.org/WS/manarService.asmx?wsdl" and click Go.
-- Once service information is downloaded, provide Namespace something like
"MyMemberService" at the bottom and click Ok.
Now that your proxy classes should be ready.
Go to your Mainpage.xaml.cs and type 'client' there..you should probably get a class with the name "ManarServiceClient".
If you get that, then try to call the suitable methods of that class.
For an example,
ManarServiceClient client = new ManarServiceClient();
client.fnGetNewsResponseCompleted += new EventHandler<fnGetNewsResponseCompletedEventArgs>(client_fnGetNewsResponseCompleted);
client.fnGetNewsResponseAsync();
Note: I am not with my working system, so cannot give you exact code. All the above is a guessed code and shall point you in the right direction. Will test my code and update soon.
If you create of an asmx web service. The first call is incredibly slow.

Resources