Display or Download Documents Saved in SQL Server with ASP.NET - html

I have documents saved in a SQL Server database as varbinary(MAX).
I am trying to retrieve the document from the database with below code. The problem I am facing is that no matter the browser I use, I don't get any response back. No dialog the browser just displays the turning circle.
Any suggestions would be highly appreciated..
if (e.ButtonID != "Download")
return;
int id = 2;
byte[] bytes;
string fileName, contentType;
string constr = ConfigurationManager.ConnectionStrings["bexsConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Title, WillData, MIMEType from Will_documents where Doc_id = #Id";
cmd.Parameters.AddWithValue("#Id", id);
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
bytes = (byte[])sdr["WillData"];
contentType = sdr["MIMEType"].ToString();
fileName = sdr["Title"].ToString();
Response.Buffer = true;
Response.Charset = "";
Response.Clear();
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = contentType;
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
con.Close();
}
}

Eventually got it Working.
Response.ClearContent();
Response.ContentType = "application/octetstream";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", name));
Response.AddHeader("Content-Length", documentBytes.Length.ToString());
Response.BinaryWrite(documentBytes);
Response.Flush();
Response.Close();

Related

SSRS Report Execution Service: export to xlsx without error

Hello thanks for looking.
I have some .net code that uses the SSRS Report Execution Service to download a report for the user as an xlsx file.
It works & everything in the report is present & accounted for.
One annoying thing though. When opened in Excel 365 it gives a popup saying:
We found a problem with some content in "theReport.xlsx" Do you want us to try to recover as much as we can? If you trust the source of this workbook click yes
When I click yes then it indicates that the workbook was repaired and the report looks normal.
It does not give any indication what it repaired in the log file, just that it was repaired.
Please take a look at my code. Perhaps there is something small I can change to get rid of the error when the Excel sheet is opened.
private void DownloadQuoteExport()
{
string reportName = "reportName";
string fileName = "filename";
//create web services instance
ReportExecutionService rs = getService();
//render report 1st parameter
ParameterValue param1 = new ParameterValue();
param1.Name = "QuoteID";
param1.Value = quoteId.ToString();
try
{
executeReport(reportName, new ParameterValue[] { param1 }, "EXCELOPENXML", fileName, rs);
}
catch (Exception ex)
{
Response.Write(ex.Message + "<br>" + ex.StackTrace.ToString());
}
}
private void executeReport(String reportName, ParameterValue[] rptParams, String rptFormat, string strRptFileName, ReportExecutionService service)
{
string encoding;
string mimeType;
string extension;
Warning[] warnings = null;
string[] streamIDs = null;
string historyID = null;
ExecutionInfo execInfo = new ExecutionInfo();
ExecutionHeader execHeader = new ExecutionHeader();
service.ExecutionHeaderValue = execHeader;
execInfo = service.LoadReport(reportName, historyID);
service.SetExecutionParameters(rptParams, "en-us");
String SessionId = service.ExecutionHeaderValue.ExecutionID;
byte[] result = service.Render(rptFormat, null, out extension, out encoding, out mimeType, out warnings, out streamIDs);
Response.ClearContent();
if (rptFormat == "EXCELOPENXML")
{
Response.AppendHeader("content-disposition", "attachment; filename=" + strRptFileName + ".xlsx");
Response.ContentType = "application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
Response.BinaryWrite(result);
Response.Flush();
}
This is finally what worked.
private void executeReport(String reportName, ParameterValue[] rptParams, String rptFormat, string strRptFileName, ReportExecutionService service)
{
string encoding;
string mimeType;
string extension;
Warning[] warnings = null;
string[] streamIDs = null;
string historyID = null;
ExecutionInfo execInfo = new ExecutionInfo();
ExecutionHeader execHeader = new ExecutionHeader();
service.ExecutionHeaderValue = execHeader;
execInfo = service.LoadReport(reportName, historyID);
service.SetExecutionParameters(rptParams, "en-us");
String SessionId = service.ExecutionHeaderValue.ExecutionID;
byte[] result = service.Render(rptFormat, null, out extension, out encoding, out mimeType, out warnings, out streamIDs);
Response.ClearContent();
Response.Clear();
if (rptFormat == "EXCELOPENXML")
{
Response.AppendHeader("content-disposition", "attachment; filename=" + strRptFileName + ".xlsx");
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
Response.BinaryWrite(result);
Response.Flush();
Response.SuppressContent = true;
try
{
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
catch (ThreadAbortException ex)
{
//ignore
}
}

MySQL Process List has too many process. Is it normal?

I created an Android app like social media app. I'm using ASP.NET web services for fetching data with JSON or process data like INSERT, UPDATE, DELETE. And I'm using MySQL database.
Number of active users is about 2,5k and daily average is 1,5k.
Anyway, when I control process list with "show processlist;" on phpMyAdmin , there are a lot of process; some processes has Sleep command value. So this situation gets errors like decreasing app speed and some times "max_user_connections".
So, I closed all connections after completing process of database on Web Service, but still have that issue or errors.
[WebMethod]
public string ABC(int x, string y)
{
using (con = new MySqlConnection(conString))
{
List<Profile> result= new List<Profile>();
result.Add(new Profile
{
posts= ""
});
List<ClassA> resultA= new List<ClassA>();
query= "SELECT COUNT(FollowId) FROM Followings WHERE FUserId = " + x;
con.Open();
cmd = new MySqlCommand(query, con);
dr = cmd.ExecuteReader();
string count = "0";
while (dr.Read())
{
count = dr[0].ToString();
}
dr.Close();
con.Close();
query= "SELECT COUNT(FollowId) FROM Followings WHERE FollowingUserId = " + x;
con.Open();
cmd = new MySqlCommand(query, con);
dr = cmd.ExecuteReader();
string count2 = "0";
while (dr.Read())
{
count2 = dr[0].ToString();
}
dr.Close();
con.Close();
query= "SELECT .... FROM Posts WHERE UserId = " + x+ " ORDER BY PostId DESC LIMIT 30";
con.Open();
cmd = new MySqlCommand(query, con);
dr = cmd.ExecuteReader();
int i;
int count3 = 0;
while (dr.Read())
{
count3++;
i = 0;
resultA.Add(new ClassA
{
postId = Convert.ToInt32(dr[i]),
postUrl = dr[++i].ToString(),
... = Convert.ToInt32(dr[++i])
});
}
dr.Close();
con.Close();
string json = "";
if (resultA.Count > 0)
{
json = JsonConvert.SerializeObject(resultA);
}
result[0].posts = json;
json = "";
if (result.Count > 0)
{
json = JsonConvert.SerializeObject(result);
}
return json;
}
}
It's any example of my web methods. Where do I mistake ?
Thanks for replies.

Quartz.net windows service does not execute job which referencesSSRS web service

I have used two web references of ssrs reporting execution service to generate the report. I am using quartz.net windows service for scheduling ssrs reports. My Windows service is working when I use the StdSchedulerFactory.GetDefaultScheduler() but as I execute my job in a Quartz service remotely and use GetScheduler() , it's not working.
public void Execute(IJobExecutionContext context)
{
RS2005.ReportingService2005 rs;
RE2005.ReportExecutionService rsExec;
// Create a new proxy to the web service
rs = new RS2005.ReportingService2005();
rsExec = new RE2005.ReportExecutionService();
// Authenticate to the Web service using Windows credentials
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
rsExec.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs.Url = "http://127.0.0.1:7001/ReportServer/reportservice2005.asmx";
rsExec.Url = "http://127.0.0.1:7001/ReportServer/reportexecution2005.asmx";
string historyID = null;
string deviceInfo = null;
string format = "PDF";
Byte[] results;
string encoding = String.Empty;
string mimeType = String.Empty;
string extension = String.Empty;
RE2005.Warning[] warnings = null;
string[] streamIDs = null;
// Path of the Report - XLS, PDF etc.
string fileName = "samplereport.pdf";
// Name of the report - Please note this is not the RDL file.
string _reportName = #"/reports_Debug/reportname";
string _historyID = null;
bool _forRendering = false;
RS2005.ParameterValue[] _values = null;
RS2005.DataSourceCredentials[] _credentials = null;
RS2005.ReportParameter[] _parameters = null;
try
{
_parameters = rs.GetReportParameters(_reportName, _historyID, _forRendering, _values, _credentials);
RE2005.ExecutionInfo ei = rsExec.LoadReport(_reportName, historyID);
RE2005.ParameterValue[] parameters = new RE2005.ParameterValue[8];
if (_parameters.Length > 0)
{
parameters[0] = new RE2005.ParameterValue();
parameters[0].Name = "FromDate";
parameters[0].Value = "1/1/2016";
parameters[1] = new RE2005.ParameterValue();
parameters[1].Name = "ToDate";
parameters[1].Value = "1/21/2016"; // June
}
rsExec.SetExecutionParameters(parameters, "en-us");
results = rsExec.Render(format, deviceInfo,
out extension, out encoding,
out mimeType, out warnings, out streamIDs);
using (FileStream stream = File.OpenWrite(fileName))
{
stream.Write(results, 0, results.Length);
}
}
catch (Exception ex)
{
throw ex;
}
}

Store .txt files into Mysql as Blob from ASP.Net MVC3

Currently I'm Working on ASP.NET MVC 3 Project. I need to Store text(.txt) files into MySQL as Blob. MySQL is New to me.
Should be something like this (Connectionstring should be modified):
string filePath = #"C:\\MyFile.ext";
//A stream of bytes that represnts the binary file
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
//The reader reads the binary data from the file stream
BinaryReader reader = new BinaryReader(fs);
//Bytes from the binary reader stored in BlobValue array
byte[] BlobValue = reader.ReadBytes((int)fs.Length);
fs.Close();
reader.Close();
SqlConnection BlobsDatabaseConn = new SqlConnection("Data Source = .; Initial Catalog = BlobsDatabase; Integrated Security = SSPI");
SqlCommand SaveBlobeCommand = new SqlCommand();
SaveBlobeCommand.Connection = BlobsDatabaseConn;
SaveBlobeCommand.CommandType = CommandType.Text;
SaveBlobeCommand.CommandText = "INSERT INTO BlobsTable(BlobFileName, BlobFile)" + "VALUES (#BlobFileName, #BlobFile)";
SqlParameter BlobFileNameParam = new SqlParameter("#BlobFileName", SqlDbType.NChar);
SqlParameter BlobFileParam = new SqlParameter("#BlobFile", SqlDbType.Binary);
SaveBlobeCommand.Parameters.Add(BlobFileNameParam);
SaveBlobeCommand.Parameters.Add(BlobFileParam);
BlobFileNameParam.Value = filePath.Substring(filePath.LastIndexOf("\\") + 1);
BlobFileParam.Value = BlobValue;
try
{
SaveBlobeCommand.Connection.Open();
SaveBlobeCommand.ExecuteNonQuery();
MessageBox.Show(BlobFileNameParam.Value.ToString() + " saved to database.","BLOB Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Save Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
SaveBlobeCommand.Connection.Close();
}
Take a look at:
Writing BLOB Values to a Database

How to get list of reports

How to list all the reports, that I have created in the report server? Later I would like to use this list to display them in my ReportViewer control.
Report server uses stored procedure called FindObjectsNonRecursive.
string cnxstr = "Data Source=server;Initial Catalog=ReportServer;Integrated Security=SSPI;"; //connection string
using (SqlConnection connection = new SqlConnection(cnxstr))
{
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "FindObjectsNonRecursive";
command.Parameters.Add(new SqlParameter("#Path", "/folder_name"));
command.Parameters.Add(new SqlParameter("#AuthType", 1));
SqlDataReader reader = null;
try
{
reader = command.ExecuteReader();
while (reader.Read())
{
string path = reader["Path"].ToString();
//now you can display this path in your list, or do whatever
}
}
finally
{
if (reader != null)
reader.Close();
}
}