rdlc Report works in local but not on server - asp.net

I have a report with some datasets, working perfectly in local, but on the server i get the error :
One or more parameters required to run the report have not been specified.
I don't have any parameters on this report, so i don't understand this error... I have this code in controller :
public ActionResult RunReport(int PremiseId)
{
LocalReport localReport = new LocalReport();
localReport.ReportPath = Server.MapPath("~/Views/Report/PremisePricing.rdlc");
Premise premise = _db.GetPremise(PremiseId);
ICollection<PremisePricing> premisePricings;
if (premise.PremiseMeters.Count() > 0)
{
premisePricings = premiseMeterPricingToPremisePricing(_db.FindAllPremiseMeteredPricing(premise).ToList());
}
else
{
premisePricings = _db.FindAllPremisePricing(PremiseId).ToList();
}
// Add your data source
List<ReportDataSource> listDS = new List<ReportDataSource>();
ICollection<Premise> premises = new List<Premise>();
premises.Add(premise);
ReportDataSource premiseDS = new ReportDataSource("Premise", premises);
listDS.Add(premiseDS);
ReportDataSource premisePricingDS = new ReportDataSource("PremisePricing", premisePricings);
listDS.Add(premisePricingDS);
ICollection<CompanyProvider> companyProviders = new List<CompanyProvider>();
CompanyProvider companyProvider = _db.GetCompanyProvider();
companyProviders.Add(companyProvider);
ReportDataSource companyProviderDS = new ReportDataSource("CompPro", companyProviders);
listDS.Add(companyProviderDS);
ICollection<CompanyProviderContactManager> companyProviderContactManager = new List<CompanyProviderContactManager>();
if (companyProvider.CompanyProviderContactManager != null)
{
companyProviderContactManager.Add(companyProvider.CompanyProviderContactManager);
}
ReportDataSource companyProviderContactManagerDS = new ReportDataSource("CompProContactManager", companyProviderContactManager);
listDS.Add(companyProviderContactManagerDS);
ICollection<Customer> customer = new List<Customer>();
if (_db.GetPremiseProviderByPremiseId(PremiseId) != null)
{
Customer cust = _db.GetPremiseProviderByPremiseId(PremiseId).Customer;
customer.Add(cust);
}
ReportDataSource customerDS = new ReportDataSource("Customer", customer);
listDS.Add(customerDS);
RenderReport(localReport, listDS, companyProvider.logo);
return View();
}
private void RenderReport(LocalReport localReport, List<ReportDataSource> listDS, byte[] logo)
{
foreach (ReportDataSource ds in listDS)
{
localReport.DataSources.Add(ds);
}
HttpContextBase imageDirectoryPath = HttpContext;
string reportType = "PDF";
string mimeType;
string encoding;
string fileNameExtension;
//The DeviceInfo settings should be changed based on the reportType
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>PDF</OutputFormat>" +
" <PageWidth>8.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.5in</MarginTop>" +
" <MarginLeft>0.5in</MarginLeft>" +
" <MarginRight>0.5in</MarginRight>" +
" <MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
//Render
renderedBytes = localReport.Render(
reportType,
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
//Write to the outputstream
//Set content-disposition to "attachment" so that user is prompted to take an action
//on the file (open or save)
Response.Clear();
Response.ContentType = mimeType;
Response.AddHeader("content-disposition", "attachment; filename=Pricing." + fileNameExtension);
Response.BinaryWrite(renderedBytes);
Response.End();
}
Any suggestion?

Related

Read .csv file from FTP in asp.net [duplicate]

I want to read a file from a FTP server without downloading it to a local file. I wrote a function but it does not work:
private string GetServerVersion()
{
WebClient request = new WebClient();
string url = FtpPath + FileName;
string version = "";
request.Credentials = new NetworkCredential(ftp_user, ftp_pas);
try
{
byte[] newFileData = request.DownloadData(new Uri(FtpPath)+FileName);
string fileString = System.Text.Encoding.UTF8.GetString(newFileData);
}
catch (WebException e)
{
}
return version;
}
Here's a simple working example using your code to grab a file from the Microsoft public FTP servers:
WebClient request = new WebClient();
string url = "ftp://ftp.microsoft.com/developr/fortran/" +"README.TXT";
request.Credentials = new NetworkCredential("anonymous", "anonymous#example.com");
try
{
byte[] newFileData = request.DownloadData(url);
string fileString = System.Text.Encoding.UTF8.GetString(newFileData);
Console.WriteLine(fileString);
}
catch (WebException e)
{
// Do something such as log error, but this is based on OP's original code
// so for now we do nothing.
}
I reckon you're missing a slash on this line here in your code:
string url = FtpPath + FileName;
Perhaps between FtpPath and FileName ?
Small binary file
If the file is small, the easiest way is using WebClient.DownloadData:
WebClient client = new WebClient();
string url = "ftp://ftp.example.com/remote/path/file.zip";
client.Credentials = new NetworkCredential("username", "password");
byte[] contents = client.DownloadData(url);
Small text file
If the small file is a text file, use WebClient.DownloadString:
string contents = client.DownloadString(url);
It assumes that the file contents is in UTF-8 encoding (a plain ASCII file will do too). If you need to use a different encoding, use WebClient.Encoding property.
Large binary file
If the file is large, so that you need to process it in chunks, instead of loading it to memory whole, use FtpWebRequest:
FtpWebRequest request =
(FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;
using (Stream stream = request.GetResponse().GetResponseStream())
{
byte[] buffer = new byte[10240];
int read;
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
// process the chunk in "buffer"
}
}
You can also simplify the code by using WebClient.OpenRead.
Large text file
If the large file is a text file and you want to process it by lines, instead of by chunks of a fixed size, use StreamReader:
FtpWebRequest request =
(FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.txt");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;
using (Stream stream = request.GetResponse().GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
// process the line
Console.WriteLine(line);
}
}
Again, this assumes UTF-8 encoding. If you want to use another encoding, use an overload of StreamReader constructor that takes also Encoding.
As previously, you can simplify the code by using WebClient.OpenRead.
Stream interface
Though, in many cases, you will want to use the downloaded data in some API that uses the Stream interface. In that case, instead of using any of the solutions above, directly use the stream returned by request.GetResponse().GetResponseStream() or WebClient.OpenRead in the API.
For an example, see Transferring files from FTP directly to Azure Blob storage in C#.
The code you have above is very simillar to another Stackoverlow example I found and used myself 2 days ago. Provided you set the URI, User and Password correctly, it will download the file and set the contents to FileString. I'm not sure what you mean by wanting to read the file without downloading it. This is not really an option.
If you want to look at file attributes (I see you mention "version"), you could use the code below to get all the file Name, Data, and Size from the FTP server without downloading the file.
Call GetFileInfo and pass in the file name (make sure you follow through the code to set the full FTP path, User and Password). This will give you back a FTPFileInfo object with a Name, Date and Size.
public static FTPFileInfo GetFileInfo(string fileName)
{
var dirInfo = WordstockExport.GetFTPDirectoryDetails();
var list = FTPFileInfo.Load(dirInfo);
try
{
FTPFileInfo ftpFile = list.SingleOrDefault(f => f.FileName == fileName);
return ftpFile;
}
catch { }
return null;
}
class FTPFileInfo
{
private DateTime _FileDate;
private long _FileSize;
private string _FileName;
public DateTime FileDate
{
get { return _FileDate; }
set { _FileDate = value; }
}
public long FileSize
{
get { return _FileSize; }
set { _FileSize = value; }
}
public string FileName
{
get { return _FileName; }
set { _FileName = value; }
}
public FTPFileInfo() { }
public static FTPFileInfo LoadFromLine(string line)
{
FTPFileInfo file = new FTPFileInfo();
string[] ftpFileInfo = line.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
file._FileDate = DateTime.Parse(ftpFileInfo[0] + " " + ftpFileInfo[1]);
file._FileSize = long.Parse(ftpFileInfo[2]);
file._FileName = ftpFileInfo[3];
return file;
}
public static List<FTPFileInfo> Load(string listDirectoryDetails)
{
List<FTPFileInfo> files = new List<FTPFileInfo>();
string[] lines = listDirectoryDetails.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
foreach(var line in lines)
files.Add(LoadFromLine(line));
return files;
}
}
private static string GetFTPDirectoryDetails()
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(App.Export_FTPPath);
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
request.Credentials = new NetworkCredential(App.FTP_User, App.FTP_Password);
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
string fileLines = reader.ReadToEnd();
reader.Close();
response.Close();
return fileLines;
}
It is impossible to know what the issue is without details about the error/exception.
At a guess, you do not seem to be assigning a new value to version after the initial declaration
string version = "";
Try changing your code to
version = System.Text.Encoding.UTF8.GetString(newFileData);
C Sharp GUI app. Minimal ftp transfer, not elegant but it works fine.
GUI, not console.
Weather from noaa. Find your region (look for your metar)!
A METAR weather report is predominantly used by pilots in fulfillment of a part of a pre- flight
Build with vs 2012 premium RC (july 2012)
(click on label, not button)
using System;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Collections.Generic;
namespace getweather
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void CYYY_Click(object sender, EventArgs e)
{
WebClient request = new WebClient();
string url = "ftp://tgftp.nws.noaa.gov/data/observations/metar/decoded/CYYY.TXT";
request.Credentials = new NetworkCredential("anonymous", "anonymous#example.com");
byte[] newFileData = request.DownloadData(url);
string fileString = System.Text.Encoding.UTF8.GetString(newFileData);
richTextBox1.Text = fileString;
}
private void CYSC_Click(object sender, EventArgs e)
{
WebClient request = new WebClient();
string url = "ftp://tgftp.nws.noaa.gov/data/observations/metar/decoded/CYSC.TXT";
request.Credentials = new NetworkCredential("anonymous", "anonymous#example.com");
byte[] newFileData = request.DownloadData(url);
string fileString = System.Text.Encoding.UTF8.GetString(newFileData);
richTextBox1.Text = fileString;
}
private void CYQB_Click(object sender, EventArgs e)
{
WebClient request = new WebClient();
string url = "ftp://tgftp.nws.noaa.gov/data/observations/metar/decoded/CYQB.TXT";
request.Credentials = new NetworkCredential("anonymous", "anonymous#example.com");
byte[] newFileData = request.DownloadData(url);
string fileString = System.Text.Encoding.UTF8.GetString(newFileData);
richTextBox1.Text = fileString;
}
private void CYUY_Click(object sender, EventArgs e)
{
WebClient request = new WebClient();
string url = "ftp://tgftp.nws.noaa.gov/data/observations/metar/decoded/CYUY.TXT";
request.Credentials = new NetworkCredential("anonymous", "anonymous#example.com");
byte[] newFileData = request.DownloadData(url);
string fileString = System.Text.Encoding.UTF8.GetString(newFileData);
richTextBox1.Text = fileString;
}
private void CYHU_Click(object sender, EventArgs e)
{
WebClient request = new WebClient();
string url = "ftp://tgftp.nws.noaa.gov/data/observations/metar/decoded/CYHU.TXT";
request.Credentials = new NetworkCredential("anonymous", "anonymous#example.com");
byte[] newFileData = request.DownloadData(url);
string fileString = System.Text.Encoding.UTF8.GetString(newFileData);
richTextBox1.Text = fileString;
}
}
}
WebClient request = new WebClient();
string url = "ftp://ftp.microsoft.com/developr/fortran/" +"README.TXT";
request.Credentials = new NetworkCredential("anonymous", "anonymous#example.com");
request.Proxy = null;
try
{
byte[] newFileData = request.DownloadData(url);
string fileString = System.Text.Encoding.UTF8.GetString(newFileData);
Console.WriteLine(fileString);
}
catch (WebException e)
{
// Do something such as log error, but this is based on OP's original code
// so for now we do nothing.
}
I know this is an old question, but I thought I'd suggest using path.combine for the next guy reading this. Helps clean up these kinds of issues.
string url = Path.Combine("ftp://ftp.microsoft.com/developr/fortran", "README.TXT");
We can use below method to get the file attribute from ftp without downloading the file.This is working fine for me.
public DataTable getFileListFTP(string serverIP,string userID,string Password)
{
DataTable dt = new DataTable();
string[] fileListArr;
string fileName = string.Empty;
long fileSize = 0;
// DateTime creationDate;
string creationDate;
FtpWebRequest Request = (FtpWebRequest)WebRequest.Create(serverIP);
Request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
Request.Credentials = new NetworkCredential(userID,Password);
FtpWebResponse Response = (FtpWebResponse)Request.GetResponse();
Stream ResponseStream = Response.GetResponseStream();
StreamReader Reader = new StreamReader(ResponseStream);
dt.Columns.Add("FileName", typeof(String));
dt.Columns.Add("FileSize", typeof(String));
dt.Columns.Add("CreationDate", typeof(DateTime));
//CultureInfo c = new CultureInfo("ES-ES");
while (!Reader.EndOfStream)//Read file name
{
fileListArr = Convert.ToString(Reader.ReadLine()).Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
fileSize = long.Parse(fileListArr[4]);
creationDate = fileListArr[6] + " " + fileListArr[5] + " " + fileListArr[7];
//creationDate =Convert.ToDateTime(fileListArr[6] + " " + fileListArr[5] + " " + fileListArr[7], c).ToString("dd/MMM/yyyy", DateTimeFormatInfo.InvariantInfo);
fileName = Convert.ToString(fileListArr[8]);
DataRow drow = dt.NewRow();
drow["FileName"] = fileName;
drow["FileSize"] = fileName;
drow["CreationDate"] = creationDate;
dt.Rows.Add(drow);
}
Response.Close();
ResponseStream.Close();
Reader.Close();
return dt;
}
Take a look at my FTP class, it might be exactly what you need.
Public Class FTP
'-------------------------[BroCode]--------------------------
'----------------------------FTP-----------------------------
Private _credentials As System.Net.NetworkCredential
Sub New(ByVal _FTPUser As String, ByVal _FTPPass As String)
setCredentials(_FTPUser, _FTPPass)
End Sub
Public Sub UploadFile(ByVal _FileName As String, ByVal _UploadPath As String)
Dim _FileInfo As New System.IO.FileInfo(_FileName)
Dim _FtpWebRequest As System.Net.FtpWebRequest = CType(System.Net.FtpWebRequest.Create(New Uri(_UploadPath)), System.Net.FtpWebRequest)
_FtpWebRequest.Credentials = _credentials
_FtpWebRequest.KeepAlive = False
_FtpWebRequest.Timeout = 20000
_FtpWebRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile
_FtpWebRequest.UseBinary = True
_FtpWebRequest.ContentLength = _FileInfo.Length
Dim buffLength As Integer = 2048
Dim buff(buffLength - 1) As Byte
Dim _FileStream As System.IO.FileStream = _FileInfo.OpenRead()
Try
Dim _Stream As System.IO.Stream = _FtpWebRequest.GetRequestStream()
Dim contentLen As Integer = _FileStream.Read(buff, 0, buffLength)
Do While contentLen <> 0
_Stream.Write(buff, 0, contentLen)
contentLen = _FileStream.Read(buff, 0, buffLength)
Loop
_Stream.Close()
_Stream.Dispose()
_FileStream.Close()
_FileStream.Dispose()
Catch ex As Exception
MessageBox.Show(ex.Message, "Upload Error: ", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Public Sub DownloadFile(ByVal _FileName As String, ByVal _ftpDownloadPath As String)
Try
Dim _request As System.Net.FtpWebRequest = System.Net.WebRequest.Create(_ftpDownloadPath)
_request.KeepAlive = False
_request.Method = System.Net.WebRequestMethods.Ftp.DownloadFile
_request.Credentials = _credentials
Dim _response As System.Net.FtpWebResponse = _request.GetResponse()
Dim responseStream As System.IO.Stream = _response.GetResponseStream()
Dim fs As New System.IO.FileStream(_FileName, System.IO.FileMode.Create)
responseStream.CopyTo(fs)
responseStream.Close()
_response.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "Download Error: ", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Public Function GetDirectory(ByVal _ftpPath As String) As List(Of String)
Dim ret As New List(Of String)
Try
Dim _request As System.Net.FtpWebRequest = System.Net.WebRequest.Create(_ftpPath)
_request.KeepAlive = False
_request.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails
_request.Credentials = _credentials
Dim _response As System.Net.FtpWebResponse = _request.GetResponse()
Dim responseStream As System.IO.Stream = _response.GetResponseStream()
Dim _reader As System.IO.StreamReader = New System.IO.StreamReader(responseStream)
Dim FileData As String = _reader.ReadToEnd
Dim Lines() As String = FileData.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
For Each l As String In Lines
ret.Add(l)
Next
_reader.Close()
_response.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "Directory Fetch Error: ", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Return ret
End Function
Private Sub setCredentials(ByVal _FTPUser As String, ByVal _FTPPass As String)
_credentials = New System.Net.NetworkCredential(_FTPUser, _FTPPass)
End Sub
End Class
To initialize:
Dim ftp As New FORM.FTP("username", "password")
ftp.UploadFile("c:\file.jpeg", "ftp://domain/file.jpeg")
ftp.DownloadFile("c:\file.jpeg", "ftp://ftp://domain/file.jpeg")
Dim directory As List(Of String) = ftp.GetDirectory("ftp://ftp.domain.net/")
ListBox1.Items.Clear()
For Each item As String In directory
ListBox1.Items.Add(item)
Next
https://stackoverflow.com/a/28669746/2701974

bulk data export to excel and download in ashx file

I have an asp.net application in which I have a js file and an ashx file. Here in a download button click Im calling handler file in ajax call and retrieving sql table data in a json formatted string/data table and Im trying to export json formated string/data table to excel/csv file and download it. Please help me to find a solution. (Need a solution which help to export large amount of data and download)
I tried the below code but its not downloading excel file.
public void ProcessRequest(HttpContext context)
{
context.Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");
context.Response.ContentType = "application/csv";
HttpResponse response = context.Response;
string exportContent = ExportToSpreadsheet(JsonStringToDataTable(GetDataFromTable()),'excelfilename');
response.Write(exportContent);
context.Response.End();
}
public DataTable JsonStringToDataTable(string jsonString)
{
DataTable dt = new DataTable();
string[] jsonStringArray = Regex.Split(jsonString.Replace("[", "").Replace("]", ""), "},{");
List<string> ColumnsName = new List<string>();
foreach (string jSA in jsonStringArray)
{
string[] jsonStringData = Regex.Split(jSA.Replace("{", "").Replace("}", ""), ",");
foreach (string ColumnsNameData in jsonStringData)
{
try
{
int idx = ColumnsNameData.IndexOf(":");
string ColumnsNameString = ColumnsNameData.Substring(0, idx - 1).Replace("\"", "");
if (!ColumnsName.Contains(ColumnsNameString))
{
ColumnsName.Add(ColumnsNameString);
}
}
catch (Exception ex)
{
//throw new Exception(string.Format(ex.Message + "Error Parsing Column Name : {0}", ColumnsNameData));
throw ex;
}
}
break;
}
foreach (string AddColumnName in ColumnsName)
{
dt.Columns.Add(AddColumnName);
}
foreach (string jSA in jsonStringArray)
{
string[] RowData = Regex.Split(jSA.Replace("{", "").Replace("}", ""), ",");
DataRow nr = dt.NewRow();
foreach (string rowData in RowData)
{
try
{
int idx = rowData.IndexOf(":");
string RowColumns = rowData.Substring(0, idx - 1).Replace("\"", "");
string RowDataString = rowData.Substring(idx + 1).Replace("\"", "");
nr[RowColumns] = RowDataString;
}
catch (Exception ex)
{
continue;
}
}
dt.Rows.Add(nr);
}
return dt;
}
private static string GetDataFromTable()
{
string returnValue = string.Empty;
var serializer = new JavaScriptSerializer { MaxJsonLength = Int32.MaxValue };
try
{
var result = //get data from sql table;
returnValue = serializer.Serialize(result);
}
catch (Exception e)
{
returnValue = serializer.Serialize(e.Message);
}
return returnValue;
}
public string ExportToSpreadsheet(DataTable table, string name)
{
string res = string.Empty;
try
{
//var resp = Response;
System.Web.HttpResponse resp = System.Web.HttpContext.Current.Response;
resp.Clear();
if (table != null)
{
foreach (DataColumn column in table.Columns)
{
resp.Write(column.ColumnName + ",");
}
}
resp.Write(Environment.NewLine);
if (table != null)
{
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
resp.Write(row[i].ToString().Replace(",", string.Empty) + ",");
}
resp.Write(Environment.NewLine);
}
}
res = "successfully downloaded";
resp.ContentType = "text/csv";
resp.AppendHeader("Content-Disposition", "attachment; filename=" + name + ".csv");
// resp.End();
}
catch(Exception ex)
{
res = ex.Message;
}
return res;
}
Start using a specialized libary like EPPlus. It will create real Excel files.
private void exportToExcel(DataTable dataTable)
{
using (ExcelPackage excelPackage = new ExcelPackage())
{
//create the worksheet
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("Sheet 1");
//load the datatable into the sheet, with headers
worksheet.Cells["A1"].LoadFromDataTable(dataTable, true);
//send the file to the browser
byte[] bin = excelPackage.GetAsByteArray();
Response.ClearHeaders();
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-length", bin.Length.ToString());
Response.AddHeader("content-disposition", "attachment; filename=\"ExcelDemo.xlsx\"");
Response.OutputStream.Write(bin, 0, bin.Length);
Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}

asp.net C# webform show report without reportviewer

currently i want to generate the report without showing in reportviewer. I search for the solution online but i only can find the MVC approach. I cant convert it to normal webform behavior.
public ActionResult Report(string id)
{
LocalReport lr = new LocalReport();
string path = Path.Combine(Server.MapPath("~/Report"), "ReportStateArea.rdlc");
if (System.IO.File.Exists(path))
{
lr.ReportPath = path;
}
else
{
return View("Index");
}
List<StateArea> cm = new List<StateArea>();
using (PopulationEntities dc = new PopulationEntities())
{
cm = dc.StateAreas.ToList();
}
ReportDataSource rd = new ReportDataSource("MyDataset", cm);
lr.DataSources.Add(rd);
string reportType = id;
string mimeType;
string encoding;
string fileNameExtension;
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>" + id + "</OutputFormat>" +
" <PageWidth>8.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.5in</MarginTop>" +
" <MarginLeft>1in</MarginLeft>" +
" <MarginRight>1in</MarginRight>" +
" <MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
renderedBytes = lr.Render(
reportType,
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
return File(renderedBytes, mimeType);
}
enter code here
Here is the sample of code that can allow user to generate the report in different format such as PDF, excel, image. ( http://www.dotnetawesome.com/2013/09/microsoft-report-in-mvc-4.html ).
Anyone can help or provide me a website which have a simple tutorial of that by using the SQL select statement instead of LINQ ?
As far as returning the report from a WebForms page, what you have above is actually pretty close. You want to return the renderedBytes array through the Response object of your current Page context like:
protected void ReportPrint_Click(object sender, EventArgs e)
{
string id = "PDF"; // get this from another control on your page
LocalReport lr = new LocalReport();
string path = Path.Combine(Server.MapPath("~/Report"), "ReportStateArea.rdlc");
if (System.IO.File.Exists(path))
{
lr.ReportPath = path;
}
else
{
// handle error condition
}
List<StateArea> cm = new List<StateArea>();
using (PopulationEntities dc = new PopulationEntities())
{
cm = dc.StateAreas.ToList();
}
ReportDataSource rd = new ReportDataSource("MyDataset", cm);
lr.DataSources.Add(rd);
string reportType = id;
string mimeType;
string encoding;
string fileNameExtension;
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>" + id + "</OutputFormat>" +
" <PageWidth>8.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.5in</MarginTop>" +
" <MarginLeft>1in</MarginLeft>" +
" <MarginRight>1in</MarginRight>" +
" <MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
renderedBytes = lr.Render(
reportType,
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
Response.Clear(); // we're going to override the default page response
Response.ContentType = mimeType;
Response.AddHeader("content-disposition", "attachment; filename=report." + fileNameExtension);
Response.BinaryWrite(renderedBytes);
Response.End();
}
This will replace the normal page response with your report content.
As far as SQL vs Linq, the DataSource object that ReportViewer uses is the old-style System.Data.DataTable so just look for information on populating a DataTable from SQL.

set a constant(same) time stamp for multiple data base rows

I'm creating an asp.net mvc4 application, that can write data into database tables from excel sheets(using sqlbulkcopy column mapping). when we select excel sheet and submit, it is writing data into database.
Now I want to set file uploaded time as timestamp for each data rows when it write data into database table.
Code:
namespace AFFEMS2_HEC.Controllers
{
public class ExcelController : Controller
{
//
// GET: /Excel/
public ActionResult Index()
{
return View();
}
[HttpPost]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(HttpPostedFileBase FileUpload1)
{
//Upload and save the file
if (Request.Files["FileUpload1"].ContentLength > 0)
{
string excelPath = Path.Combine(HttpContext.Server.MapPath("~/Content/"), Path.GetFileName(FileUpload1.FileName));
FileUpload1.SaveAs(excelPath);
string conString = string.Empty;
string extension = Path.GetExtension(FileUpload1.FileName);
switch (extension)
{
case ".xls": //Excel 97-03
conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
break;
case ".xlsx": //Excel 07 or higher
conString = ConfigurationManager.ConnectionStrings["Excel07+ConString"].ConnectionString;
break;
}
conString = string.Format(conString, excelPath);
using (OleDbConnection excel_con = new OleDbConnection(conString))
{
string sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString();
string sheet2 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[1]["TABLE_NAME"].ToString();
DataTable dtExcelData = new DataTable();
//[OPTIONAL]: It is recommended as otherwise the data will be considered as String by default.
dtExcelData.Columns.AddRange(new DataColumn[4] {
new DataColumn("Id", typeof(string)),
new DataColumn("Name", typeof(string)),
new DataColumn("Email",typeof(string)),
new DataColumn("Mobile", typeof(int)) });
string query = "SELECT s1.Id, " +
"s1.Name, " +
"s1.Mobile, " +
"s2.Email " +
"FROM ([" + sheet1 + "] as s1 INNER JOIN [" + sheet2 + "] as s2 ON " + "s1.Id = s2.Id)";
using (OleDbDataAdapter oda = new OleDbDataAdapter(query, excel_con))
{
oda.Fill(dtExcelData);
}
excel_con.Close();
string consString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(consString))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con,
SqlBulkCopyOptions.CheckConstraints|
SqlBulkCopyOptions.FireTriggers|
SqlBulkCopyOptions.KeepNulls|
SqlBulkCopyOptions.TableLock|
SqlBulkCopyOptions.UseInternalTransaction,
null))
{
//Set the database table name
sqlBulkCopy.DestinationTableName = "User1";
sqlBulkCopy.ColumnMappings.Add("Id", "Id");
sqlBulkCopy.ColumnMappings.Add("Name", "Name");
sqlBulkCopy.ColumnMappings.Add("Email", "Email");
sqlBulkCopy.ColumnMappings.Add("Mobile", "Mobile");
con.Open();
try
{
// Write from the source to the destination
sqlBulkCopy.WriteToServer(dtExcelData);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
con.Close();
}
}
}
}
}
return View();
}
}
}
Just create another column as "TimeStamp_Inserted" but it type should be datetime or
nvarchar
and try to replace following code snippet
string query = "SELECT s1.Id, " +
"s1.Name, " +
"s1.Mobile, " +
"s2.Email " +
"'"+DateTime.Now.ToString() +"'"+" as TimeStamp_Inserted"+
"FROM ([" + sheet1 + "] as s1 INNER JOIN [" + sheet2 + "] as s2 ON " + "s1.Id = s2.Id)";
sqlbulkcopy column mapping try to change like this
sqlBulkCopy.DestinationTableName = "User1";
sqlBulkCopy.ColumnMappings.Add("Id", "Id");
sqlBulkCopy.ColumnMappings.Add("Name", "Name");
sqlBulkCopy.ColumnMappings.Add("Email", "Email");
sqlBulkCopy.ColumnMappings.Add("Mobile", "Mobile");
sqlBulkCopy.ColumnMappings.Add("TimeStamp_Inserted", "TimeStamp");
con.Open();
just try it

