No report display in asp.net mvc using rdlc - asp.net-mvc

I am trying to display the report using the following code unfortunately nothing display or get download.
public ActionResult DetailsReport()
{
LocalReport localReport = new LocalReport();
localReport.ReportPath = Server.MapPath("~/Content/Reports/Data.rdlc");
ReportDataSource reportDataSource = new ReportDataSource("dsData", GetAllData());
localReport.DataSources.Add(reportDataSource);
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>1in</MarginLeft>" +
" <MarginRight>1in</MarginRight>" +
" <MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
//Render the report
renderedBytes = localReport.Render(
reportType,
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
Response.AddHeader("content-disposition", "attachment; filename=Data." + fileNameExtension);
return File(renderedBytes, mimeType);
}
public static List<vwDataReport> GetAllData()
{
var entities = new DataEntities();
var x = from c in entities.vwDataReport
select c;
return x.ToList();
}

Just Comment the following line, then rebuild the project.
Response.AddHeader("content-disposition", "attachment; filename=Data." + fileNameExtension);

Related

Error 403- When trying to retrieve single entity from Azure Table Storage using IHttpClientFactory

Here department is PartitionKey and id is RowKey.
Error: Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
Status Code: Forbidden
If someone could help me to resolve this error It would be great.
Thanks in advance :)
public HttpClient getRequestHeaders(string requestType, HttpClient Newrequest, string storageAccount, string accessKey, string resource, int Length = 0)
{
HttpClient Client = Newrequest;
var RequestDateString = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture);
if (Client.DefaultRequestHeaders.Contains("x-ms-date"))
Client.DefaultRequestHeaders.Remove("x-ms-date");
Client.DefaultRequestHeaders.Add("x-ms-date", RequestDateString);
var requestUri = #"https://" + storageAccount + ".table.core.windows.net/" + resource;
Client.DefaultRequestHeaders.Accept.Clear();
Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
if (Client.DefaultRequestHeaders.Contains("x-ms-version"))
Client.DefaultRequestHeaders.Remove("x-ms-version");
Client.DefaultRequestHeaders.Add("x-ms-version", "2015-12-11");
if (Client.DefaultRequestHeaders.Contains("DataServiceVersion"))
Client.DefaultRequestHeaders.Remove("DataServiceVersion");
Client.DefaultRequestHeaders.Add("DataServiceVersion", "3.0;NetFx");
if (Client.DefaultRequestHeaders.Contains("MaxDataServiceVersion"))
Client.DefaultRequestHeaders.Remove("MaxDataServiceVersion");
Client.DefaultRequestHeaders.Add("MaxDataServiceVersion", "3.0;NetFx");
if (Client.DefaultRequestHeaders.Contains("Authorization"))
Client.DefaultRequestHeaders.Remove("Authorization");
var sas = getAuthToken(Client, storageAccount, accessKey, resource);
Client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", sas);
return Client;
}
public string getAuthToken(HttpClient request, string storageAccount, string accessKey, string resource)
{
try
{
string sAuthTokn = "";
string stringToSign = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture) + "\n";
stringToSign += "/" + storageAccount + "/" + resource;
HMACSHA256 hasher = new HMACSHA256(Convert.FromBase64String(accessKey));
sAuthTokn = "SharedKeyLite " + storageAccount + ":" + Convert.ToBase64String(hasher.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
return sAuthTokn;
}
catch (Exception ex)
{
throw ex;
}
}
public async Task<string> GetEntityByID(string department, string id)
{
EmployeeDetails emp = new EmployeeDetails();
string storageAccount = "sample";
string resourcePath = "SampleAzureTableStorage";
string accessKey = "<sample>";
string uri = #"https://" + storageAccount + ".table.core.windows.net/" + resourcePath + "/";
var request = _httpClientFactory.CreateClient();
request = getRequestHeaders("GET", request, storageAccount, accessKey, resourcePath);
try
{
var httpResponseMessage = await request.GetAsync(uri + department + "/" + id);
httpResponseMessage.EnsureSuccessStatusCode();
return await httpResponseMessage.Content.ReadAsStringAsync();
}
catch (WebException ex)
{
throw ex;
}
}
I believe the reason you are getting this error is because you are using two different dates in your code.
You are getting the current date in getRequestHeaders method and then a different date in getAuthToken. This would cause the authorization header mismatch.
I would recommend modifying getAuthToken method and pass the date/time value computed in getRequestHeaders method.
Try the following code:
public HttpClient getRequestHeaders(string requestType, HttpClient Newrequest, string storageAccount, string accessKey, string resource, string partitionKey, string rowKey, int Length = 0)
{
HttpClient Client = Newrequest;
var RequestDateString = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture);
if (Client.DefaultRequestHeaders.Contains("x-ms-date"))
Client.DefaultRequestHeaders.Remove("x-ms-date");
Client.DefaultRequestHeaders.Add("x-ms-date", RequestDateString);
var requestUri = #"https://" + storageAccount + ".table.core.windows.net/" + resource;
Client.DefaultRequestHeaders.Accept.Clear();
Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
if (Client.DefaultRequestHeaders.Contains("x-ms-version"))
Client.DefaultRequestHeaders.Remove("x-ms-version");
Client.DefaultRequestHeaders.Add("x-ms-version", "2015-12-11");
if (Client.DefaultRequestHeaders.Contains("DataServiceVersion"))
Client.DefaultRequestHeaders.Remove("DataServiceVersion");
Client.DefaultRequestHeaders.Add("DataServiceVersion", "3.0;NetFx");
if (Client.DefaultRequestHeaders.Contains("MaxDataServiceVersion"))
Client.DefaultRequestHeaders.Remove("MaxDataServiceVersion");
Client.DefaultRequestHeaders.Add("MaxDataServiceVersion", "3.0;NetFx");
if (Client.DefaultRequestHeaders.Contains("Authorization"))
Client.DefaultRequestHeaders.Remove("Authorization");
var sas = getAuthToken(Client, storageAccount, accessKey, resource, RequestDateString, partitionKey, rowKey);
Client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", sas);
return Client;
}
public string getAuthToken(HttpClient request, string storageAccount, string accessKey, string resource, string requestDateString, string partitionKey, string rowKey)
{
try
{
string sAuthTokn = "";
string stringToSign = requestDateString + "\n";
stringToSign += "/" + storageAccount + "/" + resource + "(PartitionKey='" + partitionKey + "',RowKey='" + rowKey + "')";
HMACSHA256 hasher = new HMACSHA256(Convert.FromBase64String(accessKey));
sAuthTokn = "SharedKeyLite " + storageAccount + ":" + Convert.ToBase64String(hasher.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
return sAuthTokn;
}
catch (Exception ex)
{
throw ex;
}
}
public async Task<string> GetEntityByID(string department, string id)
{
EmployeeDetails emp = new EmployeeDetails();
string storageAccount = "sample";
string resourcePath = "SampleAzureTableStorage";
string accessKey = "<sample>";
string uri = #"https://" + storageAccount + ".table.core.windows.net/" + resourcePath + "/";
var request = _httpClientFactory.CreateClient();
request = getRequestHeaders("GET", request, storageAccount, accessKey, resourcePath, department, id);
try
{
var httpResponseMessage = await request.GetAsync(uri + "(PartitionKey='" + department + "',RowKey='" + id + "')");
httpResponseMessage.EnsureSuccessStatusCode();
return await httpResponseMessage.Content.ReadAsStringAsync();
}
catch (WebException ex)
{
throw ex;
}
}
I think the problem is in your Authorization header.
Here is your code:
Client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", sas);
I think you should change it to:
Client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"Bearer {sas}");
Otherwise the code looks righteous.

