I can't get a soap message in C# - c#

I'm getting an error:
A security error was encountered when verifying the message
Https is expected when I somehow overcome this error. But I have to use Http.
EndpointAddress address2 = new EndpointAddress("http://xx.xx.xxxx/ws/test?wsdl");
FactoryWebServiceClient client = new FactoryWebServiceClient();
client.Endpoint.Address = address2;
if (client.ClientCredentials != null)
{
client.ClientCredentials.Windows.ClientCredential = new System.Net.NetworkCredential("username","password");
client.ClientCredentials.UserName.UserName = "username";
client.ClientCredentials.UserName.Password = "password";
}
XmlDocument doc = new XmlDocument();
doc.Load("C:\\...\\test.xml");
byte[] bytes = Encoding.Default.GetBytes(doc.OuterXml);
var request2 = new factoryWSUpdateData
{
BeanXml = bytes,
Period = 1,
InputType = "xml",
OutputType = "json2",
CodeTemplate = 1
};
var result = client.create(request2);

Related

Consume web service in C# with digital sign the request

I need to consume a web service (SOAP) in C# with digital sign the request. But everytime I got the 400 bad request with message that "The Login failed because of an exception: javax.security.auth.login.LoginException: CWWSS6810E: The runtime can not identify the key corresponding to the identifier [Xqgkv4YNXYZgUmgtTX+s+ffshm4=].</" Here is my code:
public BSCACustomWcfServiceClient(string clientCertificatePath, string pfxCertificatePath)
{
clientCertificate = new X509Certificate2(clientCertificatePath);
pfxCertificate = new X509Certificate2(pfxCertificatePath, "BlueShieldCa2022!");
}
public string GetClientList()
{
System.ServiceModel.Channels.AsymmetricSecurityBindingElement asbe = new AsymmetricSecurityBindingElement();
asbe.MessageSecurityVersion = MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
asbe.InitiatorTokenParameters = new System.ServiceModel.Security.Tokens.X509SecurityTokenParameters { InclusionMode = SecurityTokenInclusionMode.Never };
asbe.RecipientTokenParameters = new System.ServiceModel.Security.Tokens.X509SecurityTokenParameters { InclusionMode = SecurityTokenInclusionMode.Never };
asbe.MessageProtectionOrder = System.ServiceModel.Security.MessageProtectionOrder.EncryptBeforeSign;
asbe.SecurityHeaderLayout = SecurityHeaderLayout.Strict;
asbe.IncludeTimestamp = true;
asbe.DefaultAlgorithmSuite = System.ServiceModel.Security.SecurityAlgorithmSuite.Basic128;
CustomBinding myBinding = new CustomBinding();
myBinding.Elements.Add(asbe);
myBinding.Elements.Add(new TextMessageEncodingBindingElement(MessageVersion.Soap12, Encoding.UTF8));
HttpsTransportBindingElement httpsBindingElement = new HttpsTransportBindingElement();
httpsBindingElement.RequireClientCertificate = true;
myBinding.Elements.Add(httpsBindingElement);
Uri httpUri = new Uri("uri");
EndpointAddress endPoint = new EndpointAddress(httpUri);
ServiceReference1.ReportsClient cliente = new ServiceReference1.ReportsClient(myBinding, endPoint);
cliente.Endpoint.Contract.ProtectionLevel = ProtectionLevel.None;
cliente.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
cliente.ClientCredentials.ServiceCertificate.DefaultCertificate = clientCertificate;
cliente.ClientCredentials.ClientCertificate.Certificate = pfxCertificate;
cliente.Open();
string ReportName = "MCP Client Listing";
string ReportType = "TAB";
string TimeStamp = DateTime.Now.ToString("yyyy-MM-ddThh:mm:ss.fffZ");
string SenderId = "CMSZZ00573";
string SenderName = "MY TEST ORGANIZATION";
string OrganizationId = "9999";
string ReceiverId = "DHCS CMS NET";
string Payload = "MCP Client Listing";
byte[] Payload1;
string ErrorCode;
string ErrorMessage;
var res = cliente.ClientListEnvelope(ref ReportName, ref ReportType, ref TimeStamp, ref SenderId, SenderName, ref OrganizationId, ref ReceiverId, Payload, out Payload1, out ErrorCode, out ErrorMessage);
return null;
}
Can anyone help to resolve the issue?

Downloading pdf file from SOAP API C#

