did SubethaSmtp store emails somewhere? - smtp

I use the SubethaSmtp library as an email server and so far I have been able to run this server and test it by sending an email. Email information is printed in the output. As far as I know, smtp protocol is used to send emails. While IMAP protocol is used to receive emails. My question is, did SubethaSmtp store emails somewhere (such as a database or file)? In general, do I need a server other than SubethaSmtp server to receive emails? What will be the relationship between these two protocols?
My code is written in the following two Java classes:
BasicSMTPServer class:
package com.sojoodi;
import org.subethamail.smtp.server.SMTPServer;
public class BasicSMTPServer {
public static void main(String[] args) {
MyMessageHandlerFactory myFactory = new MyMessageHandlerFactory();
SMTPServer smtpServer = new SMTPServer(myFactory);
smtpServer.setPort(25000);
smtpServer.start();
System.out.println("smtpServer = " + smtpServer);
System.out.println("HostName = " + smtpServer.getHostName());
}
}
and MyMessageHandlerFactory class:
package com.sojoodi;
import org.subethamail.smtp.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class MyMessageHandlerFactory implements MessageHandlerFactory {
public MessageHandler create(MessageContext ctx) {
return new Handler(ctx);
}
class Handler implements MessageHandler {
MessageContext ctx;
public Handler(MessageContext ctx) {
this.ctx = ctx;
}
public void from(String from) throws RejectException {
System.out.println("FROM:"+from);
}
public void recipient(String recipient) throws RejectException {
System.out.println("RECIPIENT:"+recipient);
}
public void data(InputStream data) throws IOException {
System.out.println("MAIL DATA");
System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
System.out.println(this.convertStreamToString(data));
System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
}
public void done() {
System.out.println("Finished");
}
public String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}
}

Maybe you can check the Receive emails with SubEtha SMTP and Spring Boot post and for you question about storing you can check the issues section in the related code repository as there is an issue same as yours.

Related

Modify Existing alarms AWS

I want to know how do i read and modify all the alarms ? I am currently facing problem to read the next set of alarms. The first set contains first 50.
DescribeAlarmsRequest describeAlarmsRequest = new DescribeAlarmsRequest();
DescribeAlarmsResult alarmsResult = cloudWatch.describeAlarms(describeAlarmsRequest);
System.out.println(alarmsResult.getMetricAlarms().size());
System.out.println(alarmsResult.getNextToken());
DescribeAlarmsRequest describeAlarmsRequest1 = new DescribeAlarmsRequest();
describeAlarmsRequest1.setNextToken(alarmsResult.getNextToken());
DescribeAlarmsResult alarmsResult1 = cloudWatch.describeAlarms(describeAlarmsRequest1);
System.out.println(alarmsResult1.getMetricAlarms().size());
I did it the following way and it worked.
public class Alarms {
private static AmazonCloudWatchClient cloudWatch;
private static AmazonSNSClient client;
private static ClientConfiguration clientConfiguration;
private static final String AWS_KEY = "";
private static final String AWS_SECRET_KEY = "";
static {
BasicAWSCredentials credentials = new BasicAWSCredentials(AWS_KEY,AWS_SECRET_KEY);
cloudWatch = new AmazonCloudWatchClient(credentials);
clientConfiguration = new ClientConfiguration();
clientConfiguration.setConnectionTimeout(10000);
clientConfiguration.setSocketTimeout(30000);
clientConfiguration.setMaxErrorRetry(5);
client = new AmazonSNSClient(credentials, clientConfiguration);
}
public static void main(String args[]) {
cloudWatch.setEndpoint("monitoring.us-east-1.amazonaws.com");
DescribeAlarmsRequest describeAlarmsRequest = new DescribeAlarmsRequest();
//describeAlarmsRequest.setStateValue(StateValue.OK);
DescribeAlarmsResult alarmsResult = cloudWatch.describeAlarms(describeAlarmsRequest);
List<MetricAlarm> metricAlarmList = new ArrayList<>();
metricAlarmList.addAll(alarmsResult.getMetricAlarms());
do {
describeAlarmsRequest.withNextToken(alarmsResult.getNextToken());
alarmsResult = cloudWatch.describeAlarms(describeAlarmsRequest);
metricAlarmList.addAll(alarmsResult.getMetricAlarms());
} while (alarmsResult.getNextToken() != null);
int i = metricAlarmList.size();
System.out.println("size " + i);
for(MetricAlarm alarm : metricAlarmList){
System.out.println(i--);
modifyalarm(alarm);
}
}
private static void modifyalarm(MetricAlarm alarm) {
Dimension instanceDimension = new Dimension();
instanceDimension.setName("InstanceId");
instanceDimension.setValue(alarm.getAlarmName());
PutMetricAlarmRequest request = new PutMetricAlarmRequest()
.withActionsEnabled(true).withAlarmName(alarm.getAlarmName())
.withComparisonOperator(ComparisonOperator.GreaterThanOrEqualToThreshold)
.withDimensions(Arrays.asList(instanceDimension))
.withAlarmActions(getTopicARN())
.withEvaluationPeriods(5)
.withPeriod(60)
.withThreshold(5.0D)
.withStatistic(Statistic.Average)
.withMetricName("StatusCheckFailed")
.withNamespace("AWS/EC2");
cloudWatch.putMetricAlarm(request);
}
private static String getTopicARN() {
ListTopicsResult listTopicsResult = client.listTopics();
String nextToken = listTopicsResult.getNextToken();
List<Topic> topics = listTopicsResult.getTopics();
String topicARN = "";
while (nextToken != null) {
listTopicsResult = client.listTopics(nextToken);
nextToken = listTopicsResult.getNextToken();
topics.addAll(listTopicsResult.getTopics());
}
for (Topic topic : topics) {
if (topic.getTopicArn().contains("status-alarms")) {
topicARN = topic.getTopicArn();
break;
}
}
return topicARN;
}
}