Changing synchronous call to async await(Asynchronous ) MvC controller

I am new to C# Asp.net mvc asynchronous programming. I need to uplaod vidoe to my server but it video upload is locked when I uploading the video. I can not do another tasks in parallel. I have tried like this but it is not working.
public async Task<ActionResult> upload()
{
if (Request.Files.Count > 0)
{
int chunk = Request["chunk"] != null ?
int.Parse(Request["chunk"]) : 0;
string fileName = Request["name"] != null ? Request["name"] :
string.Empty;
string upath = "";
if (Request.Headers["UName"] != null)
upath = Request.Headers["UName"].ToString();
//if (CloudSettings.EnableCloudStorage && upath != "")
// _fileName = upath.Substring(0, 3) + "-" + _fileName; // void duplication in cloud storage
long AlbumID = 0;
if (Request.Headers["MediaID"] != null)
AlbumID = Convert.ToInt64(Request.Headers["MediaID"]);
string uploadPath = "";
// default path
if (upath == "")
uploadPath = UrlConfig.Published_Video_Path(); // direct upload to published area
else
uploadPath = UrlConfig.Published_Video_Path(upath); // source video path
FileStream fs;
using (fs = new FileStream(Path.Combine(uploadPath, fileName), chunk == 0 ? FileMode.Create : FileMode.Append))
{
byte[] buffer = new byte[Request.Files[0].InputStream.Length];
await Request.Files[0].InputStream.ReadAsync(buffer, 0, buffer.Length);
await fs.WriteAsync(buffer, 0, buffer.Length);
}
string url = "";
string filetype = System.IO.Path.GetExtension(fileName);
string fileIndex = fileName.Replace(filetype, "");
string elementid = UtilityBLL.ReplaceSpaceWithHyphin(fileIndex);
//eturn fileName; // "Success";
return this.Content("{\"jsonrpc\" : \"2.0\", \"result\" : \"OK\", \"id\" : \"id\", \"fname\" : \"" + fileName + "\", \"url\" : \"" + url + "\", \"filetype\" : \"" + filetype + "\", \"filename\" : \"" + fileName + "\", \"fileIndex\" : \"" + fileIndex + "\", \"eleid\" : \"" + elementid + "\"}", "text/plain");
}
else
{
return this.Content("failed", "text/plain");
}
}

