Common class for HttpWebRequests - WP8 - windows-phone-8

For making the http calls I use the functions
private void DoneClicked(object sender, RoutedEventArgs e)
{
string emailText = emailTBox.Text;
string oldPass = oldPasswordPBox.Password;
string newPass = newPasswordPBox.Password;
if (emailText == "" || oldPass == "" || newPass == "")
{
PassDiaTB1.Text = "Oops..";
PassDiaTB2.Text = "Some field is empty";
PassiveDialogs.Visibility = System.Windows.Visibility.Visible;
}
else
{
var data = new { user = new { email = emailText, old_password = oldPass, new_password = newPass } };
jsonStringChild = JsonConvert.SerializeObject(data, Formatting.Indented);
Debug.WriteLine(jsonStringChild);
string uri = CycleManager.HTTP_URI + "change-password";
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = CycleManager.HTTP_PUT;
request.ContentType = "application/json";
request.Accept = "application/json";
bool IsNetWork = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
if (!IsNetWork)
{
PassDiaTB1.Text = "Oops..";
PassDiaTB2.Text = "Check your internet connectivity";
PassiveDialogs.Visibility = System.Windows.Visibility.Visible;
}
else
{
request.BeginGetRequestStream(new AsyncCallback(PostCallBack), request);
}
}
}
void PostCallBack(IAsyncResult result)
{
// End the stream request operation
HttpWebRequest request = result.AsyncState as HttpWebRequest;
Stream postStream = request.EndGetRequestStream(result);
byte[] byteArray = Encoding.UTF8.GetBytes(jsonStringChild);
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
request.BeginGetResponse(new AsyncCallback(GetResponseStreamCallBack), request);
}
void GetResponseStreamCallBack(IAsyncResult callBackResult)
{
try
{
HttpWebRequest request = callBackResult.AsyncState as HttpWebRequest;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callBackResult);
statusCode = (int)response.StatusCode;
if (statusCode == 200)
{
string result = "";
using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
{
result = httpWebStreamReader.ReadToEnd();
}
string json = result;
Dictionary<string, string> token = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
string email = token["email"];
string auth_token = token["auth_token"];
CycleManager cycMan = CycleManager.Instance;
cycMan.AuthToken = auth_token;
Dispatcher.BeginInvoke(ShowPassiveDialog);
}
}
catch (WebException e)
{
if (e.Response != null)
{
HttpWebResponse aResp = e.Response as HttpWebResponse;
if (aResp != null)
{
statusCode = (int)aResp.StatusCode;
}
if (statusCode == 401)
{
string result = "";
using (StreamReader httpWebStreamReader = new StreamReader(aResp.GetResponseStream()))
{
result = httpWebStreamReader.ReadToEnd();
}
string json = result;
var definition = new { message = "" };
var parsedStrings = JsonConvert.DeserializeAnonymousType(json, definition);
message = parsedStrings.message;
Dispatcher.BeginInvoke(ShowPassiveDialog);
}
if (statusCode == 500)
{
string result = "";
using (StreamReader httpWebStreamReader = new StreamReader(aResp.GetResponseStream()))
{
result = httpWebStreamReader.ReadToEnd();
}
string json = result;
var definition = new { message = "" };
var parsedStrings = JsonConvert.DeserializeAnonymousType(json, definition);
message = parsedStrings.message;
Dispatcher.BeginInvoke(ShowPassiveDialog);
}
}
}
}
The same three calls are made in several pages, changing the parameters and methods. I am trying to create a common class which can be called to make http calls. But these functions have differnt return types and I'm not able generalize all this??
Any help would be appreciated.