Using XPages to get data from managed bean

I am trying to create a list of Twitter users, populating it with the number of followers for the user and their profile image. Because of Twitter's API, you need to get an access token for your application prior to using their REST API. I thought the best way to do this was via Java and a managed bean. I posted the code below, which currently works. I get the access token from Twitter, then make the API call to get the user info, which is in JSON.
My question is, what is the best way to parse the JSON and iterate over a list of user names to create a table/grid on the XPage?
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import javax.net.ssl.HttpsURLConnection;
import org.apache.commons.codec.binary.Base64;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
public class TwitterUser implements Serializable {
private static final String consumerKey = "xxxx";
private static final String consumerSecret = "xxxx";
private static final String twitterApiUrl = "https://api.twitter.com";
private static final long serialVersionUID = -2084825539627902622L;
private static String accessToken;
private String twitUser;
public TwitterUser() {
this.twitUser = null;
}
public String getTwitterUser(String screenName) {
try {
this.requestTwitterUserInfo(screenName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return twitUser;
}
public void setTwitterUser() {
twitUser = twitUser;
}
//Encodes the consumer key and secret to create the basic authorization key
private static String encodeKeys(String consumerKey, String consumerSecret) {
try {
String encodedConsumerKey = URLEncoder.encode(consumerKey, "UTF-8");
String encodedConsumerSecret = URLEncoder.encode(consumerSecret, "UTF-8");
String fullKey = encodedConsumerKey + ":" + encodedConsumerSecret;
byte[] encodedBytes = Base64.encodeBase64(fullKey.getBytes());
return new String(encodedBytes);
}
catch (UnsupportedEncodingException e) {
return new String();
}
}
//Constructs the request for requesting a bearer token and returns that token as a string
private static void requestAccessToken() throws IOException {
HttpsURLConnection connection = null;
String endPointUrl = twitterApiUrl + "/oauth2/token";
String encodedCredentials = encodeKeys(consumerKey,consumerSecret);
String key = "";
try {
URL url = new URL(endPointUrl);
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("User-Agent", "Your Program Name");
connection.setRequestProperty("Authorization", "Basic " + encodedCredentials);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
connection.setRequestProperty("Content-Length", "29");
connection.setUseCaches(false);
writeRequest(connection, "grant_type=client_credentials");
// Parse the JSON response into a JSON mapped object to fetch fields from.
JSONObject obj = (JSONObject)JSONValue.parse(readResponse(connection));
if (obj != null) {
String tokenType = (String)obj.get("token_type");
String token = (String)obj.get("access_token");
accessToken = ((tokenType.equals("bearer")) && (token != null)) ? token : "";
}
else {
accessToken = null;
}
}
catch (MalformedURLException e) {
throw new IOException("Invalid endpoint URL specified.", e);
}
finally {
if (connection != null) {
connection.disconnect();
}
}
}
private void requestTwitterUserInfo(String sn) throws IOException {
HttpsURLConnection connection = null;
if (accessToken == null) {
requestAccessToken();
}
String count = "";
try {
URL url = new URL(twitterApiUrl + "/1.1/users/show.json?screen_name=" + sn);
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("User-Agent", "Your Program Name");
connection.setRequestProperty("Authorization", "Bearer " + accessToken);
connection.setRequestProperty("Content-Type", "text/plain");
connection.setUseCaches(false);
}
catch (MalformedURLException e) {
throw new IOException("Invalid endpoint URL specified.", e);
}
finally {
if (connection != null) {
connection.disconnect();
}
}
twitUser = readResponse(connection);
}
//Writes a request to a connection
private static boolean writeRequest(HttpsURLConnection connection, String textBody) {
try {
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
wr.write(textBody);
wr.flush();
wr.close();
return true;
}
catch (IOException e) { return false; }
}
// Reads a response for a given connection and returns it as a string.
private static String readResponse(HttpsURLConnection connection) {
try {
StringBuilder str = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
while((line = br.readLine()) != null) {
str.append(line + System.getProperty("line.separator"));
}
return str.toString();
}
catch (IOException e) { return new String(); }
}
}
A few pointers:
Domino has the Apache HTTP client classes. They tend to be more robust than raw HTTP connections
Define a new class as a bean that contains all values that you want to see per row. You only need the getters public
add a method to your managed bean Collection getAllData()
bind that to a repeat control
you then can use repeatvar.someProperty in column values in EL
use better names than I just used

Google docs api for Java (exception)

I have a problem with google docs. I want to retrieve all your files by using OAuth 2.0. The problem is that once you do, and authorization when trying to download a file gives me this error:
Exception in thread "main" java.lang.NullPointerException
at GoogleBlack.readUrl(GoogleBlack.java:95)
at GoogleBlack.getDocument(GoogleBlack.java:87)
at GoogleBlack.go(GoogleBlack.java:187)
at GoogleBlack.main(GoogleBlack.java:222)
Here's the code I use
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.gdata.client.GoogleService;
import com.google.gdata.client.GoogleAuthTokenFactory.UserToken;
import com.google.gdata.client.docs.DocsService;
import com.google.gdata.data.MediaContent;
import com.google.gdata.data.docs.DocumentListEntry;
import com.google.gdata.data.docs.DocumentListFeed;
import com.google.gdata.data.media.MediaSource;
import com.google.gdata.util.ServiceException;
public class GoogleBlack {
private static final String APPLICATION_NAME = "Homework";
public DocsService service;
public GoogleService spreadsheetsService;
static String CLIENT_ID = "***********";
static String CLIENT_SECRET = "**************";
static String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
static List<String> SCOPES = Arrays.asList("https://docs.google.com/feeds");
public void getSpreadSheet(String id, String i, String ids, String type) throws Exception {
UserToken docsToken = (UserToken) service.getAuthTokenFactory()
.getAuthToken();
UserToken spreadsheetsToken = (UserToken) spreadsheetsService
.getAuthTokenFactory().getAuthToken();
service.setUserToken(spreadsheetsToken.getValue());
URL url = null;
if(type.equals("doc"))
{
url = new URL("https://docs.google.com/feeds/download/documents/Export?id="+ ids);
}
else
{
url = new URL("https://docs.google.com/feeds/download/spreadsheets/Export?key="+ ids +"&exportFormat="+ type + "&gid=0");
i += ".xls";
}
System.out.println("Spred = " + url.toString());
readUrl1(url.toString(), i, type);
service.setUserToken(docsToken.getValue());
}
public void readUrl1(String url, String i, String type) throws IOException, ServiceException
{
MediaContent mc = new MediaContent();
mc.setUri(url);
MediaSource ms = service.getMedia(mc);
System.out.println("Name: "+i);
BufferedInputStream bin = new BufferedInputStream(ms.getInputStream());
OutputStream out = new FileOutputStream(i);
BufferedOutputStream bout = new BufferedOutputStream(out);
while (true) {
int datum = bin.read();
if (datum == -1)
break;
bout.write(datum);
}
bout.flush();
}
public void getDocument(String id, String i) throws Exception {
URL url = new URL(id);
readUrl(url,i);
}
public void readUrl(URL url, String i) throws Exception {
MediaContent mc = new MediaContent();
mc.setUri(url.toString());
System.out.println("Url "+ url.toString());
System.out.println("MC: " + mc.toString());
MediaSource ms = service.getMedia(mc);
System.out.println("Name: "+i);
BufferedInputStream bin = new BufferedInputStream(ms.getInputStream());
OutputStream out = new FileOutputStream(i);
BufferedOutputStream bout = new BufferedOutputStream(out);
while (true) {
int datum = bin.read();
if (datum == -1)
break;
bout.write(datum);
}
bout.flush();
// FileOutputStream fout = null;
// fout = new FileOutputStream(i);
// fout.write(cbuf.);
// fout.close();
}
static Credential getCredentials() {
HttpTransport transport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
// Step 1: Authorize -->
String authorizationUrl =
new GoogleAuthorizationCodeRequestUrl(CLIENT_ID, REDIRECT_URI, SCOPES).build();
// Point or redirect your user to the authorizationUrl.
System.out.println("Go to the following link in your browser:");
System.out.println(authorizationUrl);
// Read the authorization code from the standard input stream.
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is the authorization code?");
String code = null;
try {
code = in.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// End of Step 1 <--
// Step 2: Exchange -->
GoogleTokenResponse response = null;
try {
response = new GoogleAuthorizationCodeTokenRequest(transport, jsonFactory, CLIENT_ID, CLIENT_SECRET,
code, REDIRECT_URI).execute();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// End of Step 2 <--
// Build a new GoogleCredential instance and return it.
return new GoogleCredential.Builder().setClientSecrets(CLIENT_ID, CLIENT_SECRET)
.setJsonFactory(jsonFactory).setTransport(transport).build()
.setAccessToken(response.getAccessToken()).setRefreshToken(response.getRefreshToken());
}
public void go() throws Exception {
DocsService service = new DocsService(APPLICATION_NAME);
service.setOAuth2Credentials(getCredentials());
URL feedUrl = new URL("https://docs.google.com/feeds/default/private/full/");
DocumentListFeed feed = service.getFeed(feedUrl, DocumentListFeed.class);
System.out.println("Feed " + feed.getEntries().size());
for(int i = 0; i < feed.getEntries().size(); i++)
{
DocumentListEntry entry = feed.getEntries().get(i);
if(entry.getType().equals("file"))
{
MediaContent mc1 = (MediaContent) entry.getContent();
String UrlForDownload = mc1.getUri();
System.out.println("Type is: " + entry.getType());
System.out.println("File Name is: " + entry.getTitle().getPlainText());
System.out.println("URL "+ UrlForDownload);
getDocument(UrlForDownload, entry.getFilename());
}
else
{
MediaContent mc1 = (MediaContent) entry.getContent();
String UrlForDownload = mc1.getUri();
System.out.println("URL "+ UrlForDownload);
System.out.println("Type is: " + entry.getType());
System.out.println("File Name is: " + entry.getTitle().getPlainText());
if(entry.getTitle().getPlainText().equals("Web Design 2011/2012 - Материали"))
{
continue;
}
if(entry.getType().equals("spreadsheet"))
{
String name = entry.getTitle().getPlainText().replaceAll(" ", "");
System.out.println("name: " + name);
getSpreadSheet(UrlForDownload, name, entry.getDocId(),"xls");
}
else
{
String name = entry.getTitle().getPlainText().replaceAll(" ", "");
System.out.println("name: " + name);
getSpreadSheet(UrlForDownload, name, entry.getDocId(),"doc");
}
}
}
}
public static void main(String[] args) throws Exception {
new GoogleBlack().go();
}
}
95 row - MediaSource ms = service.getMedia(mc);
87 row - readUrl(url,i);
187 row - getDocument(UrlForDownload, entry.getFilename());
222 row - new GoogleBlack().go();
I apologize if I am not well explained!!!
You never initialized the "public DocsService service;" member of your GoogleBlack class, so when you call "service.getMedia(mc);" you're getting a NullPointerException.

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);
}
}