in mvc4 return html file from different directory

Here is my code, actually i am trying to return a html file from other directory, and my code return the html page, but it doesn't return the Image of that page, can anyone suggest me how to do the same. Mean how to return the html page with image from different directory.
public ActionResult GetHtml()
{
//var encoding = new System.Text.UTF8Encoding();
//var htm = System.IO.File.ReadAllText(ConfigurationManager.AppSettings["ServerFilePath"].ToString()
+ "CPL\\" + "CPLPolicy\\" + "IMS.htm", encoding);
//byte[] data = encoding.GetBytes(htm);
//Response.OutputStream.Write(data, 0, data.Length);
//Response.OutputStream.Flush();
//Response.AddHeader("Content-Disposition", new System.Net.Mime.ContentDisposition { Inline = true, FileName = "index.htm" }.ToString());
//return File(ConfigurationManager.AppSettings["ServerFilePath"].ToString() + "CPL\\" + "CPLPolicy\\" + "IMS.htm", "text/plain");
//return File(ConfigurationManager.AppSettings["ServerFilePath"].ToString() + "CPL\\" + "CPLPolicy\\" + "IMS.htm", "text/html");
var result = new FilePathResult(ConfigurationManager.AppSettings["ServerFilePath"].ToString()
+ "CPL\\" + "CPLPolicy\\" + "IMS.htm", "text/html");
return result;
}
Based on your comments, it looks like your HTML pages use relative URLs like this:
<img src="testImage.jpg">
<img src="~/images/testImage.jpg">
The best thing to do is to update your HTML pages to absolute URLS like this:
http://www.yoururl.com/images/testImage.jpg
If you can't modify your HTML pages, then you need HTML Agility Pack. Then you can return the HTML like this in your controller:
string fileLocation = ConfigurationManager.AppSettings["ServerFilePath"].ToString() + "CPL\\" + "CPLPolicy\\" + "IMS.htm";
string html = System.IO.File.ReadAllText(fileLocation);
StringWriter writer = new StringWriter();
string websiteUrl = "http://www.yoursite.com";
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
foreach (var img in doc.DocumentNode.Descendants("img"))
{
img.Attributes["src"].Value = new Uri(new Uri(websiteUrl), img.Attributes["src"].Value).AbsoluteUri;
}
doc.Save(writer);
string content = writer.ToString();
return File(content, "text/html");

Converting an rdlc into image in ASP.net MVC3(Razor)