May this will guide you. I create a wrapper class for such kind of work, its help me a lot and reduce lots of code and effort.
public class CommanHttpRequest
{
private string ACCEPT="application/json";
private string ContentType ="application/json";
private string POST_METHOD="POST";
private string GET_METHOD="GET";
public string IsException { get; set; }
public HttpWebRequest GetHttpRequest(string url,string header1, string header2)
{
HttpWebRequest getRequest = HttpWebRequest.CreateHttp(url);
getRequest.Accept =this.ACCEPT;
getRequest.ContentType = this.ACCEPT;
getRequest.Headers["Header1"] = header1;
getRequest.Headers["Header2"] = header2;
getRequest.Method = this.POST_METHOD;
return getRequest ;
}
public void GetRequestResponse(Action<your type> callback, IAsyncResult asyncResult, string envelop)
{
try
{
UTF8Encoding encoding = new UTF8Encoding();
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
Stream body = request.EndGetRequestStream(asyncResult);
//write body if any
byte[] formBytes = encoding.GetBytes(envelop);
body.Write(formBytes, 0, formBytes.Length);
body.Close();
request.BeginGetResponse(result =>
{
try
{
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
using (Stream data = response.GetResponseStream())
{
using (var reader = new StreamReader(data))
{
string jsonString = reader.ReadToEnd();
MemoryStream memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(jsonString));
DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(your type));
var parseddata = dataContractJsonSerializer.ReadObject(memoryStream) as your type;
callback(parseddata );
}
}
}
catch (WebException ex)
{
IsException = ex.Message;
//I asume your type =List<abc>();
callback(new List<abc>());
}
}, request);
}
catch (Exception ex)
{
IsException = ex.Message;
callback(new List<abc>());
}
}
}
public class abc
{
public void TestRequest()
{
string url="some url";
CommanHttpRequest requestObj = new CommanHttpRequest();
HttpWebRequest testRequest = _requestObj.GetHttpRequest(url, password, email);
//if there some body in request
string envelope = "{\"requestType\":" + requestType + "}";
testRequest .BeginGetRequestStream(result =>
{
requestObj.GetRequestResponse(resultData =>
{
ProcessServiceResponse(resultData);
}, result, envelope);
}, testRequest );
}
public void ProcessServiceResponse(List<abc> abcdata)
{
//abcdata is your data
}
}

Related

decompress Apache httpclient results

I'm using Apache HTTPClient 4.5.3 to make some HTTP requests, but I am getting a g-zipped response I have tried many things I found online but non of them worked. I still get gibberish when I print the response. Below are the relevant code. What do I need to do to get a human readable response?
static public CloseableHttpClient CreateHttpClient() {
// return
// HttpClients.custom().disableAutomaticRetries().setHttpProcessor(HttpProcessorBuilder.create().build())
// .build();
return HttpClientBuilder.create().disableAutomaticRetries()
.setHttpProcessor(HttpProcessorBuilder.create().build()).build();
}
static public RequestConfig GetConfig() {
return RequestConfig.custom().setSocketTimeout(READTIMEOUT).setConnectTimeout(CONNECTTIMEOUT)
.setConnectionRequestTimeout(REQUESTTIMEOUT).build();
}
static public String updates() {
String result = "";
String url = "https://example.com";
CloseableHttpClient httpClient = CreateHttpClient();
CloseableHttpResponse response = null;
URL urlObj;
RequestConfig config = GetConfig();
try {
urlObj = new URL(url);
HttpPost request = new HttpPost(url);
request.setConfig(config);
StringEntity params = new StringEntity("example");
request.addHeader("Accept-Language", "en");
request.addHeader("Content-Type", "application/json; charset=UTF-8");
request.addHeader("Content-Length", String.valueOf(params.getContentLength()));
request.addHeader("Host", urlObj.getHost());
request.addHeader("Connection", "Keep-Alive");
request.addHeader("Accept-Encoding", "gzip");
request.setEntity(params);
response = httpClient.execute(request);
int responseCode = response.getStatusLine().getStatusCode();
System.out.println("updates response code: " + responseCode);
// BufferedReader rd = new BufferedReader(new
// InputStreamReader(response.getEntity().getContent(), "UTF-8"));
result = EntityUtils.toString(response.getEntity());
// String line = "";
// while ((line = rd.readLine()) != null) {
// result.append(line);
// }
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null)
response.close();
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
You should get the content from the response entity which is an InputStream. Than you could create a String from that InputStream with BufferedReader
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result = convertInputStreamToString(instream);
instream.close();
}
Write your own convertInputStreamToString. If you need help for doing that check here:
Read/convert an InputStream to a String

