How to convert byte array to HttpPostedFileBase in C#? - c#

I am using asp.net MVC web application. My requirement is to convert byte array to HttpPostedFileBase. I am creating byte array using filepath.
I have taken reference of this question
how to convert a byte[] to HttpPostedFileBase using c# (answer by https://stackoverflow.com/users/2678145/zerratar)
When I used that code I am getting exception while saving that converted file to server. Exception is method or operation is not implemented.
I thought I am getting error because, the content type and filename of converted file was returning null.
So I slightly changed the code like this.
public class HttpPostedFileForStl : HttpPostedFileBase
{
private readonly byte[] fileBytes;
public HttpPostedFileForStl(byte[] fileBytes, string fileName)
{
this.fileBytes = fileBytes;
this.InputStream = new MemoryStream(fileBytes);
this.FileName = fileName;
}
public override int ContentLength => fileBytes.Length;
public override string FileName { get; }
public override string ContentType { get; } = "application/octet-stream";
public override Stream InputStream { get; }
}
I am passing byte array and filename to this class.
Now I am getting appropriate filename and content type in converted file, but exception is still there. Can anyone help?

public class HttpPostedFileBaseCustom : HttpPostedFileBase
{
private byte[] _Bytes;
private String _ContentType;
private String _FileName;
private MemoryStream _Stream;
public override Int32 ContentLength { get { return this._Bytes.Length; } }
public override String ContentType { get { return this._ContentType; } }
public override String FileName { get { return this._FileName; } }
public override Stream InputStream
{
get
{
if(this._Stream == null)
{
this._Stream = new MemoryStream(this._Bytes);
}
return this._Stream;
}
}
public HttpPostedFileBaseCustom(byte[] contentData, String contentType, String fileName)
{
this._ContentType = contentType;
this._FileName = fileName;
this._Bytes = contentData ?? new byte[0];
}
public override void SaveAs(String filename)
{
System.IO.File.WriteAllBytes(filename, this._Bytes);
}
}

Related

Getting file info from memory stream

I am trying to make webapi which returns image
[HttpGet("[action]")]
public IActionResult GetCheckInPhoto(int checkInId, string dealerNr, int photoIndex, int photoType)
{
var stream = _checkinService.GetCheckInPhoto(checkInId, dealerNr, photoIndex, photoType);
return new MultipartResult(){
new MultipartContent()
{
ContentType = System.Net.Mime.MediaTypeNames.Image.Jpeg,
Name = "xxx",
FileName = "dsada",
Stream = stream
}
};
}
My method GetCheckInPhoto returns MemoryStream where is photo.
how to get FileInfo like Filename or FileType from MemoryStream?
Your "CheckinService" should return something like
public class MyFile
{
public string FileName { get; set; }
public string ContentType { get; set; }
public Stream ReadStream { get; set; }
}

Deserialisation unable to list data

