Webservice method result issue via SOAP - c#

Hello I have this code below in which I connected through webservice cz.mfcr.adisrws (pictured) and I need to get some of these values according to what was called in CreateSoapEnvelope()
with this code:
namespace spolehlivost_platce
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
CallWebService();
}
private void Form1_Load(object sender, EventArgs e)
{
}
public static XmlDocument CreateSoapEnvelope()
{
XmlDocument soapEnvelop = new XmlDocument();
soapEnvelop.LoadXml
(#"<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/""><soapenv:Body><StatusNespolehlivyPlatceRequest xmlns=""http://adis.mfcr.cz/rozhraniCRPDPH/""><dic>28156609</dic></StatusNespolehlivyPlatceRequest></soapenv:Body></soapenv:Envelope>");
return soapEnvelop;
}
protected virtual WebRequest CreateRequest(ISoapMessage soapMessage)
{
var wr = WebRequest.Create(soapMessage.Uri);
wr.ContentType = "text/xml;charset=utf-8";
wr.ContentLength = soapMessage.ContentXml.Length;
wr.Headers.Add("SOAPAction", soapMessage.SoapAction);
wr.Credentials = soapMessage.Credentials;
wr.Method = "POST";
wr.GetRequestStream().Write(Encoding.UTF8.GetBytes(soapMessage.ContentXml), 0, soapMessage.ContentXml.Length);
return wr;
}
private static HttpWebRequest CreateWebRequest(string url, string action)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Headers.Add("SOAPAction", action);
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
return webRequest;
}
private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
}
public static void CallWebService()
{
var _url = "http://schemas.xmlsoap.org/soap/envelope/"; //issue
var _action = cz.mfcr.adisrws.InformaceOPlatciType(); //issue
XmlDocument soapEnvelopeXml = CreateSoapEnvelope();
HttpWebRequest webRequest = CreateWebRequest(_url,_action);
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
// begin async call to web request.
IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);
// suspend this thread until call is complete. You might want to
// do something usefull here like update your UI.
asyncResult.AsyncWaitHandle.WaitOne();
// get the response from the completed web request.
string soapResult;
using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
{
using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
{
soapResult = rd.ReadToEnd();
}
Console.WriteLine(soapResult);
}
}
I dont know what should be in this line:
var _url = "http://schemas.xmlsoap.org/soap/envelope/"; //issue
var _action = cz.mfcr.adisrws.InformaceOPlatciType(); //issue
May someone help me solve this out?
Thanks in advance.
I receive this exception:
The remote server returned an error: (405) Method Not Allowed
I followed this tutorial.

The _url is the URL of the service - it is the URL (the 'address') where you're hosting your service - if you're hosting it yourself, it should probably be something like:
_url = "http://localhost/MyService/MyService.asmx"
or if you're using the service that somebody else already hosted, then you have to see the URL they provided for it, and put that value in. The value you're currently using (http://schemas.xmlsoap.org/soap/envelope/) is just a layout of the schema for the data, not the actual URL, and esp. not the service itself (it's maybe confusing because of the http, but it's just a way of 'describing' data)
The _action part - that's the method on the service that you're trying to call, and that should also be a string, for example:
_action = "http://localhost/MyService/MyService.asmx?op=HelloWorld"
You have to think about what you are trying to achieve and who-does-what-and-where...

Related

The remote server returned an error: (405) Method Not Allowed service request and "Request method 'POST' not supported"

I have service client application written in C# where I create a service request as a soap XML as following:
var _url = "http://localhost:8082/tartsend";
var _action = "http://rep.oio.no/getTest";
StartSend startSend = new tartSend();
Envelope soapEnvelopeXml = StartSend.StartSendMethod();
HttpWebRequest webRequest = CreateWebRequest(_url, _action);
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);
asyncResult.AsyncWaitHandle.WaitOne();
string soapResult;
using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
{
using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
{
soapResult = rd.ReadToEnd();
}
Console.Write(soapResult);
}
}
private static XmlDocument CreateSoapEnvelope()
{
XmlDocument soapEnvelopeDocument = new XmlDocument();
return soapEnvelopeDocument;
}
private static HttpWebRequest CreateWebRequest(string url, string action)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Headers.Add("SOAPAction", action);
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
return webRequest;
}
private static void InsertSoapEnvelopeIntoWebRequest(Envelope soapEnvelopeXml,
HttpWebRequest webRequest)
{
var xmlString = string.Empty;
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Envelope));
var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +
"//Sendservice.xml";
System.IO.FileStream file = System.IO.File.Create(path);
using (StringWriter textWriter = new StringWriter())
{
xmlSerializer.Serialize(file, soapEnvelopeXml);
xmlString = textWriter.ToString();
}
Console.WriteLine(xmlString);
}
Envelop is the class object that contains the Body, Header, and the other objects/ attributes. I serialize it in "InsertSoapEnvelopeIntoWebRequest" method and send it to the service side.
the server side is a simple method that suppose to send OK as response and nothing else. The server side service code is in jave spring boot as following:-
#SpringBootApplication
#EnableWebMvc
#RestController
public class TestController {
#RequestMapping(value = "/getslutsend", method=RequestMethod.GET,
consumes={MediaType.APPLICATION_XML_VALUE, MediaType.TEXT_XML_VALUE,
MediaType.APPLICATION_JSON_VALUE, MediaType.TEXT_PLAIN_VALUE})
public ResponseEntity<?> readFromtest(#RequestBody String test) {
return new ResponseEntity<String>(HttpStatus.OK);
}
public static void main(String[] args) {
SpringApplication.run(TestController.class, args);
}
}
I'm not sure what I'm doing wrong to get the above errors mentioned in the title of this post. I get " (405) Method Not Allowed" and Request method not supported.
You have the RequestMethod.GET in your request mapping and the #RequestBody in parameter annotation.
Normally, you should avoid this combination, please use either RequestMethod.POST with #RequestBody, or RequestMethod.GET without the #RequestBody.

