C# error conect to webservice in SAP - c#

I have a web service in SAP and I have to make a C# client to te web service. I create the client but I receive an error from C#. Error is this :
Object reference not set to an instance of an object.
My source for client is this:
Uri uri = new Uri("http://address");
var address = new EndpointAddress(uri, EndpointIdentity.CreateSpnIdentity("teste"));
ServiceReference2.ZWS_PEP_ENVIO_MRZClient wsclient = new ServiceReference2.ZWS_PEP_ENVIO_MRZClient();
// wsclient.Endpoint.Binding.Scheme;
wsclient.ClientCredentials.UserName.UserName = "user_name";
wsclient.ClientCredentials.UserName.Password = "password";
wsclient.Endpoint.Address = address;
wsclient.Open();
ServiceReference2.ZwsPepEnvioMrz request = new ServiceReference2.ZwsPepEnvioMrz();
request.Descricao = descricaoField;
request.Mrz1 = mrz1Field;
request.Mrz2 = mrz2Field;
request.Numeroprocesso = numeroprocessoField;
request.Sn = snField;
request.Statusdatapreparation = statusdatapreparationField;
request.Versaodocumento = versaodocumentoField;
wsclient.ZwsPepEnvioMrz(request);
ServiceReference2.ZwsPepEnvioMrzResponse1 response = new ServiceReference2.ZwsPepEnvioMrzResponse1();
Resultado = response.ZwsPepEnvioMrzResponse.ToString();
textBox1.Text = Resultado;
wsclient.Close();
And the program terminates at
Resultado= response.ZwsPepEnvioMrzResponse.ToString()
Any ideas why?

this won't work:
wsclient.ZwsPepEnvioMrz(request);
ServiceReference2.ZwsPepEnvioMrzResponse1 response = new ServiceReference2.ZwsPepEnvioMrzResponse1();
you can't create a new response object yourself and expect it to contain any data. The response object should be the result from your web service call. I can't check this as the types are specific to your web service, but if the ws method ZwsPepEnviroMrz returns an object of type ServiceReference2.ZwsPepEnvioMrzResponse1 you should try this:
ServiceReference2.ZwsPepEnvioMrzResponse1 response = wsclient.ZwsPepEnvioMrz(request);
now the response variable should contain some data and this
Resultado = response.ZwsPepEnvioMrzResponse.ToString();
should work.

Related

Using C# REST API to send TriggeredSend email - created in Content Builder in SFMC in C# code