I am trying to create an application that can both serialise and deserialise data, i can serialise the information however when i try to read the information i am left with an empty list and i do not know why.
My Serialization class
[Serializable()]
public class FileSerilizeObject
{
public static string FileName { get; set; }
public static string Extension { get; set; }
public static string Base64 { get; set; }
public FileSerilizeObject(string filename, string extension, string base64vaulue)
{
FileName = filename;
Extension = extension;
Base64 = base64vaulue;
}
}
}
My serialization/deserialization methods
public void Serialize(List<FileSerilizeObject> List)
{
using (Stream stream = File.Open(savepath, FileMode.OpenOrCreate))
{
BinaryFormatter bin = new BinaryFormatter();
bin.Serialize(stream, List);
stream.Close();
}
}
public List<FileSerilizeObject> Deserialised(string OpenPath)
{
List<FileSerilizeObject> defo;
using(Stream stream = File.Open(OpenPath, FileMode.Open))
{
BinaryFormatter bin = new BinaryFormatter();
defo = (List<FileSerilizeObject>)bin.Deserialize(stream);
}
return defo;
}
I have checked to insure that the file paths are correct and that the file itself is not empty.Everything is fine however the "defo" list is always empty so i can only assume the issue is with the defo = (List<FileSerilizeObject>)bin.Deserialize(stream);Line however i do not know why.
You need to remove the static from your properties
[Serializable]
public class FileSerializeObject
{
public string FileName { get; set; }
public string Extension { get; set; }
public string Base64 { get; set; }
public FileSerializeObject(string filename, string extension, string base64vaulue)
{
FileName = filename;
Extension = extension;
Base64 = base64vaulue;
}
}
Try to set the [Serializable()] attribute for each property.
So it would look like this:
[Serializable()]
public class FileSerilizeObject
{
[Serializable()]
public string FileName { get; set; }
[Serializable()]
public string Extension { get; set; }
[Serializable()]
public string Base64 { get; set; }
public FileSerilizeObject(string filename, string extension, string base64vaulue)
{
FileName = filename;
Extension = extension;
Base64 = base64vaulue;
}
}
}
EDIT: Removed static keyword from properties.
I tested your code into a console application and it is working for me, I tested with VS 2013 but I used the same code that you wrote above.
Some details:
1. I removed the word static form the "FileSerilizeObject"
The class FileSerilizeObject
[Serializable()]
public class FileSerilizeObject
{
public string FileName { get; set; }
public string Extension { get; set; }
public string Base64 { get; set; }
public FileSerilizeObject(string filename, string extension, string base64vaulue)
{
FileName = filename;
Extension = extension;
Base64 = base64vaulue;
}
}
Functions
public static void Serialize(List<FileSerilizeObject> List)
{
using (Stream stream = File.Open(#"C:\Users\ttest\Desktop\folder1\data.bin", FileMode.OpenOrCreate))
{
BinaryFormatter bin = new BinaryFormatter();
bin.Serialize(stream, List);
stream.Close();
}
}
public static List<FileSerilizeObject> Deserialised(string OpenPath)
{
List<FileSerilizeObject> defo;
using (Stream stream = File.Open(OpenPath, FileMode.Open))
{
BinaryFormatter bin = new BinaryFormatter();
defo = (List<FileSerilizeObject>)bin.Deserialize(stream);
}
return defo;
}
Main
var bytes = Encoding.UTF8.GetBytes("dffesdbcdef==");
var base64 = Convert.ToBase64String(bytes);
FileSerilizeObject f1 = new FileSerilizeObject("test", "jpg", base64);
bytes = Encoding.UTF8.GetBytes("ggasddbcdef==");
base64 = Convert.ToBase64String(bytes);
FileSerilizeObject f2 = new FileSerilizeObject("test2", "png", base64);
bytes = Encoding.UTF8.GetBytes("asddffasdasdasdesdbcdef==");
base64 = Convert.ToBase64String(bytes);
FileSerilizeObject f3 = new FileSerilizeObject("test3", "doc", base64);
List<FileSerilizeObject> lFiles = new List<FileSerilizeObject>();
lFiles.Add(f1);
lFiles.Add(f2);
lFiles.Add(f3);
Serialize(lFiles);
Deserialised(#"C:\Users\rjimen4x\Desktop\tutoriales\data.bin");

How to Implement a Web API controller to accept chunked uploads using JQuery File Upload?

As the title states, I need some help implementing a Web API controller to accept chunked uploads using JQuery File Upload. Any help (including links to existing articles/tutorials) will be much appreciated.
First let start with the client side.
You must set the maxChunkSize option for chunked uploads. After that you need a unique identifier per file in order to identify each chunk on the server and append the corresponding chunk data to the correct file.
$('#fileupload')
.bind('fileuploadsubmit', function (e, data) {
data.headers = $.extend(data.headers,
{"X-File-Identifier": generateFileUniqueIdentifier(data)})
});
});
generateFileUniqueIdentifier = function(data){
var file=data.files[0],
var result = file.relativePath||file.webkitRelativePath||file.fileName||file.name;
return result.replace(/[^0-9a-zA-Z_-]/img,"") + "-" + i.size + "-" + $.now()
}
Now on the server side: ApiController
public class UploadController : ApiController
{
[HttpPost]
[Route("upload/{targetFolder:int}")]
[ValidateMimeMultipartContentFilter]
public async Task<IHttpActionResult> UploadDocument(int targetFolder)
{
var uploadFileService = new UploadFileService();
UploadProcessingResult uploadResult = await uploadFileService.HandleRequest(Request);
if (uploadResult.IsComplete)
{
// do other stuff here after file upload complete
return Ok();
}
return Ok(HttpStatusCode.Continue);
}
}
The service class which actually upload the file. This support chunks or a whole file.
public class UploadFileService
{
private readonly string _uploadPath;
private readonly MultipartFormDataStreamProvider _streamProvider;
public UploadFileService()
{
_uploadPath = UserLocalPath;
_streamProvider = new MultipartFormDataStreamProvider(_uploadPath);
}
#region Interface
public async Task<UploadProcessingResult> HandleRequest(HttpRequestMessage request)
{
await request.Content.ReadAsMultipartAsync(_streamProvider);
return await ProcessFile(request);
}
#endregion
#region Private implementation
private async Task<UploadProcessingResult> ProcessFile(HttpRequestMessage request)
{
if (request.IsChunkUpload())
{
return await ProcessChunk(request);
}
return new UploadProcessingResult()
{
IsComplete = true,
FileName = OriginalFileName,
LocalFilePath = LocalFileName,
FileMetadata = _streamProvider.FormData
};
}
private async Task<UploadProcessingResult> ProcessChunk(HttpRequestMessage request)
{
//use the unique identifier sent from client to identify the file
FileChunkMetaData chunkMetaData = request.GetChunkMetaData();
string filePath = Path.Combine(_uploadPath, string.Format("{0}.temp", chunkMetaData.ChunkIdentifier));
//append chunks to construct original file
using (FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate | FileMode.Append))
{
var localFileInfo = new FileInfo(LocalFileName);
var localFileStream = localFileInfo.OpenRead();
await localFileStream.CopyToAsync(fileStream);
await fileStream.FlushAsync();
fileStream.Close();
localFileStream.Close();
//delete chunk
localFileInfo.Delete();
}
return new UploadProcessingResult()
{
IsComplete = chunkMetaData.IsLastChunk,
FileName = OriginalFileName,
LocalFilePath = chunkMetaData.IsLastChunk ? filePath : null,
FileMetadata = _streamProvider.FormData
};
}
#endregion
#region Properties
private string LocalFileName
{
get
{
MultipartFileData fileData = _streamProvider.FileData.FirstOrDefault();
return fileData.LocalFileName;
}
}
private string OriginalFileName
{
get
{
MultipartFileData fileData = _streamProvider.FileData.FirstOrDefault();
return fileData.Headers.ContentDisposition.FileName.Replace("\"", string.Empty);
}
}
private string UserLocalPath
{
get
{
//return the path where you want to upload the file
}
}
#endregion
}
The extensions over HttpRequestMessagge used to identify a chunk request
public static class HttpRequestMessageExtensions
{
public static bool IsChunkUpload(this HttpRequestMessage request)
{
return request.Content.Headers.ContentRange != null;
}
public static FileChunkMetaData GetChunkMetaData(this HttpRequestMessage request)
{
return new FileChunkMetaData()
{
ChunkIdentifier = request.Headers.Contains("X-DS-Identifier") ? request.Headers.GetValues("X-File-Identifier").FirstOrDefault() : null,
ChunkStart = request.Content.Headers.ContentRange.From,
ChunkEnd = request.Content.Headers.ContentRange.To,
TotalLength = request.Content.Headers.ContentRange.Length
};
}
}
And at the end the service response model and chunk metadata
public class FileChunkMetaData
{
public string ChunkIdentifier { get; set; }
public long? ChunkStart { get; set; }
public long? ChunkEnd { get; set; }
public long? TotalLength { get; set; }
public bool IsLastChunk
{
get { return ChunkEnd + 1 >= TotalLength; }
}
}
public class UploadProcessingResult
{
public bool IsComplete { get; set; }
public string FileName { get; set; }
public string LocalFilePath { get; set; }
public NameValueCollection FileMetadata { get; set; }
}
The MultiPartContentFilter is just an ActionFilter to validate the content (from damienbod)
public class ValidateMimeMultipartContentFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
}
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
}
}
You can find inspiration here: ASP.NET Multiple File Upload With Drag & Drop and Progress Bar Using HTML5. An example of a chunked upload controller method starts in UploadFile. On the client, jquery file upload option maxChunkSize needs to be set according to https://github.com/blueimp/jQuery-File-Upload/wiki/Options .

