I want to access an RDL to obtain the report as PDF. I have
static void Main()
{
string pdfOutputFIleName = #"C:\Development\testoutputAsPdf.pdf";
var urlAsPdf = #"http://serverName/ReportServer/Reserved.ReportViewerWebControl.axd?ExecutionID=xxx&Culture=1033&CultureOverrides=False&UICulture=9&UICultureOverrides=False&ReportStack=1&ControlID=yyy&OpType=Export&FileName=Bug+Status&ContentDisposition=OnlyHtmlInline&Format=PDF";
var client = new WebClient();
client.UseDefaultCredentials = true;
//client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
client.Headers.Add("Content-Type", "application/pdf");
Process(client, urlAsPdf, pdfOutputFIleName);
Console.Read();
}
private static void Process(WebClient client, string url, string outputFileName)
{
Stream data = client.OpenRead(url);
using (var reader = new StreamReader(data))
{
string output = reader.ReadToEnd();
using (Stream s = File.Create(outputFileName))
{
var writer = new StreamWriter(s);
writer.Write(output);
Console.WriteLine(output);
}
}
}
The URL works fine in my browser. The program runs. When I to open the PDF I receive an error in Adobe:
There was an error opening this document. The file is damaged and
could not be repaired.
Since you already specify the output file name and the url to read from, perhaps you can use the WebClient.DownloadFile(string address, string filename) member.
private static void Process(WebClient client, string url, string outputFileName)
{
client.DownloadFile(url, outputFileName);
}
Related
I have a project (c# console application), in which I want to automatically download an excel file, via URL, with login credentials.
I have been using a webclient to download the file automatically, and all I receive is an html page as response, informing me to login into the site (I have run it in Chrome.)
private static string url = "[the whole url link to the file, deleted for privacy]";
public void test()
{
const string username = "[mail]";
const string password = "[password]";
var securedPassword = new SecureString();
foreach (var c in password.ToCharArray())
{
securedPassword.AppendChar(c);
}
var credentials = new SharePointOnlineCredentials(username, securedPassword);
DownloadFile(url, credentials, #"C:\Documents\ExcelFilesSinc\test.xlsx");
}
private static void DownloadFile(string webUrl, ICredentials credentials, string fileRelativeUrl)
{
using (var client = new WebClient())
{
client.Credentials = credentials;
string _UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
client.Headers.Add(HttpRequestHeader.UserAgent, _UserAgent);
client.DownloadFile(webUrl, fileRelativeUrl);
}
}
In this way, the file is generated, but the whole content saved in it is an HTML page that requires me to login to Microsoft. Any suggestions?
You can try to add headers for base auth like
client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
client.Headers.Add("User-Agent: Other");
client.Credentials = credentials;
see also here:
Download File From SharePoint 365
Im unable to create an issue on github even though its supposed to work. I do manage to get something back out of it for some reason.
What i am trying to do is uploading a string in json format that has the same feature as POST. Apparently that is not working.
using System;
using System.Collections.Generic;
using System.Net;
using Newtonsoft.Json;
namespace TestProject
{
class Program
{
static void Main(string[] args)
{
CreateGithubIssue("Test Issue - C#", "This is just a test to check if i can manage to create an issue from C#.");
}
static string username = "someUser";
static string password = "somePassword";
static string repoIssueLink = "http://api.github.com/repos/someUser/someRepo/issues";
public static void CreateGithubIssue(string Title, string Description)
{
WebClient webClient = new WebClient();
webClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
webClient.Credentials = new NetworkCredential(username, password);
string jsonPost = JsonConvert.SerializeObject(new Issue(Title, Description), Formatting.Indented);
string response = webClient.UploadString(repoIssueLink, jsonPost);
Console.WriteLine(response);
Console.WriteLine(jsonPost);
}
}
public class Issue
{
public string title;
public string body;
public List<string> assignees;
public int milestone;
public List<string> labels;
public Issue(string title = "Default Title", string body = "Default Body", List<string> assignees = null, int milestone = 0, List<string> labels = null)
{
if (assignees == null) assignees = new List<string>();
if (labels == null) labels = new List<string>();
this.title = title;
this.body = body;
this.assignees = assignees;
this.milestone = milestone;
this.labels = labels;
}
}
}
The Output:
Alright, after asking some other people, i managed to find the answer.
I changed the link to HTTPS and used this code:
WebClient webClient = new WebClient();
webClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password));
webClient.Headers[HttpRequestHeader.Authorization] = string.Format("Basic {0}", credentials);
string jsonOutput = JsonConvert.SerializeObject(new Issue(Title, Description), Formatting.Indented);
string response = webClient.UploadString(repoIssueLink, jsonOutput);
Console.WriteLine(response);
Console.WriteLine(jsonOutput);
I am using the following method to connect to an rss feed.
var url = "http://blogs.mysite.com/feed/";
var sourceXmlFeed = "";
using (var wc = new WebClient())
{
wc.Headers.Add("user-agent", "Mozilla/5.0 (Windows; Windows NT 5.1; rv:1.9.2.4) Gecko/20100611 Firefox/3.6.4");
sourceXmlFeed = wc.DownloadString(url);
}
var xrs = new XmlReaderSettings();
xrs.CheckCharacters = false;
var xtr = new XmlTextReader(new System.IO.StringReader(sourceXmlFeed));
var xmlReader = XmlReader.Create(xtr, xrs);
SyndicationFeed feed = SyndicationFeed.Load(xmlReader);
However I am getting bad characters (as below) in the output and I assume it is something to do with the encoding.
eg. for 2015 we are â?ogoing for goldâ?
Anyone know how to fix this?
By the way, I am doing things this way because I have been unable to use a more direct approach (as below) without causing The remote server returned an error: (443).
var xmlReader = XmlReader.Create("http://blogs.mysite.com/feed);
SyndicationFeed feed = SyndicationFeed.Load(xmlReader);
Problem with encoding is caused by reading xml as string because encoding detection in XML differs from encoding detection in strings.
WebClient webClient = null;
XmlReader xmlReader = null;
try
{
webClient = new WebClient();
webClient.Headers.Add("user-agent", "Mozilla/5.0 (Windows; Windows NT 5.1; rv:1.9.2.4) Gecko/20100611 Firefox/3.6.4");
xmlReader = XmlReader.Create(webClient.OpenRead(url));
// Read XML here because in a finaly block the response stream and the reader will be closed.
}
finally
{
if (webClient != null)
{ webClient.Dispose(); }
if (xmlReader != null)
{ xmlReader .Dispose(); }
}
I want to display image recieved from webresponse to browser directly without saving to a file.i have used below code to save the image to file but i want to display in browser directly.the website provides the captcha image in webresponse which i want to display.please help me.
public void captcha(string id, string pass)
{
HttpWebRequest req;
HttpWebResponse response;
string strNewValue,ckuser,ckpass;
System.Drawing.Image returnval;
ckuser = id;
ckpass = pass;
this.req = (HttpWebRequest)WebRequest.Create("http://site2sms.com/security/captcha.asp");
ServicePointManager.Expect100Continue = false;
this.req.CookieContainer = new CookieContainer();
this.req.AllowAutoRedirect = false;
this.req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/8.0";
this.req.Accept = "*/*";
this.req.Method = "POST";
this.req.CookieContainer = cookieCntr;
this.req.ContentType = "application/x-www-form-urlencoded";
this.req.Referer = "http://site2sms.com/verification.asp?source=login";
this.strNewValue = "user=" + ckuser + "&password=" + ckpass + "&Submit=Sign+in";
this.req.ContentLength = this.strNewValue.Length;
StreamWriter writer = new StreamWriter(this.req.GetRequestStream(), Encoding.ASCII);
writer.Write(this.strNewValue);
writer.Close();
this.response = (HttpWebResponse)this.req.GetResponse();
returnval = Image.FromStream(response.GetResponseStream());
// returnval.Save( Server.MapPath("captcha.bmp"));
Response.AppendHeader("Content-Disposition:", "inline;filename=captcha.bmp");
Response.ContentType = "image/bmp";
Response.Write(returnval);
Response.End();
this.response.Close();
}
You can use HttpResponse.WriteFile method to send the stream to client directly.
Writes the specified file directly to an HTTP response output stream.
You can create the IHttpHandler to send the stream, thus avoid some page life circle, increase the performance. Here is the link
I am using ZipOutputStream from SharpZipLib and I wish to upload the zipped contents it creates directly to my MVC post action. I am successfully getting it to post however the parameter of my action method has null as the posted data when it gets to my MVC action.
Here is my Test code I'm using to test this out:
public void UploadController_CanUploadTest()
{
string xml = "<test>xml test</test>"
string url = "http://localhost:49316/Api/DataUpload/Upload/";
WebClient client = new WebClient();
var cc= new CredentialCache();
cc.Add(new Uri(url),
"Basic",
new NetworkCredential("Testuser", "user"));
client.Credentials = cc;
string _UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
client.Headers.Add(HttpRequestHeader.UserAgent, _UserAgent);
client.Headers["Content-type"] = "application/x-www-form-urlencoded";
using (var stream = client.OpenWrite(url, "POST"))
{
Zipped zip = new Zipped(stream, Encoding.UTF8, false);
FileContent content = new FileContent("Upload", xml);
var uploads = new List<FileContent>();
uploads.Add(content);
zip.Compress(uploads);
stream.Flush();
stream.Close();
}
}
This is my zipped class wrapper:
public class Zipped : ICompression, IDisposable
{
private Stream _stream = null;
private bool _closeStreamOnDispose = true;
private Encoding _encoding;
public Zipped()
: this(new MemoryStream())
{
}
public Zipped(Stream stream)
: this(stream, Encoding.UTF8, true)
{
}
public Zipped(Stream stream, Encoding encoding)
: this(stream, encoding, true)
{
}
public Zipped(Stream stream, Encoding encoding, bool closeStreamOnDispose)
{
_stream = stream;
_closeStreamOnDispose = closeStreamOnDispose;
_encoding = encoding;
}
public Stream Compress(IList<FileContent> dataList)
{
ZipOutputStream outputStream = new ZipOutputStream(_stream);
outputStream.SetLevel(9);
foreach (var data in dataList)
{
ZipEntry entry = new ZipEntry(data.Name);
entry.CompressionMethod = CompressionMethod.Deflated;
outputStream.PutNextEntry(entry);
byte[] dataAsByteArray = _encoding.GetBytes(data.Content);
outputStream.Write(dataAsByteArray, 0, dataAsByteArray.Length);
outputStream.CloseEntry();
}
outputStream.IsStreamOwner = false;
outputStream.Flush();
outputStream.Close();
return _stream;
}
public List<FileContent> DeCompress()
{
ZipInputStream inputStream = new ZipInputStream(_stream);
ZipEntry entry = inputStream.GetNextEntry();
List<FileContent> dataList = new List<FileContent>();
while(entry != null)
{
string entryFileName = entry.Name;
byte[] buffer = new byte[4096]; // 4K is optimum
// Unzip file in buffered chunks. This is just as fast as unpacking to a buffer the full size
// of the file, but does not waste memory.
// The "using" will close the stream even if an exception occurs.
using (MemoryStream tempMemoryStream = new MemoryStream())
{
StreamUtils.Copy(inputStream, tempMemoryStream, buffer);
string copied = _encoding.GetString(tempMemoryStream.ToArray());
dataList.Add(new FileContent(entry.Name, copied));
}
entry = inputStream.GetNextEntry();
}
return dataList;
}
public void Dispose()
{
if(_closeStreamOnDispose)
_stream.Dispose();
}
Here is my simple MVC action:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase uploaded)
{
// uploaded is null at this point
}
If you want to use HttpPostedFileBase in your controller action you need to send a multipart/form-data request from the client and not application/x-www-form-urlencoded.
In fact you set the content type to application/x-www-form-urlencoded but you are not respecting this because you are directly writing the raw bytes to the request which is invalid. Well, in fact it's not respecting the HTTP protocol standard but it could still work if you read the raw request stream from the controller instead of using HttpPostedFileBase. I wouldn't recommend you going that route.
So the correct HTTP request that you are sending must look like this:
Content-Type: multipart/form-data; boundary=AaB03x
--AaB03x
Content-Disposition: form-data; name="uploaded"; filename="input.zip"
Content-Type: application/zip
... byte contents of the zip ...
--AaB03x--
The boundary must be chosen so that it doesn't appear anywhere in the contents of the file.
I have blogged about an example of how you could upload multiple files.