In my asp.net mvc3(Razor) application i am using rdlc for Reporting. For printing purpose i just need to convert the rdlc into image. I just tried the following code
public ActionResult FilePrint()
{
LocalReport localReport = new LocalReport();
localReport.ReportPath = #"Reports/OP/Rdlc/ClinicInvoiceReceipt.rdlc";
iClinicInvoiceReceipt = new RmtOPInvoice.ClinicInvoiceReceipt();
DataTable dt = iClinicInvoiceReceipt.SelectReceiptDtlForPrint(2);
ReportDataSource reportDataSource = new ReportDataSource();
reportDataSource.Value = dt;
reportDataSource.Name = "DataSet1";
localReport.DataSources.Add(reportDataSource);
string reportType = "Image";
string mimeType;
string encoding;
string fileNameExtension;
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
//Render the report
renderedBytes = localReport.Render(
reportType,
null,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
return File(renderedBytes, "Image");
}
and in view
<img src="#Url.Action("FilePrint","ClinicInvoiceReceipt")" />
But it doesnot works. How can i achieve this? If anybody knows please share..
You are missing DeviceInfo settings. Create a DeviceInfo settings as follows
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>JPEG</OutputFormat>" +
" <PageWidth>8.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.4in</MarginTop>" +
" <MarginLeft>0.6in</MarginLeft>" +
" <MarginRight>0.6in</MarginRight>" +
" <MarginBottom>0.4in</MarginBottom>" +
"</DeviceInfo>";
and change
renderedBytes = localReport.Render(
reportType,
null,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
return File(renderedBytes, "Image");
to
renderedBytes = localReport.Render(
reportType,
deviceInfo ,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
return File(renderedBytes, "image/jpeg");
Have a look at Image Device Information Settings for other image types.

Exception Management Application Block with MVC

I've been scanning forums for an implementation of the Exception Management Application Block (EMAB) in an ASP.NET MVC (MVC3) application.
There's a lot of talk about ELMAH and NLog as well as handling via the global.asax (http://s151.codeinspot.com/q/694875) Vs an ErrorController (http://www.davidjuth.com/asp-net-mvc-error-handler.aspx) approach as well as leveraging the [HandleError] decoration
We are looking at standardising our Exception Management of our MVC apps with EMAB but I can't seem to find any specific examples that provide an all round solution.
Does anyone have any links or can explain exactly how you might utilise EMAB within the MVC framework
I decided on the approach below...
//**In Global.asax
protected void Application_Error(object sender, EventArgs e)
{
Exception originalError = Server.GetLastError();
Exception replacedError;
if (ExceptionPolicy.HandleException(originalError, "Global Policy", out replacedError))
{
Exception ex = replacedError ?? originalError;
if (ex.InnerException != null)
{
ex = ex.InnerException;
}
var httpException = ex as HttpException;
HttpApplication httpApplication = this.Context.ApplicationInstance;
string message = Utility.GetFullMessage(httpApplication, ex, "::");
string messageHtml = Utility.GetFullMessage(httpApplication, ex, "<br/>");
LogEntry logEntry = new LogEntry();
logEntry.EventId = 100;
logEntry.Priority = 2;
logEntry.Message = ex.Message + "::" + message;
Logger.Write(logEntry);
Response.Clear();
Server.ClearError();
var routeData = new RouteData();
routeData.Values["controller"] = "Error";
routeData.Values["action"] = Constants.ErrorGeneralKey; //"General"
routeData.Values["message"] = ex.Message;
routeData.Values["fullMessage"] = messageHtml;
Response.StatusCode = 500;
if (httpException != null)
{
Response.StatusCode = httpException.GetHttpCode();
switch (Response.StatusCode)
{
case 403:
routeData.Values["action"] = "Http403";
break;
case 404:
routeData.Values["action"] = "Http404";
break;
default:
routeData.Values["httpStatusCode"] = Response.StatusCode;
break;
}
}
IController errorController = new ErrorController();
var rc = new RequestContext(new HttpContextWrapper(Context), routeData);
errorController.Execute(rc);
}
}
//**In helper class
public static string GetFullMessage(HttpApplication httpApplication, Exception ex, string delimiter)
{
return "StackTrace: " + ex.StackTrace
+ delimiter + "User: " + ((httpApplication.User == null) ? "<null>" : httpApplication.User.Identity.Name)
+ delimiter + "Data: " + GetExceptionData(ex.Data)
+ delimiter + "Version: " + httpApplication.Request.Browser.Version
+ delimiter + "Browser: " + httpApplication.Request.Browser.Browser
+ delimiter + "Major Version: " + httpApplication.Request.Browser.MajorVersion.ToString()
+ delimiter + "Minor Version: " + httpApplication.Request.Browser.MinorVersion.ToString()
+ delimiter + "Javascript Version: " + httpApplication.Request.Browser.JScriptVersion.ToString()
+ delimiter + "Ecma Script Version: " + httpApplication.Request.Browser.EcmaScriptVersion.ToString()
+ delimiter + "Platform: " + httpApplication.Request.Browser.Platform
+ delimiter + "Source: " + ex.Source
+ delimiter + "Form: " + httpApplication.Request.Form.ToString()
+ delimiter + "QueryString: " + httpApplication.Request.QueryString.ToString()
+ delimiter + "TargetSite: " + ex.TargetSite;
}
//**In Error controller
public ActionResult General(string httpStatusCode, string message, string fullMessage)
{
errorViewModel.RootCause = Enums.RootCause.General;
errorViewModel.HttpStatusCode = httpStatusCode;
errorViewModel.Message = message;
errorViewModel.FullMessage = fullMessage;
return View("Error", errorViewModel);
}
public ActionResult Http404()
{
errorViewModel.RootCause = Enums.RootCause.NotFound;
return View("Error", errorViewModel);
}
public ActionResult Http403()
{
errorViewModel.RootCause = Enums.RootCause.Forbidden;
return View("Error", errorViewModel);
}

Resources