How to perform POST operation on Windows Phone 8.1

I am struggling to successfully implement a POST operation within Windows Phone 8.1.
PostMessage method executes without any exceptions being caught.
However, the POST method within MessagesController never gets invoked.
How do I perform a POST for Windows Phone 8.1?
The code is below:
internal async Task PostMessage(string text)
{
Globals.MemberId = 1;
int memberId = 2;
// server to POST to
string url = #"http://localhost:17634/api/messages";
try
{
// HTTP web request
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "text/plain; charset=utf-8";
httpWebRequest.Method = "POST";
// Write the request Asynchronously
using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream,
httpWebRequest.EndGetRequestStream, null))
{
//create some json string
var message = new Message() { FromId = Globals.MemberId, ToId = memberId, Content = text, Timestamp = DateTime.Now };
var json = string.Format("{0}{1}", "action=", JsonConvert.SerializeObject(message));
// convert json to byte array
byte[] jsonAsBytes = Encoding.UTF8.GetBytes(json);
// Write the bytes to the stream
await stream.WriteAsync(jsonAsBytes, 0, jsonAsBytes.Length);
}
}
catch(Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
public class MessagesController : ApiController
{
public HttpResponseMessage Post(Message message)
{
throw new NotImplementedException();
}
}
public class Message
{
public int MessageId { get; set; }
public int FromId { get; set; }
public int ToId { get; set; }
public DateTime Timestamp { get; set; }
public string Content { get; set; }
}
The following link resolved my issue.
The updated client is as follows:
using (var client = new System.Net.Http.HttpClient())
{
// New code:
client.BaseAddress = new Uri(Globals.URL_PREFIX);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var message = new Message() { MessageId = 0, FromId = Globals.MemberId, ToId = memberId, Content = text, Timestamp = DateTime.Now };
var json_object = JsonConvert.SerializeObject(message);
var response = await client.PostAsync("api/messages", new StringContent(json_object.ToString(), Encoding.UTF8, "application/json"));
Debug.Assert(response.StatusCode == System.Net.HttpStatusCode.Accepted);
}
This works fine for me. The function accepts an payload of type T. The server accepts a JSON object and returns a JSON response.
public async static Task SendRequestPacket<T>(object payload)
{
Uri theUri = new Uri("the_uri");
//Create an Http client and set the headers we want
HttpClient aClient = new HttpClient();
aClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
aClient.DefaultRequestHeaders.Host = theUri.Host;
//Create a Json Serializer for our type
DataContractJsonSerializer jsonSer = new DataContractJsonSerializer(typeof(T));
// use the serializer to write the object to a MemoryStream
MemoryStream ms = new MemoryStream();
jsonSer.WriteObject(ms, payload);
ms.Position = 0;
//use a Stream reader to construct the StringContent (Json)
StreamReader sr = new StreamReader(ms);
StringContent theContent = new StringContent(sr.ReadToEnd(), Encoding.UTF8, "application/json");
//Post the data
HttpResponseMessage aResponse = await aClient.PostAsync(theUri, theContent);
if (aResponse.IsSuccessStatusCode)
{
string content = await aResponse.Content.ReadAsStringAsync();
System.Diagnostics.Debug.WriteLine(content);
}
else
{
// show the response status code
}
}
Just dont use HttpWebRequest if you are not forced to in any way.
This example is using HttpClient() and it is good to always have the client created once and not every time you make a request.
So in your class add:
private static HttpClient _client;
public static Uri ServerBaseUri
{
get { return new Uri("http://localhost:17634/api"); }
}
public ClassConstructor()
{
_client = new HttpClient();
}
internal async Task<ResponseType> PostMessage(string text)
{
Globals.MemberId = 1;
int memberId = 2;
try
{
var js = "{ JSON_OBJECT }";
var json = new StringContent(js);
json.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
var response = await Client.PostAsync(new Uri(ServerBaseUri, "/messages"), json);
var reply = await response.Content.ReadAsStringAsync();
} catch (Exception)
{
return null;
}
}
More on HttpClient.

Pass a jsonstring to the service and convert it to stream on the server side

i have this
{"invoices":{"POSWorkstationID":"POS7","POSClerkID":"admin","CustomerName":"Alice in Wonderland Tours","IsFreightOverwrite":true},"invoiceDetails":[{"ItemDescription":"Old World Lamppost","QuantityOrdered":"1","SalePriceRate":" $107.99","ExtPriceRate":"107.99","ItemType":"Stock","LineNum":1,"WarehouseCode":"Main"}]}
Now i want to pass this on my server using rest and convert it to stream. My service code is here. https://stackoverflow.com/questions/9594382/convert-json-to-stream-in-wcf
Please find some sample code to get your scenario working:
On my Server:
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
public string CreateInvoice(Stream xmlStream)
{
byte[] buffer = new byte[WebOperationContext.Current.IncomingRequest.ContentLength];
int read = -1;
while (read != 0)
{
read = xmlStream.Read(buffer, 0, buffer.Length);
}
System.Text.Encoding enc = System.Text.Encoding.ASCII;
string jsonobjectstring = enc.GetString(buffer);
JavaScriptSerializer json = new JavaScriptSerializer();
object jsonobject = json.DeserializeObject(jsonobjectstring);
return "Recieved the json text on server";
//MaintainInvoice(xmlStream, InvoiceMaintainance.CreateInvoice);
}
I have modified the server method logic so that i can test it. Once you get the stream on the server you can use your logic to return the invoice object as needed.
Now on client side to invoke the rest service i use the below code:
private string UseHttpWebApproachByteArray(string serviceUrl, string resourceUrl, string method, byte[] requestBody)
{
string responseMessage = null;
var request = WebRequest.Create(string.Concat(serviceUrl, resourceUrl)) as HttpWebRequest;
if (request != null)
{
request.ContentType = "application/octet-stream";
request.Method = method;
}
if (method == "POST" && requestBody != null)
{
request.ContentLength = requestBody.Length;
using (Stream postStream = request.GetRequestStream())
postStream.Write(requestBody, 0, requestBody.Length);
}
if (request != null)
{
var response = request.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
if (responseStream != null)
{
var reader = new StreamReader(responseStream);
responseMessage = reader.ReadToEnd();
}
}
else
{
responseMessage = response.StatusDescription;
}
}
return responseMessage;
}
private void Test()
{
string jsonText = "{\"invoices\":{\"POSWorkstationID\":\"POS7\",\"POSClerkID\":\"admin\",\"CustomerName\":\"Alice in Wonderland Tours\",\"IsFreightOverwrite\":true},\"invoiceDetails\":[{\"ItemDescription\":\"Old World Lamppost\",\"QuantityOrdered\":\"1\",\"SalePriceRate\":\" $107.99\",\"ExtPriceRate\":\"107.99\",\"ItemType\":\"Stock\",\"LineNum\":1,\"WarehouseCode\":\"Main\"}]}";
System.Text.Encoding enc = System.Text.Encoding.ASCII;
byte[] jsonBytes = enc.GetBytes(jsonText);
UseHttpWebApproachByteArray(serviceBaseUrl, resourceUrl, method, jsonBytes);
}