I am totally new to SalesForce Marketing cloud.
We have a “Triggered Send” created using “Content Builder” with an email body with HTML attribuites. For eg. %%=v(#EVENT)=%% Invitation
There is a Customer_key for this TriggerSendDefinition
I am using FuelSDK – to TriggerSend this email.
I have NUget Package manager install Fuel SDK in my Visual studio 2019 project.
The App.config has the “clientId” and “clientSecret” values in the FuelSDK config section.
Here is my code below.
public void TestInvitationSend(string CustomerKey)
{
string myName = "John Adams";
string myEvent = "13989";
string fullurl = baseAPIAuthURL + AuthTokenUrl; // Values passed in
NameValueCollection parameters = new NameValueCollection();
parameters.Add("clientId", clientId);
parameters.Add("clientSecret",clientSecret);
parameters.Add("accountId", "account123");
**ETClient myclient = new ETClient(parameters);**
TriggeredSendDefinition definition = new TriggeredSendDefinition();
definition.CustomerKey = customerKey;
//subscriber to whom email is sent
Subscriber subscriber = new Subscriber();
subscriber.EmailAddress = myTest#test.com;
subscriber.SubscriberKey = myTest#test.com;
TriggeredSend triggeredsend = new TriggeredSend();
triggeredsend.TriggeredSendDefinition = definition;
triggeredsend.AuthStub = myclient;
triggeredsend.CustomerKey = customerKey;
triggeredsend.Subscribers = new Subscriber[] { subscriber };
SendReturn results = triggeredsend.Send();
Console.WriteLine("Send Status: " + results.Status.ToString());
}
I am getting a 404 error at the line in “bold” when initializing myClient and unable to pass-in values dynamically. Could not find much documentation for email send through code.
Can you point me to some examples of TriggerSend emails using REST API ?
Thanks

Send web header collection

How to send web header collection from rest Service to remoting service?
I have tried to send web headers using below code but its not working.
System.Net.WebRequest request = base.GetWebRequest(uri);
request.Headers.Add("myheader", "myheader_value");
You can try the below sample
public RemotingServiceClient serviceClient = new RemotingServiceClient();
public void Demo()
{
using (OperationContextScope scope = new OperationContextScope(serviceClient.InnerChannel))
{
MessageHeader<string> header = new MessageHeader<string>("HeaderValue1");
var v1 = header.GetUntypedHeader("HeaderName1", "RemotingService");
OperationContext.Current.OutgoingMessageHeaders.Add(v1);
header = new MessageHeader<string>("HeaderValue2");
var v2 = header.GetUntypedHeader("HeaderName2", "RemotingService");
OperationContext.Current.OutgoingMessageHeaders.Add(v2);
//IMP: To send headers make sure to call service in this block only.
//Keep unique uri name "RemotingService"
return serviceClient.MyRemotingServiceCall();
}
}
It's working for me as expected

SOAP service on Java returns incorrect types in Response

I use a third-party server written in Java.
WSDL is taken with the style of rpc/literal.
Connection to the service is initialized as follows:
private static MLPortChannel GetMerlionClient()
{
BasicHttpsBinding binding = new BasicHttpsBinding(BasicHttpsSecurityMode.Transport);
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
binding.MaxReceivedMessageSize = 4096000;
EndpointAddress adress = new EndpointAddress(new Uri(#"https://apitest.merlion.com/rl/mlservice3"));
ChannelFactory<MLPortChannel> factory = new ChannelFactory<MLPortChannel>(binding, adress);
factory.Credentials.UserName.UserName = mlLogin;
factory.Credentials.UserName.Password = mlPassword;
return factory.CreateChannel();
}
It is works correctly only for one method and returns the correct data type and the data.
When I call other methods, they returns error as:
"Can not convert an object of type " ... MLService3RLTest.CatalogResult [] " of the type " ... MLService3RLTest.ShipmentDatesResult []"
In this example return type must be ShipmentDatesResult[].
I tested the service via special tool. All requests and responses is correct and returned correct XML.
What may be the cause of this error? Perhaps something needs to be configured for SOAP service. Maybe some magic option with right value?
If, instead of referring to the service, make a web link which uses the technology of web services .Net FrameWork 2.0 what works
var client = new WpfApplication1.com.merlion.apitest.MLService();
var myCredentials = new System.Net.NetworkCredential(Логин, Пароль);
// Create a webrequest with the specified URL.
var url = "https://apitest.merlion.com/rl/mlservice3";;
client.Credentials = myCredentials.GetCredential(new Uri(url), "Basic");
textBox.AppendText(client.helloWorld("Привет"));
var ответ = client.getCatalog("N1");
var массив = new string[] { "" };
var rz = client.getItems("N10100", массив, "", 0, 2, "");
add
client.PreAuthenticate = true;

C# can't make http request from website or service

I am trying to write a simple POST request to google-analytics server, here is my code :
using (var client = new System.Net.WebClient())
{
var values = new System.Collections.Specialized.NameValueCollection();
//values["v"] = "1";
//values["t"] = "event";
//values["tid"] = trackingID;
//values["cid"] = clientID;
//values["ec"] = eventCategory.ToString();
//values["ea"] = eventAction.ToString();
//values["el"] = eventAction.ToString();
var endpointAddress = "http://www.google-analytics.com/collect";
var response = client.UploadValues(endpointAddress, values);
var responseString = System.Text.Encoding.Default.GetString(response);
}
This code works fine in a console application, but not on a website application (hosted on IIS or run on Visual Studio 2013) or in a WCF (likewise).
I checked using
WindowsIdentity.GetCurrent()
in both the site, the WCF service and the application, everytime the DOMAIN and USERNAME are my own, so I don't think that is the problem. I have tried using .NET impersonation without success.
I've tried setting the application pool identity to my user, ApplicationPoolIdentity or NetworkService, without success.
I've also tried changing the authentication mode to AnonymousUser or Windows Authentication. I've tried changing the physical access path, without success.
I'm at work behind a proxy, at home I've tried it and it worked well.
Does anyone has an idea as to why it doesn't work ?
Try supplying the proxy details when making the request. Assuming you are behind a proxy.
using (var client = new System.Net.WebClient())
{
WebProxy proxy = new WebProxy("localproxyIP:8080", true);
proxy.Credentials = new NetworkCredential("domain\\user", "password");
WebRequest.DefaultWebProxy = proxy;
client.Proxy = proxy;
var values = new System.Collections.Specialized.NameValueCollection();
//values["v"] = "1";
//values["t"] = "event";
//values["tid"] = trackingID;
//values["cid"] = clientID;
//values["ec"] = eventCategory.ToString();
//values["ea"] = eventAction.ToString();
//values["el"] = eventAction.ToString();
var endpointAddress = "http://www.google-analytics.com/collect";
var response = client.UploadValues(endpointAddress, values);
var responseString = System.Text.Encoding.Default.GetString(response);
}

Calling a web service from a .net windows application

I need to call a web service from a .net web application, here is my code:
LoginRequest req = new LoginRequest();
LoginRequestBody reqBody = new LoginRequestBody();
reqBody.username = txtUsername.Text;
reqBody.password = txtPassword.Text;
req.Body = reqBody;
LoginResponse resp = new LoginResponse();
LoginResponseBody respBody = new LoginResponseBody();
resp.Body = respBody;
MessageBox.Show(respBody.LoginResult.ToString());
The message returned is always false, while the message from the web service (when I test directly) is returning true, what's wrong with my code?
You are not actually calling the web-service! You should not be creating a response directly - you should be asking the web-service for one, e.g.
LoginResponse response = LoginService.Login(req);
However, I don't know what your service is actually called, so the above is just a sample.

Categories

Resources