Can't get response from SOAP 1.2 Web Request in C# Console app

I am unable to hit a SOAP 1.2 web service with C# code. I followed the code in this example, Web Service SOAP Call
It does not work for me. My web service URL works in SOAPUI but I can't get a response in my C# code. I get a "500 Internal error." The status reads "ProtocolError."
I am running this from my Visual Studio 2017 editor.
using System;
using System.IO;
using System.Net;
using System.Xml;
namespace testBillMatrixConsole
{
class Program
{
static void Main(string[] args)
{
string _url = #"https://service1.com/MSAPaymentService/MSAPaymentService.asmx";
var _action = #"http://schemas.service1.com/v20060103/msapaymentservice/AuthorizePayment";
try
{
XmlDocument soapEnvelopeXml = CreateSoapEnvelope();
HttpWebRequest webRequest = CreateWebRequest(_url, _action);
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
// begin async call to web request.
IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);
// suspend this thread until call is complete. You might want to
// do something usefull here like update your UI.
asyncResult.AsyncWaitHandle.WaitOne();
// get the response from the completed web request.
string soapResult;
using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
{
using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
{
soapResult = rd.ReadToEnd();
}
Console.Write(soapResult);
}
}
catch (WebException ex)
{
throw;//ex.Message.ToString();
}
}
private static XmlDocument CreateSoapEnvelope()
{
XmlDocument soapEnvelopeDocument = new XmlDocument();
soapEnvelopeDocument.LoadXml(#"<soap:Envelope xmlns:soap=""http://www.w3.org/2003/05/soap-envelope"" xmlns:msap=""http://schemas.service1.com/v20060103/msapaymentservice""><soap:Body><msap:AuthorizePayment><!--Optional:--><msap:clientPaymentId>?</msap:clientPaymentId><msap:amount>?</msap:amount><msap:method>?</msap:method><!--Optional:--><msap:parameters><!--Zero or more repetitions:--><msap:PaymentParameter><!--Optional:--><msap:Name>?</msap:Name><!--Optional:--><msap:Value>?</msap:Value></msap:PaymentParameter></msap:parameters></msap:AuthorizePayment></soap:Body></soap:Envelope>");
return soapEnvelopeDocument;
}
private static HttpWebRequest CreateWebRequest(string url, string action)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Headers.Add("SOAPAction", action);
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
return webRequest;
}
private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
}
}
}

"Stream not Writable" error when using StreamWriter in loop