HTTP POST does not return expected JSON response

I have pasted a code snippet for HTTP Post where I am POSTING a multipart message to the server which needs Authentication. I am expecting a JSON response, but when I run this I always get the login page in HTML.
public final class MyScreen extends MainScreen {
private RichTextField _Output;
public MyScreen() {
// Set the displayed title of the screen
setTitle("MyTitle");
_Output = new RichTextField();
add(_Output);
addMenuItem(_GetDataAction);
}
protected MenuItem _GetDataAction = new MenuItem("GetData", 100000, 10) {
public void run() {
String URL = "<Sample URL Goes Here>";
ServiceRequestThread svc = new ServiceRequestThread(URL,
(MyScreen) UiApplication.getUiApplication()
.getActiveScreen());
svc.start();
}
};
public void updateDestination(final String text) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
_Output.setText(text);
}
});
}
}
class ServiceRequestThread extends Thread {
protected String _URL;
protected MyScreen _Dest = null;
protected URLEncodedPostData _PostData = null;
StringBuffer writer = new StringBuffer();
public void setPOSTData(URLEncodedPostData data) {
_PostData = data;
}
public ServiceRequestThread(String URL, MyScreen screen) {
super();
_Dest = screen;
_URL = URL;
}
public void run() {
try
{
String boundary = "SATBA";
String twoHyphens = "--";
String data1 = "{\"IMPORTING\":{ \"IN_COUNTRY_CODE\":\"US\"}}";
String CRLF = "\r\n";
byte[] encoded = Base64OutputStream.encode
("User:password".getBytes(), 0, "User:password".length(), false,false);
"Prepare the data for post"
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"param\"").append(
CRLF);
writer.append("Content-Type: text/json; charset=" + "UTF-8").append(CRLF);
writer.append("Content-Transfer-Encoding: 8bit").append(CRLF);
writer.append("Request-Id:Abcd123456" ).append(CRLF);
writer.append("Request-Type:rfc_json").append(CRLF);
writer.append("function:00163E0136C01EE0AE8B059433A71727")
.append(CRLF);
writer.append(CRLF);
writer.append(data1).append(CRLF);
writer.append("--" + boundary + "--").append(CRLF);
String string = new String(writer);
HttpConnection conn1 = (HttpConnection)Connector.open(_URL,Connector.READ_WRITE);
conn1.setRequestMethod(HttpConnection.POST);
conn1.setRequestProperty("Authorization", "Basic "+ new String(encoded));
conn1.setRequestProperty("Content-Type","multipart/mixed; boundary=" + boundary);
OutputStreamWriter osw = new OutputStreamWriter(conn1.openOutputStream(), "UTF-8");
osw.write(string);
osw.flush();
osw.close();
int responseCode = conn1.getResponseCode();
if (responseCode == HttpConnection.HTTP_OK) {
InputStream data = conn1.openInputStream();
StringBuffer raw = new StringBuffer();
byte[] buf = new byte[4096];
int nRead = data.read(buf);
while (nRead > 0) {
raw.append(new String(buf, 0, nRead));
nRead = data.read(buf);
}
_Dest.updateDestination(raw.toString());
} else {
_Dest.updateDestination("responseCode="
+ Integer.toString(responseCode));
}
}
catch( IOException e)
{
e.printStackTrace();
_Dest.updateDestination("Exception:"+e.toString());
}
}
}
Turns out the code was perfectly alright and the issue was on the rim.public property file where the application.handler.http.AuthenticationSupport was set to true and because of this it was not loggging in.
Now I set it to false and get the correct response.