I am trying to download a file content from SOAP API which is imported as an wsdl into my .net core project. I can see the response in the fiddler that file contents are coming back from API but in my .net code it is blank. Every other field in the response is coming back fine and it is just the content of the file getting striped out from response.
Below is the code to download:
BasicHttpBinding basicHttpBinding = new BasicHttpBinding(BasicHttpSecurityMode.None);
basicHttpBinding.MaxBufferSize = 2147483647;
basicHttpBinding.MaxBufferPoolSize = 2147483647;
basicHttpBinding.MaxReceivedMessageSize = 2147483647;
basicHttpBinding.ReaderQuotas.MaxStringContentLength = 2147483647;
basicHttpBinding.ReaderQuotas.MaxArrayLength = 2147483647;
basicHttpBinding.ReaderQuotas.MaxDepth = 32;
basicHttpBinding.ReaderQuotas.MaxBytesPerRead = 2147483647;
var wcfHostUri = new Uri(esbServiceOptions?.DocumentumServiceHost);
var endpoint = new Uri(wcfHostUri, esbServiceOptions?.RACQServiceFolderUrl);
var endpointAddress = new EndpointAddress(endpoint);
var client = new RACQ.PC.DocumentumService.RACQServicePortClient(basicHttpBinding, endpointAddress);
using (new OperationContextScope(client.InnerChannel))
{
var identitiesHeader = new ServiceContextHeader();
OperationContext.Current.OutgoingMessageHeaders.Add(identitiesHeader);
var document = client.retrieveDocumentAsync(new PC.DocumentumService.ObjectIdentitySet()
{
Identities = new[]
{
new ObjectIdentity
{
repositoryName = esbServiceOptions.RepositoryName,
valueType = ObjectIdentityType.OBJECT_ID,
valueTypeSpecified = true,
Item = new ObjectId
{
id = documentId
}
}
}
}, new OperationOptions()
{
Profiles = new Profile[]
{
new ContentTransferProfile
{
transferMode = ContentTransferMode.BASE64,
transferModeSpecified = true
},
new ContentProfile
{
urlReturnPolicy = UrlReturnPolicy.NEVER,
urlReturnPolicySpecified = true,
renditionTypeFilter = RenditionTypeFilter.ANY,
renditionTypeFilterSpecified = true,
pageModifierFilter = PageModifierFilter.ANY,
pageModifierFilterSpecified = true,
pageFilter = PageFilter.ANY,
pageFilterSpecified = true,
formatFilter = FormatFilter.ANY,
formatFilterSpecified = true
}
}
}, esbServiceOptions.DocumentUsername).GetAwaiter().GetResult();//Result;
var content = (BinaryContent)document.#return.DataObjects.First().Contents.First();
return content.Value; //this is null
The #content.Value is null in the above code. The below is that is in the fiddler you can clearly see that file is coming back for the same request I am capturing:

Sharepoint 2010 GetListItems with Webservice - ListSoapClient with DefaultNetworkCredentials

I want to get some ListItems of a SharePoint 2010 List with a Win8 App. Everything works fine when I set the Credentials manually like:
BasicHttpBinding basicHttpBinding = new BasicHttpBinding();
basicHttpBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
EndpointAddress endpoint = new EndpointAddress("http://site1/site2/_vti_bin/Lists.asmx");
string listName = "{4e661b3b-d0a9-4440-b98f-3f3ef41a44a7}";
string viewName = "{f1ba8d46-ad36-40ef-b4bc-6f74ea87b5d7}";
string rowLimit = "25";
XElement ndQuery = new XElement("Query");
XElement ndViewFields = new XElement("ViewFields");
XElement ndQueryOptions = new XElement("QueryOptions");
MyService.ListsSoapClient client = new MyService.ListsSoapClient(basicHttpBinding, endpoint);
client.ClientCredentials.Windows.ClientCredential.UserName = "user";
client.ClientCredentials.Windows.ClientCredential.Password = "pw";
client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
MyService.GetListItemsResponse response = await client.GetListItemsAsync(listName, viewName, ndQuery, ndViewFields, rowLimit, ndQueryOptions, null);
If I try to set the Credentials with the logged on Windows user i get the following Unauthorized error:
The HTTP request is unauthorized with client authentication scheme
'Negotiate'. The authentication header received from the server was
'Negotiate,NTLM'.
client.ClientCredentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
Can you help me?
try this (use default credentials instead of specific):
private ListsSoapClient CreateListsSoapClient(string siteUrl, string siteUserName, string sitePassword)
{
var basicHttpBinding = new BasicHttpBinding
{
CloseTimeout = new TimeSpan(00, 5, 00),
OpenTimeout = new TimeSpan(00, 5, 00),
ReceiveTimeout = new TimeSpan(00, 5, 00),
SendTimeout = new TimeSpan(00, 5, 00),
TextEncoding = Encoding.UTF8,
MaxReceivedMessageSize = int.MaxValue,
MaxBufferSize = int.MaxValue,
Security =
{
Mode = BasicHttpSecurityMode.TransportCredentialOnly
},
ReaderQuotas =
{
MaxArrayLength = int.MaxValue,
MaxBytesPerRead = int.MaxValue,
MaxStringContentLength = int.MaxValue
}
};
basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
var url = string.Format("{0}/_vti_bin/Lists.asmx", siteUrl);
var address = new EndpointAddress(url);
var listsSoapClient = new ListsSoapClient(basicHttpBinding, address);
listsSoapClient.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Delegation;
listsSoapClient.ChannelFactory.Credentials.Windows.ClientCredential = new NetworkCredential(siteUserName, sitePassword);
listsSoapClient.ChannelFactory.Credentials.Windows.AllowNtlm = true;
return listsSoapClient;
}

How to connect Amazon API in c#

I have tried with below stuffs to connect Amazon API but failed to connect it I am getting error as "The remote server returned an error: (400) Bad Request". How to resolve this issue. Any help would be appreciated.
Code:
protected void btnAmazonItemSerach_Click(object sender, EventArgs e)
{
string associateId = "**************";
string accessKey = "*************";
string secretKey = "**************************";
string url = "http://webservices.amazon.com/onca/xml";
HttpWebRequest oRequest = (HttpWebRequest)HttpWebRequest.Create(url);
oRequest.Method = "GET";
oRequest.ContentType = "application/xml";
oRequest.Headers.Add("AWSAccessKeyId", accessKey);
oRequest.Headers.Add("AssociateTag", associateId);
oRequest.Headers.Add("Keywords", "Blueant s4");
oRequest.Headers.Add("Operation", "ItemSearch");
oRequest.Headers.Add("Service", "AWSECommerceService");
Encoding oEncod = new UTF8Encoding();
HMACSHA1 signature = new HMACSHA1();
signature.Key = oEncod.GetBytes(secretKey);
string sign = Convert.ToBase64String(signature.Key);
oRequest.Headers.Add("Signature", sign);
oRequest.Headers.Add("SearchIndex", "All");
oRequest.Headers.Add("Version", "2011-08-01");
string dateval = DateTime.Now.ToString();
oRequest.Headers.Add("Timestamp", dateval);
HttpWebResponse oResponse =(HttpWebResponse) oRequest.GetResponse();
StreamReader oreader =new StreamReader(oResponse.GetResponseStream());
var val = oreader.ReadToEnd();
XmlDocument oxmldoc = new XmlDocument();
oxmldoc.LoadXml(val);
XmlElement oxmlelem = (XmlElement)oxmldoc.GetElementsByTagName("Items")[0];
if (oxmlelem != null)
{
List<string> olistItems = new List<string>();
XmlNodeList olist = oxmldoc.GetElementsByTagName("Item");
for (int i = 0; i < olist.Count; i++)
{
string asi = olist[i].FirstChild.InnerText;
olistItems.Add(asi);
}
}
}

c# - How to Add Post Comment in LinkedIn?

I'm trying to add post comment in LinkedIn for the past one week
I've written this code
protected void Page_Load(object sender, EventArgs e)
{
string xmlContent = "<?xml version='1.0' encoding='UTF-8'?>";
xmlContent += "<comment><text>Check out</text></comment>";
byte[] databytes = Encoding.Default.GetBytes(xmlContent);
var credentials = new Hammock.Authentication.OAuth.OAuthCredentials
{
Type = OAuthType.AccessToken,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = "*********",
ConsumerSecret = "*********",
Token = "*********",
TokenSecret = "*********",
Version = "1.0"
};
var client = new Hammock.RestClient() { Authority = "http://api.linkedin.com/v1/posts" };
var request = new Hammock.RestRequest() { Path = "/56787878/comments", Method = Hammock.Web.WebMethod.Post, Timeout = new TimeSpan(0, 0, 5), Credentials = credentials };
request.AddHeader("Content-Type", "application/xml");
client.AddParameter("","");
client.AddPostContent(Encoding.UTF8.GetBytes(xmlContent));
//request.AddPostContent(Encoding.UTF8.GetBytes(xmlContent));
var response = client.Request(request);
Response.Write(response.Content);
}
I get an error in the below Xml format
<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>
<error>
<status>400</status>
<timestamp>1374494502579</timestamp>
<request-id>QM4MYPEKJJ</request-id>
<error-code>0</error-code>
<message>Couldn't parse message document: error: Unexpected end of file after null</message>\n</error>
Anybody handle this error? Thanks in advance.

Categories

Resources