I am trying to create a file upload in a flex/air application that sends information to a .NET wcf SOAP webservice. The file upload also has to have progress indicating events. The service uses a Stream as a MessageBodyMember to allow streaming upload. My input looks a little like this:
[MessageContract]
public class SendFileRequestMessage : IDisposable
{
public string UserName;
[MessageBodyMember(Order = 1)]
public Stream FileData;
}
and the service looks like this:
public interface IFileTransferService
{
[OperationContract]
SendFileResponseMessage SendFile(SendFileRequestMessage request);
}
Now when i create a proxy class in VS2010 i get a Stream object for FileData. If I do the same in Flash Builder 4.7 the FileData is interpreted as a ByteArray. I already looked into FileUpload and UrlLoader in my client but i can't get the body member set. My action script now looks like this
not working
var dataToSave:XML = <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:q0="http://mystuff/uploadservice/v1"><soapenv:Body><q0:SendFile/></soapenv:Body></soapenv:Envelope>
var request:URLRequest = new URLRequest("http://localhost:31454/Uploadhandler.svc");
request.requestHeaders = new Array(new URLRequestHeader("SOAPAction", "http://mystuff/uploadservice/v1/IFileTransferService/SendFile"));
request.data = dataToSave;
request.contentType = "text/xml; charset=utf-8";
request.method = URLRequestMethod.POST;
var loader:URLLoader = new URLLoader();
loader.load(request);
So how can do a streaming file upload to a soap service from flex? Any help would be very appreciated.
I'm not familiar with .NET SOAP model, but if it expects standard http content dispositions for file data you can try getting FileReference object for your file and then pass your URLRequiest in its upload method. In your case this could be like
... Create class level variable ...
var fr:FileReference = new FileReference();
... Obtain file reference somewhere ...
//Set handlers for Filereference events
fr.browse(); //Obtain actual file reference
... Somewhere in selectHandler chain....
var dataToSave:XML = <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:q0="http://mystuff/uploadservice/v1"><soapenv:Body><q0:SendFile/></soapenv:Body></soapenv:Envelope>
var request:URLRequest = new URLRequest("http://localhost:31454/Uploadhandler.svc");
request.requestHeaders = new Array(new URLRequestHeader("SOAPAction", "http://mystuff/uploadservice/v1/IFileTransferService/SendFile"));
request.data = dataToSave;
request.contentType = "text/xml; charset=utf-8";
request.method = URLRequestMethod.POST;
//Do POST
fr.upload(request);
This Documentation contains examples for using FileReference.
Related
I have XML Web API like this
http://test/REST?hiInstanceId=7
XML parameters
<request_info>SALE</request_info><location_id>36</location_id>
<from_dt>01-JUN-22</from_dt><to_dt>10-JUN-22</to_dt>
how to get the response from the XML web API?
how to get response from the xml web Api
To make the Asp.net Core API return the XML format response. We need to configure XML formatters implemented using XmlSerializer, call AddXmlSerializerFormatters:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers()
.AddXmlSerializerFormatters();
Then, in the API controller, use the [Produces] attribute to specify a format.
[Route("api/[controller]")]
[ApiController]
public class TodoController : ControllerBase
{
[HttpGet]
[Produces("application/xml")]
public TestModel GetCustomers( )
{
return new TestModel()
{
request_info = "Sale",
location_id = 36,
from_dt = "01-JUN-22",
to_dt = "10-JUN-22"
};
}
}
Then, use the following code to call the API method and get the XML response:
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(new Uri("https://localhost:44374/api/todo"));
httpRequest.ContentType = "application/xml";
httpRequest.Method = "Get";
using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse())
{
using (Stream stream = httpResponse.GetResponseStream())
{
string xml = (new StreamReader(stream)).ReadToEnd(); //get the XML response
//Using XMLSerializer to convert the XML response to the object.
XmlSerializer serializer = new XmlSerializer(typeof(TestModel));
StringReader rdr = new StringReader(xml);
var result = (TestModel)serializer.Deserialize(rdr);
}
}
The debug screenshot like this:
I'm using Protobuf-net to try and send a serialized object to a webapplication that I'm running in another project. The Serializer.Serialize<T>() method takes a Stream (to write to) and and instance of T (in this case, a list of a few objects that I set up to work with protobuf-net)
How do I go about doing this? Do I need to write to a file or can I send the stream as postdata somehow? Below you can see I'm using a string as the postdata.
My execute post method
public static void ExecuteHttpWebPostRequest(Uri uri,string postdata, int requestTimeOut, ref string responseContent)
{
if (string.IsNullOrEmpty(uri.Host))// || !IsConnectedToInternet(uri))
return;
var httpWebReq = (HttpWebRequest)WebRequest.Create(uri);
var bytePostData = Encoding.UTF8.GetBytes(postdata);
httpWebReq.Timeout = requestTimeOut*1000;
httpWebReq.Method = "POST";
httpWebReq.ContentLength = bytePostData.Length;
//httpWebReq.ContentType = "text/xml;charset=utf-8";
httpWebReq.ContentType = "application/octet-stream";
//httpWebReq.TransferEncoding=
//httpWebReq.ContentType = "application/xml";
//httpWebReq.Accept = "application/xml";
var dataStream = httpWebReq.GetRequestStream();
dataStream.Write(bytePostData, 0, bytePostData.Length);
dataStream.Close();
var httpWebResponse = (HttpWebResponse)httpWebReq.GetResponse();
// Get the stream associated with the response.
var receiveStream = httpWebResponse.GetResponseStream();
// Pipes the stream to a higher level stream reader with the required encoding format.
var readStream = new StreamReader(receiveStream,Encoding.Default);
responseContent = readStream.ReadToEnd();
httpWebResponse.Close();
}
You can just serialize to the request:
Serializer.Serialize(dataStream, obj);
And equally, you can deserialize from receiveStream, if you choose.
Note, however, that protobuf data is not text, and should not be treated as such - very bad things happen if you try that.
This is the code i have written to get the xml of one url but it says
"Data at the root level is invalid" with any url.. Can someone specify why?
XmlDocument xdoc = new XmlDocument();//xml doc used for xml parsing
xdoc.LoadXml("http://latestpackagingnews.blogspot.com/feeds/posts/default");//loading XML in xml doc
XmlNodeList xNodelst = xdoc.DocumentElement.SelectNodes("entry");//reading node so that we can traverse thorugh the XML
Response.Write(xNodelst);
You need to first download your xml data using WebClient class
string downloadedString;
System.Net.WebClient client = new System.Net.WebClient();
downloadedString = client.DownloadString("http://latestpackagingnews.blogspot.com/feeds/posts/default");
//Now write this string as an xml
//I think you can easily do it with XmlDocument class and then read it
The xdoc.LoadXml can not for read url, change it to xdoc.Load and it will work.
You can also read : Using Returned XML with C#
XmlDocument.LoadXml method awaits XML-text, but not the source URL.
First, download page content into string and then pass it to LoadXml. Here is how you can download:
public string GetUrlContent(string url)
{
var request = (HttpWebRequest)HttpWebRequest.Create(url);
var response = (HttpWebResponse)request.GetResponse();
var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
var content = reader.ReadToEnd();
reader.Close();
response.Close();
return content;
}
In your case it would be:
var content = GetUrlContent("http://latestpackagingnews.blogspot.com/feeds/posts/default");
var doc = new XmlDocument();
doc.LoadXml(content);
I have a webservice which i need to call in .net application. The link looks like this.
http://www.contoso.com/student?id=12345
This will work only when its called like this. For rest of the this i dont have access. ie if i call it on a browser without the querystring it will not work. but with querystring it will return an XML data.
Now, when i call this in the .net application its not working?
How can I call this in a .NET application?
The Normal Webservice Importing methods are not working since it needs a querystring with value and we dont have access to the links which doesnt have the querystring.
How are you currently trying to download it?
A very simple way to do this is to use the HttpWebRequest and HttpWebResponse classes;
public XmlDocument GetStudentXml(int studentId)
{
XmlDocument targetXml = new XmlDocument();
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(String.Format("http://www.contoso.com/student?id={0}", studentId));
webRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
webRequest.Accept = "text/xml";
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
using (Stream responseStream = webResponse.GetResponseStream())
{
XmlTextReader reader = new XmlTextReader(responseStream);
targetXml.Load(reader);
reader.Close();
}
webResponse.Close();
return targetXml;
}
This method simply creates a HttpWebRequest, initializes it with the URL (via String.Format so as to append the student id), some windows credentials and the expected content type.
It then calls the remote address via the GetResponse method. The response is then loaded into a stream, and an XmlTextReader is used to load the Xml data from the response stream into the XmlDocument, which is then returned to the caller.
You can also use WebClient and XDocument to achieve the same thing:
string url = String.Format("http://www.contoso.com/student?id={0}", studentId);
string remoteXml;
using (var webClient = new WebClient())
{
remoteXml = webClient.DownloadString(url);
}
XDocument doc = XDocument.Parse(remoteXml);
i want to send xml file with userid and password over HTTPs and then send all other xml file on HTTP using POST method and get the response as a xml file back. in ASP.NET (with vb.net preferred)
The url to which i want to send my xml file is:http://www.hostelspoint.com/xml/xml.php
exect xml file pettern is:
<?xml version="1.0" encoding="UTF-8"?>
<OTA_PingRQ xmlns="http://www.opentravel.org/OTA/2003/05"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.opentravel.org/OTA/2003/05OTA_PingRQ.xsd"
TimeStamp="2003-03-17T11:09:47-05:00"
Target="Production" Version="1.001" PrimaryLangID="en"
EchoToken="testtoken12">
<EchoData>Hello</EchoData>
</OTA_PingRQ>
You should check out the WCF REST Starter Kit, and watch the screencast on HTTP Plain XML (POX) Services which explains step by step how to do just that - create a WCF REST service that will accept and process a plain XML stream.
All the WCF and WCF REST screencasts by Pluralsight are highly recommended! It's excellent material on how to get started and work with WCF.
In addition to that, the MSDN WCF Developer Center is your first point of contact for any questions or more information on WCF and WCF REST.
i don't know why u removed correct answer from here but yesterday i got correct answer here. and it is:- (can any one tell me how to do same with HTTPS protocol?)
string targetUri = "http://www.hostelspoint.com/xml/xml.php";
System.Xml.XmlDocument reqDoc = new System.Xml.XmlDocument();
reqDoc.Load(Server.MapPath("~\\myfile.xml"));
string formParameterName = "OTA_request";
string xmlData = reqDoc.InnerXml;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUri);
string sendString = formParameterName + "=" + HttpUtility.UrlEncode(xmlData);
byte[] byteStream;
byteStream = System.Text.Encoding.UTF8.GetBytes(sendString);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteStream.LongLength;
using (Stream writer = request.GetRequestStream())
{
writer.Write(byteStream, 0, (int)request.ContentLength);
writer.Flush();
}
HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
string respStr = "";
if (request.HaveResponse)
{
if (resp.StatusCode == HttpStatusCode.OK || resp.StatusCode == HttpStatusCode.Accepted)
{
StreamReader respReader = new StreamReader(resp.GetResponseStream());
respStr = respReader.ReadToEnd(); // get the xml result in the string object
XmlDocument doc = new XmlDocument();
doc.LoadXml(respStr);
Label1.Text = doc.InnerXml.ToString();
}
}
Yes, you can do same thing using HTTPS protocol. You have to add this code before request:
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, X509Certificate certificate, X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
bool validationResult = true;
//
// policy code here ...
//
return validationResult;
};