HTTP Get to Report Server 2008 works with DefaultCredentials, fails with some NetworkCredentials

The following WithDefaultCredentials() works but WithCredentialsMe() fails with a http 401 returned ?
The difference is that
ICredentials credentials = System.Net.CredentialCache.DefaultCredentials;
works OK against the report server 2008 url , but
ICredentials credentials = new NetworkCredential("myUsername", "myPassword", "ourDomain");
comes back with a HTTP 401.
The console app is being developed by me so, there should not be a difference between DefaultCredentials and NetworkCredential. There is no problem with my Username and password.
Any ideas ?
static void Main(string[] args)
{
WithDefaultCredentials();
WithCredentialsMe();
}
public static void WithDefaultCredentials()
{
try
{
ICredentials credentials = System.Net.CredentialCache.DefaultCredentials;
string url = "http://myBox/ReportServer_SQLSERVER2008/Pages/ReportViewer.aspx?%2fElfInvoice%2fElfInvoice&rs:Command=Render&InvoiceID=115abba9-61bb-4070-bd28-f572115a2860&rs:format=PDF";
var bytes = GetByteListFromUrl(url, credentials);
File.WriteAllBytes(#"c:\temp\A_WithDefaultCredentitials.pdf", bytes.ToArray());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public static void WithCredentialsMe()
{
try
{
ICredentials credentials = new NetworkCredential("myUsername", "myPassword", "ourDomain");
string url = "http://myBox/ReportServer_SQLSERVER2008/Pages/ReportViewer.aspx?%2fElfInvoice%2fElfInvoice&rs:Command=Render&InvoiceID=115abba9-61bb-4070-bd28-f572115a2860&rs:format=PDF";
var bytes = GetByteListFromUrl(url, credentials);
File.WriteAllBytes(#"c:\temp\A_Credentials_me_1.pdf", bytes.ToArray());
}
catch( Exception ex )
{
Console.WriteLine( ex.Message);
}
}
public static List<Byte> GetByteListFromUrl(string url, System.Net.ICredentials credentials)
{
List<Byte> lstByte = new List<byte>();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
if (credentials != null)
{
request.Credentials = credentials;
}
var response = (HttpWebResponse)request.GetResponse();
var stream = response.GetResponseStream();
int totalBytesRead = 0;
int bufferbytesRead = 0;
try
{
byte[] buffer = new byte[1024];
while ((bufferbytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
{
totalBytesRead += bufferbytesRead;
if (bufferbytesRead < buffer.Length)
{
bufferbytesRead = bufferbytesRead - 1 + 1;
}
for (int i = 0; i < bufferbytesRead; i++)
{
var bToAdd = buffer[i];
lstByte.Add(bToAdd);
}
}
}
catch (Exception ex)
{
}
finally{}
//-Return
return lstByte;
}
With the help of http://forums.asp.net/t/1217642.aspx this code got me what I wanted ...
Next step is clean it all up and unit test in dev ...
public static void ReportServerWebService()
{
// wsdl /out:rs.cs /namespace:ReportService2005 http://mybox/ReportServer_SQLSERVER2008/ReportService2005.asmx?wsdl
/// wsdl /out:rsExec.cs /namespace:ReportExecution2005 http://mybox/ReportServer_SQLSERVER2008/ReportExecution2005.asmx?wsdl
ICredentials credentials = new NetworkCredential("myUserName", "myPassword", "hcml");
Guid invoiceID = new Guid("115ABBA9-61BB-4070-BD28-F572115A2860");
var rs = new ReportService2005.ReportingService2005();
var rsExec = new ReportExecution2005.ReportExecutionService();
rs.Credentials = credentials;
rsExec.Credentials = credentials;
string historyID = null;
string deviceInfo = null;
string format = "PDF";
Byte[] bytPDF;
string encoding = String.Empty;
string mimeType = String.Empty;
string extension = String.Empty;
ReportExecution2005.Warning[] warnings = null;
string[] streamIDs = null;
string _reportName = "/ElfInvoice/ElfInvoice" ;
string _historyID = null;
bool _forRendering = false;
ReportService2005.ParameterValue[] _values = null;
ReportService2005.DataSourceCredentials[] _credentials = null;
ReportService2005.ReportParameter[] _parameters = null;
try
{
// Get if any parameters needed.
_parameters = rs.GetReportParameters( _reportName, _historyID, _forRendering, _values, _credentials);
// Load the selected report.
var ei = rsExec.LoadReport(_reportName, historyID);
// Prepare report parameter.
// Set the parameters for the report needed.
var parameters = new ReportExecution2005.ParameterValue[1];
// // Place to include the parameter.
if (_parameters.Length > 0)
{
parameters[0] = new ReportExecution2005.ParameterValue();
parameters[0].Label = "InvoiceID";
parameters[0].Name = "InvoiceID";
parameters[0].Value = invoiceID.ToString();
}
rsExec.SetExecutionParameters(parameters, "en-us");
bytPDF = rsExec.Render( format , deviceInfo , out extension , out encoding , out mimeType , out warnings , out streamIDs ) ;
try
{
File.WriteAllBytes(#"c:\temp\A_WithMyCredentitials_ReportServerWebService.pdf", bytPDF.ToArray());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}