how to display a .docx file in ckeditor?

I am making a website in ASP.NET using C#. I have stored .docx file in database in binary form. I have successfully retrieved it but now my task is that I have to open .docx file from database in ckeditor. And if I make any changes then the file in the database should be updated.
Code for saving .docx file in DB...
private Boolean InsertUpdateData(SqlCommand cmd)
{
String strConnString = System.Configuration.ConfigurationManager
.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}
}
protected void btnUpload_Click(object sender, EventArgs e)
{
// Read the file and convert it to Byte Array
string filePath = FileUpload1.PostedFile.FileName;
string filename = Path.GetFileName(filePath);
string ext = Path.GetExtension(filename);
string contenttype = String.Empty;
//Set the contenttype based on File Extension
switch (ext)
{
case ".doc":
contenttype = "application/vnd.ms-word";
break;
case ".docx":
contenttype = "application/vnd.ms-word";
break;
case ".xls":
contenttype = "application/vnd.ms-excel";
break;
case ".xlsx":
contenttype = "application/vnd.ms-excel";
break;
case ".jpg":
contenttype = "image/jpg";
break;
case ".png":
contenttype = "image/png";
break;
case ".gif":
contenttype = "image/gif";
break;
case ".pdf":
contenttype = "application/pdf";
break;
}
if (contenttype != String.Empty)
{
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
//insert the file into database
string strQuery = "insert into tblFiles(Name, ContentType, Data)" +
" values (#Name, #ContentType, #Data)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = filename;
cmd.Parameters.Add("#ContentType", SqlDbType.VarChar).Value
= contenttype;
cmd.Parameters.Add("#Data", SqlDbType.Binary).Value = bytes;
InsertUpdateData(cmd);
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "File Uploaded Successfully";
}
else
{
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "File format not recognised." +
" Upload Image/Word/PDF/Excel formats";
}
}
Retrieving from DB...
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager
.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch
{
return null;
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
private void download(DataTable dt)
{
Byte[] bytes = (Byte[])dt.Rows[0]["Data"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = dt.Rows[0]["ContentType"].ToString();
Response.AddHeader("content-disposition", "attachment;filename="
+ dt.Rows[0]["Name"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
protected void btnshow_Click(object sender, EventArgs e)
{
string s1 = proclist.SelectedItem.Value;
string str1 = "";
db.con.Open();
try
{
string str = "select Name, ContentType, Data from tblFiles where Name='" + proclist.SelectedItem.Value + "'";
db.com = new SqlCommand(str, db.con);
SqlDataReader dr = db.com.ExecuteReader();
DataTable dt = GetData(db.com);
if (dt != null)
{
download(dt);
}
}
catch (NullReferenceException ex)
{
ex.ToString();
}
db.con.Close();
}
Javascript method:
function button_convertDocxToHTML_DisplayInCKEditor() {
$.ajax({
type: "POST",
async: false,
url: "Page.aspx/GetHTML",
data: "{'pathFile':'UploadFolder/',
'fileName':'docName',
'extensionFile':'.docx'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var resultHtml = result.d;
var objEditor = CKEDITOR.instances["yourID_Description"];
objEditor.setData(resultHtml);
},
error: function (result) {
// Unexpected error...
return false;
}
});
}
In the code-behind Page.aspx.cs, we have a web method in the side server. Maybe you will need some using like these:
using System.Reflection;
using System.Runtime.InteropServices;
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string GetHTML(string pathFile, string fileName, string extensionFile)
{
string result = string.Empty;
object path_DocsName = HttpContext.Current.Request.MapPath(pathFile + fileName + extensionFile);
object o = Missing.Value;
object oFalse = false;
object oTrue = true;
Microsoft.Office.Interop.Word._Application app = null;
Microsoft.Office.Interop.Word.Documents docs = null;
Microsoft.Office.Interop.Word.Document doc = null;
StreamReader reader = null;
try
{
app = new Microsoft.Office.Interop.Word.Application
{
Visible = false,
DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone
};
docs = app.Documents;
doc = docs.Open(ref path_DocsName, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o, ref o);
doc.Activate();
string newHtmlFile = HttpContext.Current.Request.MapPath("pathHtmlTEMPORAL/" + fileName + ".html");
// Create html file
doc.SaveAs(FileName: newHtmlFile, FileFormat: Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML);
doc.Close(ref o, ref o, ref o);
app.Quit(ref o, ref o, ref o);
using (reader = new StreamReader(newHtmlFile, Encoding.GetEncoding("utf-8")))
{
result += reader.ReadToEnd();
reader.Dispose();
reader.Close();
}
}
catch (Exception ex)
{
result = Resources.WholeSite.Validation_UnexpectedError + ": " + ex.Message;
}
finally
{
if (doc != null) Marshal.FinalReleaseComObject(doc);
if (docs != null) Marshal.FinalReleaseComObject(docs);
if (app != null) Marshal.FinalReleaseComObject(app);
if (reader != null) { reader.Dispose(); reader.Close(); }
}
return result; // this result has all html that you have to display into CKEditor.
}

Resources