Missing Assembly Reference And Method must have a return type?! MVC 4

im working in mvc 4 and try to implement jquery file uploader.
but in my FileStatus class and UploadHandler give me several errors.
-namespace FileStatus cannot be found,
-Method FileStatus need a return type.
i have an example and have seen that the method FileStatus dont return anything,
i dont´t know what is going on..
can someone give a hand?
FIleStatusCLASS
public class FileStatus
{
public const string HandlerPath = "/Upload/";
public string group { get; set; }
public string name { get; set; }
public string type { get; set; }
public int size { get; set; }
public string progress { get; set; }
public string url { get; set; }
public string thumbnail_url { get; set; }
public string delete_url { get; set; }
public string delete_type { get; set; }
public string error { get; set; }
public FilesStatus() { }
public FilesStatus(FileInfo fileInfo) { SetValues(fileInfo.Name, (int)fileInfo.Length, fileInfo.FullName); }
public FilesStatus(string fileName, int fileLength, string fullPath) { SetValues(fileName, fileLength, fullPath); }
private void SetValues(string fileName, int fileLength, string fullPath)
{
name = fileName;
type = "image/png";
size = fileLength;
progress = "1.0";
url = HandlerPath + "UploadHandler.ashx?f=" + fileName;
delete_url = HandlerPath + "UploadHandler.ashx?f=" + fileName;
delete_type = "DELETE";
var ext = Path.GetExtension(fullPath);
var fileSize = ConvertBytesToMegabytes(new FileInfo(fullPath).Length);
if (fileSize > 3 || !IsImage(ext)) thumbnail_url = "/Content/img/generalFile.png";
else thumbnail_url = #"data:image/png;base64," + EncodeFile(fullPath);
}
private bool IsImage(string ext)
{
return ext == ".gif" || ext == ".jpg" || ext == ".png";
}
private string EncodeFile(string fileName)
{
return Convert.ToBase64String(System.IO.File.ReadAllBytes(fileName));
}
static double ConvertBytesToMegabytes(long bytes)
{
return (bytes / 1024f) / 1024f;
}
}
UPLOADHANDLER
public class UploadHandler : IHttpHandler
{
private readonly JavaScriptSerializer js;
private string StorageRoot
{
get { return Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Files/")); } //Path should! always end with '/'
}
public UploadHandler()
{
js = new JavaScriptSerializer();
js.MaxJsonLength = 41943040;
}
public bool IsReusable { get { return false; } }
public void ProcessRequest(HttpContext context)
{
context.Response.AddHeader("Pragma", "no-cache");
context.Response.AddHeader("Cache-Control", "private, no-cache");
HandleMethod(context);
}
// Handle request based on method
private void HandleMethod(HttpContext context)
{
switch (context.Request.HttpMethod)
{
case "HEAD":
case "GET":
if (GivenFilename(context)) DeliverFile(context);
else ListCurrentFiles(context);
break;
case "POST":
case "PUT":
UploadFile(context);
break;
case "DELETE":
DeleteFile(context);
break;
case "OPTIONS":
ReturnOptions(context);
break;
default:
context.Response.ClearHeaders();
context.Response.StatusCode = 405;
break;
}
}
private static void ReturnOptions(HttpContext context)
{
context.Response.AddHeader("Allow", "DELETE,GET,HEAD,POST,PUT,OPTIONS");
context.Response.StatusCode = 200;
}
// Delete file from the server
private void DeleteFile(HttpContext context)
{
var filePath = StorageRoot + context.Request["f"];
if (File.Exists(filePath))
{
File.Delete(filePath);
}
}
// Upload file to the server
private void UploadFile(HttpContext context)
{
var statuses = new List<FilesStatus>();
var headers = context.Request.Headers;
if (string.IsNullOrEmpty(headers["X-File-Name"]))
{
UploadWholeFile(context, statuses);
}
else
{
UploadPartialFile(headers["X-File-Name"], context, statuses);
}
WriteJsonIframeSafe(context, statuses);
}
// Upload partial file
private void UploadPartialFile(string fileName, HttpContext context, List<FilesStatus> statuses)
{
if (context.Request.Files.Count != 1) throw new HttpRequestValidationException("Attempt to upload chunked file containing more than one fragment per request");
var inputStream = context.Request.Files[0].InputStream;
var fullName = StorageRoot + Path.GetFileName(fileName);
using (var fs = new FileStream(fullName, FileMode.Append, FileAccess.Write))
{
var buffer = new byte[1024];
var l = inputStream.Read(buffer, 0, 1024);
while (l > 0)
{
fs.Write(buffer, 0, l);
l = inputStream.Read(buffer, 0, 1024);
}
fs.Flush();
fs.Close();
}
statuses.Add(new FilesStatus(new FileInfo(fullName)));
}
// Upload entire file
private void UploadWholeFile(HttpContext context, List<FilesStatus> statuses)
{
for (int i = 0; i < context.Request.Files.Count; i++)
{
var file = context.Request.Files[i];
var fullPath = StorageRoot + Path.GetFileName(file.FileName);
file.SaveAs(fullPath);
string fullName = Path.GetFileName(file.FileName);
statuses.Add(new FilesStatus(fullName, file.ContentLength, fullPath));
}
}
private void WriteJsonIframeSafe(HttpContext context, List<FilesStatus> statuses)
{
context.Response.AddHeader("Vary", "Accept");
try
{
if (context.Request["HTTP_ACCEPT"].Contains("application/json"))
context.Response.ContentType = "application/json";
else
context.Response.ContentType = "text/plain";
}
catch
{
context.Response.ContentType = "text/plain";
}
var jsonObj = js.Serialize(statuses.ToArray());
context.Response.Write(jsonObj);
}
private static bool GivenFilename(HttpContext context)
{
return !string.IsNullOrEmpty(context.Request["f"]);
}
private void DeliverFile(HttpContext context)
{
var filename = context.Request["f"];
var filePath = StorageRoot + filename;
if (File.Exists(filePath))
{
context.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
context.Response.ContentType = "application/octet-stream";
context.Response.ClearContent();
context.Response.WriteFile(filePath);
}
else
context.Response.StatusCode = 404;
}
private void ListCurrentFiles(HttpContext context)
{
var files =
new DirectoryInfo(StorageRoot)
.GetFiles("*", SearchOption.TopDirectoryOnly)
.Where(f => !f.Attributes.HasFlag(FileAttributes.Hidden))
.Select(f => new FilesStatus(f))
.ToArray();
string jsonObj = js.Serialize(files);
context.Response.AddHeader("Content-Disposition", "inline; filename=\"files.json\"");
context.Response.Write(jsonObj);
context.Response.ContentType = "application/json";
}
}
For UploadHandler i use this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.Script.Serialization;
and for fileclass this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
i know its a lot of code and sorry for that but i think its better to show you all the code.
Thanks in advance for the help.
You're declaring a class called FileStatus:
public class FileStatus
... but here you're trying to declare a constructor for FilesStatus:
public FilesStatus(FileInfo fileInfo)
(And the other constructors.)
Basically, your class name and the name specified in the constructor don't match, and they need to.

Programmatically exporting reports from SQL 2012 Reporting Services

I have a console application which needs to connect to SQL Reporting Services on SQL Server Express 2012.
All the exporting logic should be implemented in a separate dll, and the paths should be dynamic (I have loop through various settings for various servers/reports and export them to Excel one by one).
I tried to follow these tutorials:
http://www.aspose.com/docs/display/wordsreportingservices/Rendering+Reports+Programmatically
http://blogs.msdn.com/b/selvar/archive/2010/12/13/accessing-the-reportexecutionservice-render-method-when-reporting-service-2008-r2-is-in-forms-based-authentication.aspx
Basically, I added web references:
http://localhost:80/ReportServer_SQLEXPRESS12/ReportExecution2005.asmx
and
http://localhost:80/ReportServer_SQLEXPRESS12/ReportService2010.asmx
to my dll. Looks good so far, except those nasty app.config settings (I'll have to adjust them dynamically later).
Then I tried to do as in the example:
// Create Web service proxies.
ReportingService2010.ReportingService2010 rs = new ReportingService2010.ReportingService2010();
ReportExecutionService.ReportExecutionService rsExec = new ReportExecutionService.ReportExecutionService();
and got some troubles:
Error 76 The type or namespace name 'ReportExecutionService' does not exist in the namespace 'MyDllNamespace.ReportExecutionService' (are you missing an assembly reference?)
Error 74 The type or namespace name 'ReportingService2010' does not exist in the namespace 'MyDllNamespace.ReportingService2010' (are you missing an assembly reference?)
Now where do I go next, how do I use the Reporting Services API, if I cannot even create a proxy object? Or should I better use ServerReport class form the Winforms ReportViewer instead of these web references?
Even one of Microsoft examples is using ReportViewer in a console application, but it seems a bit awkward to import Winforms in a console app.
I hope the following will help (extract of pertinent parts of code)
using (ZUtilities.SSRS.Report report = new ZUtilities.SSRS.Report {
ReportServerPath = VParameter.GetValue("SSRS_WebServiceUrl", _repo.Parameters).ToString(),
Format = rformat,
ReportPath = "some_path_on_ssrs_server"
}) {
report.Params.Add("Id", id.ToString());
report.Credentials = nwc;
MemoryStream ms = new MemoryStream();
report.Render().CopyTo(ms);
FileContentResult fsr = new FileContentResult(ms.ToArray(), rctype);
fsr.FileDownloadName = String.Format("EPV-{0}-{1:yyyyMMdd}.{2}", epv.ExternalReference, DateTime.Now, fext);
ms.Close();
return fsr;
}
with the following (be carefull to the stream management)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
namespace ZUtilities.SSRS {
public enum ReportFormats {
Html = 1,
MHtml,
Pdf,
Xlsx,
Docx
}
public class ReportFormat {
static ReportFormat() {
Html = new ReportFormat { Code = ReportFormats.Html, Instruction = "HTML4.0" };
MHtml = new ReportFormat { Code = ReportFormats.MHtml, Instruction = "MHTML" };
Pdf = new ReportFormat { Code = ReportFormats.Pdf, Instruction = "PDF" };
Xlsx = new ReportFormat { Code = ReportFormats.Xlsx, Instruction = "EXCELOPENXML" };
Docx = new ReportFormat { Code = ReportFormats.Docx, Instruction = "WORDOPENXML" };
}
private ReportFormat() {
}
public ReportFormats Code { get; set; }
public String Instruction { get; set; }
public static ReportFormat Html { get; private set; }
public static ReportFormat MHtml { get; private set; }
public static ReportFormat Pdf { get; private set; }
public static ReportFormat Xlsx { get; private set; }
public static ReportFormat Docx { get; private set; }
public static ReportFormat ByCode(ReportFormats code) {
switch (code) {
case ReportFormats.Html: return Html;
case ReportFormats.MHtml: return Html; //<<======================
case ReportFormats.Pdf: return Pdf;
case ReportFormats.Xlsx: return Xlsx;
case ReportFormats.Docx: return Docx;
default : return null;
}
}
}
public class Report : IDisposable {
private HttpWebRequest _httpWReq;
private WebResponse _httpWResp;
public Report() {
_httpWReq = null;
_httpWResp = null;
Format = ReportFormats.Html;
Params = new Dictionary<String, String>();
}
public Dictionary<String, String> Params { get; set; }
public String ReportServerPath { get; set; }
public String ReportPath { get; set; }
public ReportFormats Format { get; set; }
public NetworkCredential Credentials { get; set; }
//public String PostData { get { return String.Format("rs:Command=Render&rs:Format={0}", ReportFormat.ByCode(Format).Instruction); } }
public String PostData { get {
StringBuilder sb = new StringBuilder(1024);
sb.AppendFormat("rs:Command=Render&rs:Format={0}", ReportFormat.ByCode(Format).Instruction);
if (Format == ReportFormats.Html) {
sb.Append("&rc:Toolbar=false");
}
foreach (var kv in Params) {
sb.AppendFormat("&{0}={1}", kv.Key, kv.Value);
}
return sb.ToString();
} }
public String ReportFullPath { get { return ReportServerPath + "?/" + ReportPath; } }
public Stream Render() {
_httpWReq = (HttpWebRequest)HttpWebRequest.Create(ReportFullPath);
_httpWReq.Method = "POST";
if (Credentials != null)
_httpWReq.Credentials = Credentials;
byte[] byteArray = Encoding.UTF8.GetBytes(PostData);
_httpWReq.ContentType = "application/x-www-form-urlencoded";
_httpWReq.ContentLength = byteArray.Length;
Stream dataStream = _httpWReq.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
if (_httpWResp != null )
_httpWResp.Close();
_httpWResp = _httpWReq.GetResponse();
return _httpWResp.GetResponseStream();
}
public void RenderTo(String fileName) {
Stream receiveStream = Render();
Stream ds = File.Open(fileName, FileMode.Create);
receiveStream.CopyTo(ds);
ds.Close();
receiveStream.Close();
}
public void Dispose() {
if (_httpWResp != null) {
_httpWResp.Close();
_httpWResp = null;
}
if (_httpWReq != null) {
_httpWReq = null;
}
}
}
}

Categories

Resources