Is there any way to improve the performace of local report or even an alternative if not ? Current code for converting rdlc to pdf below. Have been looking for a solution for quite some time but the general consensus seems to be that its just slow, Thanks for any help.
public byte[] genReportBytes(int id, string fromm, string too, string filetype)
{
reportDetails repD = new reportDetails();
repD = getOneReport(id);
LocalReport report = new LocalReport();
if (fromm != null)
repD.ParametersCommandLine = "#startdate=" + fromm;
if (too != null)
repD.ParametersCommandLine += " #enddate=" + too;
string RDLCPath = ConfigurationManager.AppSettings["RDLCPath"];
string ReportOutputPath = ConfigurationManager.AppSettings["ReportOutputPath"];
string RDLCName = repD.RDLCName;
RDLCPath += #"\" + RDLCName;
report.ReportPath = RDLCPath;
string sqlGet = repD.SQLOfReport;
report.DataSources.Add(new ReportDataSource(repD.DatasetName, getReportData(sqlGet, repD.ParametersCommandLine)));
// export to byte array
Warning[] warnings;
string[] streamids;
string mimeType;
string encoding;
string filenameExtension;
string deviceInf = "";
byte[] bytes;
string extension;
if (filetype == "pdf")
{
deviceInf = "<DeviceInfo><PageHeight>8.5in</PageHeight><PageWidth>11in</PageWidth><MarginLeft>0in</MarginLeft><MarginRight>0in</MarginRight></DeviceInfo>";
//fileName = ReportOutputPath + #"\" + repD.NameOfOutputPDF + ".PDF";
bytes = report.Render("pdf", deviceInf, out mimeType, out encoding, out filenameExtension,
out streamids, out warnings);
}
else
{
//fileName = ReportOutputPath + #"\" + repD.NameOfOutputPDF + ".XLS";
bytes = report.Render(
"Excel", null, out mimeType, out encoding,
out extension,
out streamids, out warnings);
}
return bytes;
}
I've post an answer here slow-performance-with-dynamic-grouping-and-reportviewer-in-local-mode
Basically you have to run the reportviewer in a separated Appdomain, this is the Render method, it takes all the parameters from your current reportviewer control.
private static byte[] Render(string reportRenderFormat, string deviceInfo, string DisplayName, string ReportPath, bool Visible, ReportDataSourceCollection DataSources, string repMainContent, List<string[]> repSubContent, ReportParameter[] reportParam)
{
AppDomainSetup setup = new AppDomainSetup { ApplicationBase = Environment.CurrentDirectory, LoaderOptimization = LoaderOptimization.MultiDomainHost };
setup.SetCompatibilitySwitches(new[] { "NetFx40_LegacySecurityPolicy" });
AppDomain _casPolicyEnabledDomain = AppDomain.CreateDomain("Full Trust", null, setup);
try
{
WebReportviewer.FullTrustReportviewer rvNextgenReport2 = (WebReportviewer.FullTrustReportviewer)_casPolicyEnabledDomain.CreateInstanceFromAndUnwrap(typeof(WebReportviewer.FullTrustReportviewer).Assembly.CodeBase, typeof(WebReportviewer.FullTrustReportviewer).FullName);
rvNextgenReport2.Initialize(DisplayName, ReportPath, Visible, reportParam, reportRenderFormat, deviceInfo, repMainContent, repSubContent);
foreach (ReportDataSource _ReportDataSource in DataSources)
{
rvNextgenReport2.AddDataSources(_ReportDataSource.Name, (DataTable)_ReportDataSource.Value);
}
return rvNextgenReport2.Render(reportRenderFormat, deviceInfo);
}
finally
{
AppDomain.Unload(_casPolicyEnabledDomain);
}
}
this is the new Assembly that will run the report:
namespace WebReportviewer
{
[Serializable]
public class FullTrustReportviewer : MarshalByRefObject
{
private ReportViewer FullTrust;
public FullTrustReportviewer()
{
FullTrust = new ReportViewer();
FullTrust.ShowExportControls = false;
FullTrust.ShowPrintButton = true;
FullTrust.ShowZoomControl = true;
FullTrust.SizeToReportContent = false;
FullTrust.ShowReportBody = true;
FullTrust.ShowDocumentMapButton = false;
FullTrust.ShowFindControls = true;
FullTrust.LocalReport.SubreportProcessing += LocalReport_SubreportProcessing;
}
public void Initialize(string DisplayName, string ReportPath, bool Visible, ReportParameter[] reportParam, string reportRenderFormat, string deviceInfo, string repMainContent, List<string[]> repSubContent)
{
FullTrust.LocalReport.DisplayName = DisplayName;
FullTrust.LocalReport.ReportPath = ReportPath;
FullTrust.Visible = Visible;
FullTrust.LocalReport.LoadReportDefinition(new StringReader(repMainContent));
FullTrust.LocalReport.SetParameters(reportParam);
repSubContent.ForEach(x =>
{
FullTrust.LocalReport.LoadSubreportDefinition(x[0], new StringReader(x[1]));
});
FullTrust.LocalReport.DataSources.Clear();
}
public byte[] Render(string reportRenderFormat, string deviceInfo)
{
return FullTrust.LocalReport.Render(reportRenderFormat, deviceInfo);
}
public void AddDataSources(string p, DataTable datatable)
{
FullTrust.LocalReport.DataSources.Add(new ReportDataSource(p, datatable));
}
public SubreportProcessingEventHandler SubreportProcessing { get; set; }
public static void LocalReport_SubreportProcessing(object sender, SubreportProcessingEventArgs e)
{
LocalReport lr = (LocalReport)sender;
e.DataSources.Clear();
ReportDataSource rds;
if (e.ReportPath.Contains("DataTable2"))
{
DataTable dt = (DataTable)lr.DataSources["DataTable2"].Value;
DataView dv = new DataView(dt);
dv.RowFilter = string.Format("Id={0}", e.Parameters["Id"].Values[0]);
rds = new ReportDataSource("DataTable2", dv.ToTable());
e.DataSources.Add(rds);
}
}
}
}
Doing it this way will require the minimum changes to your current code.
regards.
Also, placing <trust legacyCasModel="true" level="Full"/> inside <system.web> tag in web.config will produce the same result. More details here
Sounds no way to improve this RDLC to PDF. No solution!
Related
My Project is in ASP.NET MVC, Right now I am using Razor Engine Service (RazorEngineService.RunCompile) to create multiple XML files and making it as a single Zip file and exporting it.
But the problem is that when we pass the model object each time to process the template and return it as separate XML files and completing the whole operation it takes more time to complete (Almost ~40 Seconds for 10 objects) for whole content to export.
Is there anything wrong with my current approach or am I doing it correctly right now? Please guide me If I am doing any mistakes in this approach.
private FileInfo Export(List<Model> modelList)
{
string timeStr = Datetime.Now.ToString();
string archiveFileName = "Main.zip";
string archivePath = Path.Combine(_reportFolderPath, archiveFileName);
using (ZipArchive archive = ZipFile.Open(archivePath, ZipArchiveMode.Create))
{
foreach (var list in modelList)
{
string fileName = model.name + model.Id;
string filePath = GetModelExport(list, fileName, timeStr);
archive.CreateEntryFromFile(filePath, fileName + ".xml");
}
archive.Dispose();
}
return new FileInfo(archivePath);
}
private string GetModelExport(Model model, string fileName, string timeStr)
{
var processedTemplate = ProcessTemplate(model, TemplateName, TemplateKey);
string reportFilelName = fileName + "_" + timeStr + ".xml";
string filePath = Path.Combine(_reportFolderPath, reportFilelName);
using (var file = new StreamWriter(filePath))
{
file.Write(processedTemplate);
}
return filePath;
}
private string ProcessTemplate(Model model, string templateName, string templateKey)
{
var templateFilePath = Path.Combine(_reportTemplateFolder, templateName);
return ReportUtils.ProcessTemplate(templateFilePath, templateKey, model);
}
public static string ProcessTemplate(string templatePath, string templateKey, object model = null)
{
var templateService = RazorEngineService.Create();
var result = templateService.RunCompile(File.ReadAllText(templatePath), templateKey, null, model);
return result;
}
some of your code is missing so i cant see the whole picture, this is what i would start with..... gd luck.
public class HolderTempName
{
private TemplateService _templateService;
private Dictionary<string, string> _templateContainer;
public HolderTempName()
{
//this will save creating this everytime
_templateService = RazorEngineService.Create();
//this will hold the template so it does not have to fetch on each loop,
//if the same template is used.
_templateContainer = new Dictionary<string, string>();
}
//you will need to tweeek this to get the type out
private string GetTemplate(string templateName, templatePath)
{
if(!_templateContainer.Conatains(templateName))
{
var text = File.ReadAllText(templatePath);
_templateContainer[templateName] = text;
}
return _templateContainer[templateName];
}
private FileInfo Export(List<Model> modelList)
{
string timeStr = Datetime.Now;
string archiveFileName = "Main.zip";
string archivePath = Path.Combine(_reportFolderPath, archiveFileName);
using (ZipArchive archive = ZipFile.Open(archivePath, ZipArchiveMode.Create))
{
foreach (var item in modelList)
{
var templateFilePath = Path.Combine(_reportTemplateFolder, TemplateName); //<--TemplateName seems like a local private
//these should come from where cant see where...
var template = GetTemplate( TemplateName, templateFilePath)
string modelResponse = ProcessModel(item,template,TemplateKey ); //<-- why is not passing in the template
//step 2;
//making this above done in parrell and then add aync, but before all that measure what is taking time
string pathname = MakeFileName(_reportFolderPath, reportFilelName, timeStr);
SaveToDisk(pathname, modelResponse);
string fileName = model.name + model.Id;
archive.CreateEntryFromFile(filePath, fileName + ".xml");
}
archive.Dispose();
}
return new FileInfo(archivePath);
}
private string MakeFileName(string path ,string filename, string tStamp)
{
string reportFilelName = fileName + "_" + timeStr + ".xml";
string filePath = Path.Combine(_reportFolderPath, reportFilelName);
return filePath;
}
private void SaveToDisk(string filePath, string content)
{
using (var file = new StreamWriter(filePath))
{
file.Write(processedTemplate);
}
}
public static string ProcessTemplate(object model, string template, templateKey)
{
var result = templateService.RunCompile(template, templateKey, null, model);
return result;
}
}
I want to download the textfile on button click from Kendo grid rows. I got an Id of selected row and pass it to my
controller and now it doesnt download the file as it is showing the error below. Thou the error seems to be fixed
Failed to load resource: net::ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION
The file naming is like this : e669a7e7-7eb2-4cfa-b950-3b79ed621a57
public ActionResult DownloadIndex(int id)
{
try
{
string Filelocation = "MyServerLocationFolder";
OnePossModel md = new Models.OnePossModel();
JsonParamBuilder myBuilder = new JsonParamBuilder();
myBuilder.AddParam<Guid>("userid", System.Guid.Parse(User.Identity.GetUserId()));
myBuilder.AddParam<int>("id", Convert.ToInt32(id));
string jsonReq = Models.JsonWrapper.JsonPOST(ApiBaseUrl + "/WriteFile", myBuilder.GetJSonParam());
string poassFilename = Models.DeserialiseFromJson<string>.DeserialiseApiResponse(jsonReq);
string filepath = Filelocation + poassFilename.ToString();
byte[] filedata = System.IO.File.ReadAllBytes(filepath);
string contentType = MimeMapping.GetMimeMapping(filepath);
var cd = new System.Net.Mime.ContentDisposition
{
FileName = poassFilename,
Inline = true,
};
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + poassFilename + "\"");
return File(filedata, "application/txt", Server.UrlEncode(poassFilename));
}
catch (Exception ex)
{
throw ex;
}
}
Use "text/plain" instead of "application/txt":
public ActionResult DownloadIndex(int id)
{
try
{
string Filelocation = "MyServerLocationFolder";
OnePossModel md = new Models.OnePossModel();
JsonParamBuilder myBuilder = new JsonParamBuilder();
myBuilder.AddParam<Guid>("userid", System.Guid.Parse(User.Identity.GetUserId()));
myBuilder.AddParam<int>("id", Convert.ToInt32(id));
string jsonReq = Models.JsonWrapper.JsonPOST(ApiBaseUrl + "/WriteFile", myBuilder.GetJSonParam());
string poassFilename = Models.DeserialiseFromJson<string>.DeserialiseApiResponse(jsonReq);
string filepath = Filelocation + poassFilename.ToString();
byte[] filedata = System.IO.File.ReadAllBytes(filepath);
return File(filedata, "text/plain", Server.UrlEncode(poassFilename));
}
catch (Exception ex)
{
throw ex;
}
}
Hello I have signature like this:
which is encoded to a DataUrl specifically this string:
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAADICAYAAADGFbfiAAAYlElEQVR4Xu2dC8w1R1nHQSCIgIKVGLmoiLciFwUs... (long string)"
What i want to do is Convert this DataUrl to an PNG Image, and save the image to the device, this is what i am doing so far:
if (newItem.FieldType == FormFieldType.Signature)
{
if (newItem.ItemValue != null)
{
//string completeImageName = Auth.host + "/" + li[i];
string path;
string filename;
string stringName = newItem.ItemValue;
var base64Data = Regex.Match(stringName, #"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value;
var binData = Convert.FromBase64String(base64Data);
path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
filename = Path.Combine(path, base64Data);
if (!File.Exists(filename))
{
using (var stream = new MemoryStream(binData))
{
//Code crashing here--------------------------
File.WriteAllBytes(filename, binData);
}
}
newItem.ItemValue = filename;
}
}
App.Database.SaveReportItem(newItem);
But my code is making my application to crash specifically in this line:
File.WriteAllBytes(filename, binData);
The sample I am using as reference (Link) is using a PictureBox but with Xamarin there is no use of a pictureBox.
Any Ideas?
As #SLaks mentioned I didn't need a MemoryStream, the problem with my code was the path and the filename for further help this is the working code:
if (newItem.FieldType == FormFieldType.Signature)
{
if (newItem.ItemValue != null)
{
//string completeImageName = Auth.host + "/" + li[i];
string path;
string filename;
string stringName = newItem.ItemValue;
var base64Data = Regex.Match(stringName, #"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value;
var binData = Convert.FromBase64String(base64Data);
path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
//filename = Path.Combine(path, base64Data.Replace(#"/", string.Empty));
long milliseconds = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
string fileName = "Sn" + milliseconds.ToString() + ".PNG";
filename = Path.Combine(path, fileName);
if (!File.Exists(filename))
{
//using (var stream = new MemoryStream(binData))
//{
File.WriteAllBytes(filename, binData);
//}
}
newItem.ItemValue = filename;
}
}
App.Database.SaveReportItem(newItem);
And the image showed:
I just cleaned Mario's code and fine tuned regex:
public string SaveDataUrlToFile(string dataUrl, string savePath)
{
var matchGroups = Regex.Match(dataUrl, #"^data:((?<type>[\w\/]+))?;base64,(?<data>.+)$").Groups;
var base64Data = matchGroups["data"].Value;
var binData = Convert.FromBase64String(base64Data);
System.IO.File.WriteAllBytes(savePath, binData);
return savePath;
}
I have a web app written in C# that I need to be able to render an SSRS report on an aspx page without using the Report Viewer control.
As HTML inside a div tag would be perfect. I have the app attached to my SSRS instance via ReportingService2010 reference.
I've found some examples online but are for ReportingServices2005 and couldn't port them over.
How can I do this?
I pulled this out of a project I put together about a year ago.
A few key points:
you need to pass credentials to the report server.
you need to create an images path so that any images in your report are rendered and displayed in the html Report/GraphFiles/ "this should be relative to your app url"
and if your report has any parameters you will need to add them.
you will definitely need to tweek the code to get it going.
it uses the ReportExecutionService reference, you will have to play around with it but the nuts and bolts should all be here.
i'd really love to spend time cleaning it up a bit but i dont have the time sorry, i hope it helps
class RenderReport
{
public struct ReportServerCreds
{
public string UserName { get; set; }
public string Password { get; set; }
public string Domain { get; set; }
}
public ReportServerCreds GetReportCreds()
{
ReportServerCreds rsc = new ReportServerCreds();
rsc.UserName = ConfigurationManager.AppSettings["reportserveruser"].ToString();
rsc.Password = ConfigurationManager.AppSettings["reportserverpassword"].ToString();
rsc.Domain = ConfigurationManager.AppSettings["reportserverdomain"].ToString();
return rsc;
}
public enum SSRSExportType
{
HTML,PDF
}
public string RenderReport(string reportpath,SSRSExportType ExportType)
{
using (ReportExecutionService.ReportExecutionServiceSoapClient res = new ReportExecutionService.ReportExecutionServiceSoapClient("ReportExecutionServiceSoap"))
{
ReportExecutionService.ExecutionHeader ExecutionHeader = new ReportExecutionService.ExecutionHeader();
ReportExecutionService.TrustedUserHeader TrusteduserHeader = new ReportExecutionService.TrustedUserHeader();
res.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
ReportServerCreds rsc = GetReportCreds();
res.ClientCredentials.Windows.ClientCredential.Domain = rsc.Domain;
res.ClientCredentials.Windows.ClientCredential.UserName = rsc.UserName;
res.ClientCredentials.Windows.ClientCredential.Password = rsc.Password;
res.Open();
ReportExecutionService.ExecutionInfo ei = new ReportExecutionService.ExecutionInfo();
string format =null;
string deviceinfo =null;
string mimetype = null;
if (ExportType.ToString().ToLower() == "html")
{
format = "HTML4.0";
deviceinfo = #"<DeviceInfo><StreamRoot>/</StreamRoot><HTMLFragment>True</HTMLFragment></DeviceInfo>";
}
else if (ExportType.ToString().ToLower() == "pdf")
{
format = "PDF";
mimetype = "";
}
byte[] results = null;
string extension = null;
string Encoding = null;
ReportExecutionService.Warning[] warnings;
string[] streamids = null;
string historyid = null;
ReportExecutionService.ExecutionHeader Eheader;
ReportExecutionService.ServerInfoHeader serverinfoheader;
ReportExecutionService.ExecutionInfo executioninfo;
// Get available parameters from specified report.
ParameterValue[] paramvalues = null;
DataSourceCredentials[] dscreds = null;
ReportParameter[] rparams = null;
using (ReportService.ReportingService2005SoapClient lrs = new ReportService.ReportingService2005SoapClient("ReportingService2005Soap"))
{
lrs.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
lrs.ClientCredentials.Windows.ClientCredential.Domain = rsc.Domain;
lrs.ClientCredentials.Windows.ClientCredential.UserName = rsc.UserName;
lrs.ClientCredentials.Windows.ClientCredential.Password = rsc.Password;
lrs.GetReportParameters(reportpath,historyid,false,paramvalues,dscreds,out rparams);
}
// Set report parameters here
//List<ReportExecutionService.ParameterValue> parametervalues = new List<ReportExecutionService.ParameterValue>();
//string enumber = Session["ENumber"] as string;
//parametervalues.Add(new ReportExecutionService.ParameterValue() { Name = "ENumber", Value = enumber });
//if (date != null)
//{
// DateTime dt = DateTime.Today;
//parametervalues.Add(new ReportExecutionService.ParameterValue() { Name = "AttendanceDate", Value = dt.ToString("MM/dd/yyyy")});
//}
//if (ContainsParameter(rparams, "DEEWRID"))
//{
//parametervalues.Add(new ReportExecutionService.ParameterValue() { Name = "DEEWRID", Value = deewrid });
//}
//if (ContainsParameter(rparams, "BaseHostURL"))
//{
// parametervalues.Add(new ReportExecutionService.ParameterValue() { Name = "BaseHostURL", Value = string.Concat("http://", Request.Url.Authority) });
//}
//parametervalues.Add(new ReportExecutionService.ParameterValue() {Name="AttendanceDate",Value=null });
//parametervalues.Add(new ReportExecutionService.ParameterValue() { Name = "ENumber", Value = "E1013" });
try
{
Eheader = res.LoadReport(TrusteduserHeader, reportpath, historyid, out serverinfoheader, out executioninfo);
serverinfoheader = res.SetExecutionParameters(Eheader, TrusteduserHeader, parametervalues.ToArray(), null, out executioninfo);
res.Render(Eheader, TrusteduserHeader, format, deviceinfo, out results, out extension, out mimetype, out Encoding, out warnings, out streamids);
string exportfilename = string.Concat(enumber, reportpath);
if (ExportType.ToString().ToLower() == "html")
{
//write html
string html = string.Empty;
html = System.Text.Encoding.Default.GetString(results);
html = GetReportImages(res, Eheader, TrusteduserHeader, format, streamids, html);
return html;
}
else if (ExportType.ToString().ToLower() == "pdf")
{
//write to pdf
Response.Buffer = true;
Response.Clear();
Response.ContentType = mimetype;
//Response.AddHeader("content-disposition", string.Format("attachment; filename={0}.pdf", exportfilename));
Response.BinaryWrite(results);
Response.Flush();
Response.End();
}
}
catch (Exception e)
{
Response.Write(e.Message);
}
}
}
string GetReportImages(ReportExecutionService.ReportExecutionServiceSoapClient res,
ReportExecutionService.ExecutionHeader EHeader,
ReportExecutionService.TrustedUserHeader tuh,
string reportFormat, string[] streamIDs, string html)
{
if (reportFormat.Equals("HTML4.0") && streamIDs.Length > 0)
{
string devInfo;
string mimeType;
string Encoding;
int startIndex;
int endIndex;
string fileExtension = ".jpg";
string SessionId;
Byte[] image;
foreach (string streamId in streamIDs)
{
SessionId = Guid.NewGuid().ToString().Replace("}", "").Replace("{", "").Replace("-", "");
//startIndex = html.IndexOf(streamId);
//endIndex = startIndex + streamId.Length;
string reportreplacementname = string.Concat(streamId, "_", SessionId, fileExtension);
html = html.Replace(streamId, string.Concat(#"Report\GraphFiles\", reportreplacementname));
//html = html.Insert(endIndex, fileExtension);
//html = html.Insert(startIndex, #"Report/GraphFiles/" + SessionId + "_");
devInfo = "";
//Image = res.RenderStream(reportFormat, streamId, devInfo, out encoding, out mimeType);
res.RenderStream(EHeader,tuh, reportFormat, streamId, devInfo, out image , out Encoding, out mimeType);
System.IO.FileStream stream = System.IO.File.OpenWrite(HttpContext.Current.Request.PhysicalApplicationPath + "Report\\GraphFiles\\" + reportreplacementname);
stream.Write(image, 0, image.Length);
stream.Close();
mimeType = "text/html";
}
}
return html;
}
bool ContainsParameter(ReportParameter[] parameters, string paramname)
{
if(parameters.Where(i=>i.Name.Contains(paramname)).Count() != 0)
{
return true;
}
return false;
}
}
To Execute:
first parameter is the location of the report on the server.
the second is a SSRSExportType enum
RenderReport("ReportPathOnServer",SSRSExportType.HTML);
If you are just trying to show the HTML render of a report and you want it to look like a native object to the application without any parameters or toolbar, then you could call the URL for the report directly and include "&rc:Toolbar=false" in the URL. This will hide the toolbar for the Report Viewer control. This method is described under the URL Access Parameter Reference msdn article. Not exactly what you asked for, but it may achieve the purpose.
Here's a sample call that omits the HTML and Body sections if you are embedding the results in an existing HTML document:
http://ServerName/ReportServer?%2fSome+Folder%2fSome+Report+Name&rs:Command=Render&rc:Toolbar=false&rc:HTMLFragment=true
Definitely an old question but if you're using ASP.NET MVC you could try this open source solution. It uses an HTML helper and renders an .aspx page in an iframe. The repo has a server-side, local render, and anonymous example.
I'm using radAsyncFileUpload to upload a file. I want to save the file contents in a database as bytes. Here's my code so far:
protected void DetailsView1_ItemInserting(object sender, DetailsViewInsertEventArgs e)
{
if (DetailsView1.CurrentMode == DetailsViewMode.Insert)
{
if (Session["ProjectId"] != null)
{
int Projectid = Convert.ToInt32(Session["ProjectId"]);
string Description = (DetailsView1.FindControl("RadEditor1") as RadEditor).Content;
RadAsyncUpload radAsyncUpload = DetailsView1.FindControl("RadAsyncUpload1") as RadAsyncUpload;
UploadedFile file = radAsyncUpload.UploadedFiles[0];
string s = file.FileName;
string path = System.IO.Path.GetFileName(s);
radAsyncUpload.UploadedFiles[0].SaveAs(Server.MapPath("Uploads/") + path);
string Contenttype = radAsyncUpload.UploadedFiles[0].ContentType;
int fileSize = radAsyncUpload.UploadedFiles[0].ContentLength;
float length = float.Parse(fileSize.ToString());
byte[] fileData = new byte[file.InputStream.Length];
file.InputStream.Read(fileData, 0, (int)file.InputStream.Length);
ProTrakEntities objEntity = new ProTrakEntities();
ProjectFile objFile = new ProjectFile();
objFile.ProjectId = Projectid;
objFile.FileName = s;
objFile.FileType = Contenttype;
objFile.FileSize = length;
objFile.CreatedBy = "admin";
objFile.CreatedDate = DateTime.Now;
objFile.Description = Description;
objFile.FileData = fileData;
objEntity.AddToProjectFiles(objFile);
objEntity.SaveChanges();
}
DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);
ClientScript.RegisterStartupScript(Page.GetType(), "mykey", "CloseAndRebind('navigateToInserted');", true);
}
}
I'm getting an error while uploading at the line file.InputStream.Read(fileData, 0, (int)file.InputStream.Length);:
Could not find file 'D:\Tiru\Projects\ProTrak\App_Data\RadUploadTemp\0ngsv0wx.fxs'.
What does this error mean, and how can I get rid of it?
As em not having the edit right..
em posting ur code with little modification see if it works..
my code
protected void DetailsView1_ItemInserting(object sender, DetailsViewInsertEventArgs e)
{
if (DetailsView1.CurrentMode == DetailsViewMode.Insert)
{
if (Session["ProjectId"] != null)
{
int Projectid = Convert.ToInt32(Session["ProjectId"]);
string Description = (DetailsView1.FindControl("RadEditor1") as RadEditor).Content;
RadAsyncUpload radAsyncUpload = DetailsView1.FindControl("RadAsyncUpload1") as RadAsyncUpload;
UploadedFile file = radAsyncUpload.UploadedFiles[0];
string s = file.FileName;
string path = System.IO.Path.GetFileName(s);
string Contenttype = radAsyncUpload.UploadedFiles[0].ContentType;
int fileSize = radAsyncUpload.UploadedFiles[0].ContentLength;
float length = float.Parse(fileSize.ToString());
byte[] fileData = new byte[file.InputStream.Length];
file.InputStream.Read(fileData, 0, (int)file.InputStream.Length);
ProTrakEntities objEntity = new ProTrakEntities();
ProjectFile objFile = new ProjectFile();
objFile.ProjectId = Projectid;
objFile.FileName = s;
objFile.FileType = Contenttype;
objFile.FileSize = length;
objFile.CreatedBy = "admin";
objFile.CreatedDate = DateTime.Now;
objFile.Description = Description;
objFile.FileData = fileData;
objEntity.AddToProjectFiles(objFile);
objEntity.SaveChanges();
}
DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);
ClientScript.RegisterStartupScript(Page.GetType(), "mykey", "CloseAndRebind('navigateToInserted');", true);
radAsyncUpload.UploadedFiles[0].SaveAs(Server.MapPath("Uploads/") + path);
}
}
use like this..
RadAsyncUpload radAsyncUpload = InsertItem.FindControl("AsyncUpload1") as RadAsyncUpload;
UploadedFile file = radAsyncUpload.UploadedFiles[0];
byte[] fileData = new byte[file.InputStream.Length];
file.InputStream.Read(fileData, 0, (int)file.InputStream.Length);