I'm trying to write a tool in C# to help QA some network issues, and am running into a problem. The program is supposed to send a query in JSON format to the server every second.
Currently, it works once, but on the second attempt to send the query, I get an exception because the
"Stream was not writable."
Here's my code:
public partial class Form1 : Form
{
Timer timer1;
String query;
String result;
HttpWebRequest request;
StreamWriter writeData;
StreamReader readData;
HttpWebResponse response;
public Form1()
{
InitializeComponent();
timer1 = new Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 1000;
File.Delete(AppDomain.CurrentDomain.BaseDirectory + "log.txt");
logOutput.ReadOnly = true;
request = (HttpWebRequest)WebRequest.Create("a URL goes here");
request.ContentType = "application/json";
request.Method = "POST";
query = "{some json stuff goes here}";
}
private void startButton_Click(object sender, EventArgs e)
{
if (!timer1.Enabled)
{
timer1.Start();
startButton.Text = "Stop";
}
else
{
timer1.Stop();
startButton.Text = "Start";
}
}
private void timer1_Tick(object sender, EventArgs e)
{
writeData = new StreamWriter(request.GetRequestStream());
writeData.Write(query);
writeData.Flush();
writeData.Close();
response = (HttpWebResponse)request.GetResponse();
readData = new StreamReader(response.GetResponseStream());
result = readData.ReadToEnd();
logOutput.Text = result;
File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + "log.txt", result + "\r\n");
}
}
}
Anyone know what I'm doing wrong?
First off, Stop with the global variables. Move the streamwriter, streamreader, httpwebresponse etc into the actual tick method.
Anything that implements IDisposable, which most of that stuff does, should be very local variables that aren't hanging around and are wrapped up in using clauses.
Basically your request object is closed out once your method has finished.
Something like this will work a LOT better:
private void timer1_Tick( object sender, EventArgs e ) {
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("a URL goes here");
request.ContentType = "application/json";
request.Method = "POST";
String query = "{some json stuff goes here}";
String result = String.Empty;
using ( StreamWriter writeData = new StreamWriter(request.GetRequestStream()) ) {
writeData.Write(query);
writeData.Flush();
using ( HttpWebResponse response = (HttpWebResponse)request.GetResponse() ) {
using ( StreamReader readData = new StreamReader(response.GetResponseStream()) ) {
result = readData.ReadToEnd();
}
}
}
logOutput.Text = result;
File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + "log.txt", result + "\r\n");
}
}
So I presume it's the writeData.Write(query) that's throwing? request.GetRequestStream() should only be writeable until the request is actually sent, which I believe is done when you call request.GetResponse(). So it works on the first tick, but then sends the request and can't write the second time.
Are you trying to send the request multiple times? You would need to reinitialize the request object.
Similar issue causes if you do not reinitialize the request. As mentioned by ryachza i have pushed request initialization inside loop and it worked for me.
foreach (String item in DATA)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "POST";
request.ContentType = "application/json";
using (Stream webStream = request.GetRequestStream())
using (StreamWriter requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII))
{
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
Object routes_list =
json_serializer.DeserializeObject(item);
requestWriter.Write(item);
}
WebResponse webResponse = request.GetResponse();
using (Stream webStream = webResponse.GetResponseStream() ?? Stream.Null)
using (StreamReader responseReader = new StreamReader(webStream))
{
response.Add(responseReader.ReadToEnd());
}
}

Fetching Result from HTTP Response

I have the following C# class which initiates an HTTP request from a Windows Phone to a server:
public class Request
{
public string data;
public string result;
public Request()
{
}
public void doRequest(string parameters, string URL)
{
data = parameters;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
}
public void GetRequestStreamCallback(IAsyncResult callbackResult)
{
HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
Stream postStream = myRequest.EndGetRequestStream(callbackResult);
byte[] byteArray = Encoding.UTF8.GetBytes(data);
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), myRequest);
}
public void GetResponsetStreamCallback(IAsyncResult callbackResult)
{
HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream());
result = httpWebStreamReader.ReadToEnd();
}
Now, in my main class, I call the doRequest method to do an HTTP request from the Windows Phone:
Request req = new Request();
req.doRequest("function=LogIn&username=" + username + "&password=" + password, "http://localhost:4000/Handler.ashx");
When calling this method, how can I get the result (the result variable) from the server since it is received in the GetResponsetStreamCallback method and not in the doRequest method?
You have several possibilities. One would be to define property to make the result accessible outside. Define
public class Request
{
public string Result
{
get{
if(result != null && !string.IsNullOrEmpty(result))
return result;
return null;
}
}
...
}
You might create an event and have objects subscribe to it, so you can notice them when the asynchronous request has ended. Or make your calls synchronous, which is a little easier to do, as you don't have synchronize your calls and the requests from other objects.

What should be the redirect URI for yammer when using a windows phone 8 app?

I am using the following URL for OAuth2.0
https://www.yammer.com/dialog/oauth?client_id=client_id&redirect_uri=redirect_uri&response_type=token
and passing this to the Post().
Result: My App does not run and waits for the resources. i think probably it is not getting the HTTP response.
Please validate and let me know what i have done wrong in here?
private void Post(string address)
{
System.Uri targetUri = new System.Uri(address);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(targetUri);
request.Method = "POST";
request.BeginGetResponse(new AsyncCallback(ReadWebRequestCallback), request);
}
// STEP4 STEP4 STEP4
private void ReadWebRequestCallback(IAsyncResult callbackResult)
{
HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
HttpWebResponse myResponse = (HttpWebResponse)myRequest.EndGetResponse(callbackResult);
string results;
using (StreamReader httpwebStreamReader = new StreamReader(myResponse.GetResponseStream()))
{
results = httpwebStreamReader.ReadToEnd();
//TextBlockResults.Text = results; //-- on another thread!
SkyDriveContent test = new SkyDriveContent();
test.Name = results;
str_results = results;
Dispatcher.BeginInvoke(() => ContentList.Add(test));
}
myResponse.Close();
}

Categories

Resources