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.
Related
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.
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");
}
}
public String generateReport() {
try
{
final FacesContext facesContext = FacesContext.getCurrentInstance();
final HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
response.reset();
response.setHeader("Content-Disposition", "attachment; filename=\"" + "myReport.zip\";");
final BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
final ZipOutputStream zos = new ZipOutputStream(bos);
for (final PeriodScale periodScale : Scale.getPeriodScales(this.startDate, this.endDate))
{
final JasperPrint jasperPrint = JasperFillManager.fillReport(
this.reportsPath() + File.separator + "periodicScale.jasper",
this.parameters(this.reportsPath(), periodScale.getScale(),
periodScale.getStartDate(), periodScale.getEndDate()),
new JREmptyDataSource());
final byte[] bytes = JasperExportManager.exportReportToPdf(jasperPrint);
response.setContentLength(bytes.length);
final ZipEntry ze = new ZipEntry("periodicScale"+ periodScale.getStartDate() + ".pdf"); // periodicScale13032015.pdf for example
zos.putNextEntry(ze);
zos.write(bytes, 0, bytes.length);
zos.closeEntry();
}
zos.close();
facesContext.responseComplete();
}
catch (final Exception e)
{
e.printStackTrace();
}
return "";
}
This is my action method in the managedBean which is called by the user to print a JasperReport, but when I try to put more than one report inside the zip file it's not working.
getPeriodScales are returning two objects and JasperFillManager.fillReport is running correctly as the reports print when I just generate data for one report, when I try to stream two reports though and open in WinRar only one appears and I get an "unexpedted end of archive", in 7zip both appear but the second is corrupted.
What am I doing wrong or is there a way to stream multiple reports without zipping it?
I figured out what was, I was setting the contentLenght of the response with bytes.length size, but it should be bytes.length * Scale.getPeriodScales(this.startDate, this.endDate).size()
public JasperPrint generatePdf(long consumerNo) {
Consumer consumerByCustomerNo = consumerService.getConsumerByCustomerNo(consumerNo);
consumerList.add(consumerByCustomerNo);
BillHeaderIPOP billHeaderByConsumerNo = billHeaderService.getBillHeaderByConsumerNo(consumerNo);
Long billNo = billHeaderByConsumerNo.getBillNo();
List<BillLineItem> billLineItemByBilNo = billLineItemService.getBillLineItemByBilNo(billNo);
System.out.println(billLineItemByBilNo);
List<BillReadingLine> billReadingLineByBillNo = billReadingLineService.getBillReadingLineByBillNo(billNo);
File jrxmlFile = ResourceUtils.getFile("classpath:demo.jrxml");
JasperReport jasperReport = JasperCompileManager.compileReport(jrxmlFile.getAbsolutePath());
pdfContainer.setName(consumerByCustomerNo.getName());
pdfContainer.setTelephone(consumerByCustomerNo.getTelephone());
pdfContainer.setFromDate(billLineItemByBilNo.get(0).getStartDate());
pdfContainer.setToDate(billLineItemByBilNo.get(0).getEndDate());
pdfContainer.setSupplyAddress(consumerByCustomerNo.getSupplyAddress());
pdfContainer.setMeterNo(billReadingLineByBillNo.get(0).getMeterNo());
pdfContainer.setBillType(billHeaderByConsumerNo.getBillType());
pdfContainer.setReadingType(billReadingLineByBillNo.get(0).getReadingType());
pdfContainer.setLastBilledReadingInKWH(billReadingLineByBillNo.stream().filter(billReadingLine -> billReadingLine.getRegister().contains("KWH")).collect(Collectors.toList()).get(0).getLastBilledReading());
pdfContainer.setLastBilledReadingInKW(billReadingLineByBillNo.stream().filter(billReadingLine -> billReadingLine.getRegister().contains("KW")).collect(Collectors.toList()).get(0).getLastBilledReading());
pdfContainer.setReadingType(billReadingLineByBillNo.get(0).getReadingType());
pdfContainer.setRateCategory(billLineItemByBilNo.get(0).getRateCategory());
List<PdfContainer> pdfContainerList = new ArrayList<>();
pdfContainerList.add(pdfContainer);
Map<String, Object> parameters = new HashMap<>();
parameters.put("billLineItemByBilNo", billLineItemByBilNo);
parameters.put("billReadingLineByBillNo", billReadingLineByBillNo);
parameters.put("consumerList", consumerList);
parameters.put("pdfContainerList", pdfContainerList);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, new JREmptyDataSource());
return jasperPrint;
}
//above code is accroding to my requirement , you just focus on the jasperPrint object which am returning , then jasperPrint object is being used for pdf generation , storing those pdf into a zip file .
#GetMapping("/batchpdf/{rangeFrom}/{rangeTo}")
public String batchPdfBill(#PathVariable("rangeFrom") long rangeFrom, #PathVariable("rangeTo") long rangeTo) throws JRException, IOException {
consumerNosInRange = consumerService.consumerNoByRange(rangeFrom, rangeTo);
String zipFilePath = "C:\\Users\\Barada\\Downloads";
FileOutputStream fos = new FileOutputStream(zipFilePath +"\\"+ rangeFrom +"-To-"+ rangeTo +"--"+ Math.random() + ".zip");
BufferedOutputStream bos = new BufferedOutputStream(fos);
ZipOutputStream outputStream = new ZipOutputStream(bos);
try {
for (long consumerNo : consumerNosInRange) {
JasperPrint jasperPrint = generatePdf(consumerNo);
byte[] bytes = JasperExportManager.exportReportToPdf(jasperPrint);
outputStream.putNextEntry(new ZipEntry(consumerNo + ".pdf"));
outputStream.write(bytes, 0, bytes.length);
outputStream.closeEntry();
}
} finally {
outputStream.close();
}
return "All Bills PDF Generated.. Extract ZIP file get all Bills";
}
}
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);
I am new in Blackberry development and I have to upload my Image from device gallery to server. I found lot many links related to this point. But I can not found the exact result of this problem. I used this Example . Using this example I got the value into Byte[] but I am not able to fulfill my requirements using this code. In that I am not able understand that which URL we have to passed in the code and which are the parameters.
I used one more format, I post my code here, using this I got the Response Code:200. But I am not able to solve this
HttpConnection oCon = (HttpConnection)Connector.open("http://74.208.77.106/jm/testing/iDaddyapi.php;deviceside=true;interface=wifi");
oCon.setRequestMethod(HttpConnection.POST);
oCon.setRequestProperty("Content-Length", "" + imageByte.length);
URLEncodedPostData oPostData = new URLEncodedPostData(URLEncodedPostData.DEFAULT_CHARSET, false);
oPostData.append("api", "postidaddyimage");
oPostData.append("imagetype", "F");
oPostData.append("image", strImage);
OutputStream strmOut = oCon.openOutputStream();
strmOut.write(oPostData.getBytes());
strmOut.flush();
strmOut.close();
int rc = oCon.getResponseCode();
System.out.println("Response code.............."+rc);
if (rc != HttpConnection.HTTP_OK)
throw new IOException("Error response code: " + rc);
Can anyone help me? I am stuck on this.
Thanks,
Mansi
HttpConnection conn = (HttpConnection) Connector.open(Url, Connector.READ_WRITE);
conn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH,
String.valueOf(imagedata.length));
conn.setRequestProperty("x-rim-transcode-content", "none");
ByteArrayOutputStream out = new ByteArrayOutputStream();
OutputStream finalOut = conn.openOutputStream();
String newLine = "\r\n";
out.write(newLine.getBytes());
out.write("--".getBytes());
out.write(boundary.getBytes());
out.write(newLine.getBytes());
String contDisp = "Content-Disposition:form-data;
name=\"file\";filename=\"Image.jpg\"";
String contEnc = "Content-Transfer-Encoding: binary";
String type = "Content-Type:image/jpeg";
out.write(contDisp.getBytes());
out.write(newLine.getBytes());
out.write(type.getBytes());
out.write(newLine.getBytes());
out.write(contEnc.getBytes());
out.write(newLine.getBytes());
out.write(newLine.getBytes());
out.write(imagedata);
out.write(newLine.getBytes());
out.write("--".getBytes());
out.write(boundary.getBytes());
out.write("--".getBytes());
out.write(newLine.getBytes());
finalOut.write(out.toByteArray());
out.flush();
out.close();
finalOut.flush();
finalOut.close();
public class ImageUploader extends Thread {
String filename;
Bitmap temp;
public ImageUploader(String filename)
{
this.filename=filename;
}
public void run() {
final String boundary = "Some_Unique_Text_Also_Alphanumeric";
try
{
//FileInputStream fis=new FileInputStream(File.FILESYSTEM_PATRIOT,filename);
FileConnection fis=(FileConnection)Connector.open(filename);
InputStream inputStream = fis.openInputStream();
ByteArrayOutputStream bos=new ByteArrayOutputStream();
int buffersize=1024;
byte[] buffer=new byte[buffersize];
int length=0;
while((length=inputStream.read(buffer))!=-1)
{
bos.write(buffer,0,length);
}
byte[] imagedata=bos.toByteArray();
HttpConnection conn = (HttpConnection) Connector.open(URL, Connector.READ_WRITE);
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_TYPE,
HttpProtocolConstants.CONTENT_TYPE_MULTIPART_FORM_DATA
+ ";boundary=" + boundary);
conn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH,
String.valueOf(imagedata.length));
conn.setRequestProperty("x-rim-transcode-content", "none");
ByteArrayOutputStream out = new ByteArrayOutputStream();
OutputStream finalOut = conn.openOutputStream();
String newLine = "\r\n";
out.write(newLine.getBytes());
out.write("--".getBytes());
out.write(boundary.getBytes());
out.write(newLine.getBytes());
String contDisp = "Content-Disposition:form-data; name=\"file\";filename=\"Image.jpg\"";
String contEnc = "Content-Transfer-Encoding: binary";
String type = "Content-Type:image/jpeg";
out.write(contDisp.getBytes());
out.write(newLine.getBytes());
out.write(type.getBytes());
out.write(newLine.getBytes());
out.write(contEnc.getBytes());
out.write(newLine.getBytes());
out.write(newLine.getBytes());
out.write(imagedata);
out.write(newLine.getBytes());
out.write("--".getBytes());
out.write(boundary.getBytes());
out.write("--".getBytes());
out.write(newLine.getBytes());
finalOut.write(out.toByteArray());
out.flush();
out.close();
finalOut.flush();
finalOut.close();
InputStream instream=conn.openInputStream();
int ch=0;
StringBuffer buffesr=new StringBuffer();
while((ch=instream.read())!=-1)
{
buffesr.append((char)ch);
}
JSONObject myprofileObject = new JSONObject(buffesr.toString());
String result = myprofileObject.optString("result");
String url = myprofileObject.optString("url");
String message=myprofileObject.optString("msg");
MyProfile._model.setProfilePic(url);
}
catch (Exception e) {
// TODO: handle exception
}
};
thread.start();
}
}