Render SSRS 2008 Report in web page without Report Viewer - c#

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.

Related

What is the best way to create multiple xml files and export it as one zip file

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;
}
}

How can i download a text file from the server folder not inside project solution

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;
}
}

Cant Post a Upload Image with IHttpActionResult

i have try with postman in my local server to route the API
this is my code
[HttpPost]
[Route("photo")]
public IHttpActionResult Upload()
{
// LOCAL VARIABLE
int ErrCode = 1;
dynamic ExpObj = new ExpandoObject();
string FilePath = HttpContext.Current.Server.MapPath("/Img");
// GET SID & DECRYPTING OBJEK TO JSON OBJ
var HttpRequest = HttpContext.Current.Request;
string SID = GetSID(this.Request.Headers);
dynamic objek = GetobjekuMultipart(SID, HttpRequest.Form["objek"]);
// EXTRACT OBJEK
string UserID = objek.userID;
if (HttpRequest.Files.Count > 0)
{
// GET UPLOADED IMAGE
var PostedFile = HttpRequest.Files["image"];
// SET FILE NAME ( USERID + Right(FileName,10) )
string FileName = GetFileName(UserID, PostedFile.FileName, 10);
// SAVE IMAGE
string ImagePath = Path.Combine(FilePath, FileName);
PostedFile.SaveAs(ImagePath);
ExpObj.imageURL = ServerUrl + ServerPath + FileName;
}
else
{
ErrCode = -900;
}
// RETURN IF GOT ERROR
if (ErrCode < 0)
{
return StatusCode((HttpStatusCode)(ErrCode * (-1)));
}
// SERIALIZING & ENCRYPTING
string SerializedObj = JsonConvert.SerializeObject(ExpObj, JsonSetting);
string EncryptedReturn = Encrypt(SerializedObj, SID);
// RETURN
return Ok(EncryptedReturn);
}
and this is my public method (General Method)
public string Decrypt(string cipherText, string sid)
{
RNCryptor.Decryptor D = new Decryptor();
string DecryptedString = "";
if (Prod == true)
{
try
{
DecryptedString = D.Decrypt(cipherText, sid + SigningKey);
}
catch (Exception ex)
{
int ErrCode = -902; // Error in Decrypt
throw new HttpResponseException((HttpStatusCode)(ErrCode * (-1)));
}
}
else
{
DecryptedString = cipherText;
}
return DecryptedString.Trim();
}
public dynamic GetObjekMultipart(string sid, string Objek)
{
string StrObjek = Decrypt(Objek, sid);
return JsonConvert.DeserializeObject<dynamic>(StrObjek);
}
public string GetFileName(string UserID, string fileName, int length)
{
string FileName;
string FileFormat;
// GET FILE FORMAT
string[] Words = fileName.Split('.');
FileFormat = "." + Words[Words.Length - 1];
// GET FILE NAME WITHOUT THE FILE FORMAT
FileName = fileName.Substring(0, fileName.Length - FileFormat.Length);
// SET THE FILE NAME
FileName = UserID + "-" + GetRight(FileName, length) + FileFormat;
return FileName;
}
and POSTMAN Result is "Object reference not set to an instance of an object"
the result said that the httprequest.form is NULL
please help :(

Local report rdlc to pdf very slow

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!

I'm try to implement UPSP Label Generating

I am tryin to implement UPSP label generating but i am getting this error.
**API Authorization failure. DelivConfirmCertifyV3.0Request is not a valid API name for this protocol.**
if i test on browser, it's working fine
http://production.shippingapis.com/ShippingAPI.dll?API=Verify&XML=%3CAddressValidateRequest%20USERID=%22Testuserid%22%3E%3CAddress%20ID=%221%22%3E%3CAddress1%3E%3C/Address1%3E%3CAddress2%3E10051+Orr+%26amp%3b+Day+Rd%3C/Address2%3E%3CCity%3Esanta+fe+springs%3C/City%3E%3CState%3Eca%3C/State%3E%3CZip5%3E90670%3C/Zip5%3E%3CZip4%3E%3C/Zip4%3E%3C/Address%3E%3C/AddressValidateRequest%3E
Anyone know about this problem...
Code Is below:
public Package GetDeliveryConfirmationLabel(Package package)
{
string labeldate = package.ShipDate.ToShortDateString();
if (package.ShipDate.ToShortDateString() == DateTime.Now.ToShortDateString())
labeldate = "";
string url = "?API=DelivConfirmCertifyV3.0Request&XML=<DelivConfirmCertifyV3.0Request.0Request USERID=\"{0}\"><Option>{1}</Option><ImageParameters></ImageParameters><FromName>{2}</FromName><FromFirm>{3}</FromFirm><FromAddress1>{4}</FromAddress1><FromAddress2>{5}</FromAddress2><FromCity>{6}</FromCity><FromState>{7}</FromState><FromZip5>{8}</FromZip5><FromZip4>{9}</FromZip4><ToName>{10}</ToName><ToFirm>{11}</ToFirm><ToAddress1>{12}</ToAddress1><ToAddress2>{13}</ToAddress2><ToCity>{14}</ToCity><ToState>{15}</ToState><ToZip5>{16}</ToZip5><ToZip4>{17}</ToZip4><WeightInOunces>{18}</WeightInOunces><ServiceType>{19}</ServiceType><POZipCode>{20}</POZipCode><ImageType>{21}</ImageType><LabelDate>{22}</LabelDate><CustomerRefNo>{23}</CustomerRefNo><AddressServiceRequested>{24}</AddressServiceRequested><SenderName>{25}</SenderName><SenderEMail>{26}</SenderEMail><RecipientName>{27}</RecipientName><RecipientEMail>{28}</RecipientEMail></DelivConfirmCertifyV3.0Request.0Request>";
url = GetURL() + url;
//url = String.Format(url,this._userid, (int)package.LabelType, package.FromAddress.Contact, package.FromAddress.FirmName, package.FromAddress.Address1, package.FromAddress.Address2, package.FromAddress.City, package.FromAddress.State, package.FromAddress.Zip, package.FromAddress.ZipPlus4, package.ToAddress.Contact, package.ToAddress.FirmName, package.ToAddress.Address1, package.ToAddress.Address2, package.ToAddress.City, package.ToAddress.State, package.ToAddress.Zip, package.ToAddress.ZipPlus4, package.WeightInOunces.ToString(), package.ServiceType.ToString().Replace("_", " "), package.OriginZipcode, package.LabelImageType.ToString(), labeldate, package.ReferenceNumber, package.AddressServiceRequested.ToString(), package.FromAddress.Contact, package.FromAddress.ContactEmail, package.ToAddress.Contact, package.ToAddress.ContactEmail);
url = String.Format(url, this._userid, (int)package.LabelType, package.FromAddress.Contact, package.FromAddress.FirmName, package.FromAddress.Address1, package.FromAddress.Address2, package.FromAddress.City, package.FromAddress.State, package.FromAddress.Zip, package.FromAddress.ZipPlus4, package.ToAddress.Contact, package.ToAddress.FirmName, package.ToAddress.Address1, package.ToAddress.Address2, package.ToAddress.City, package.ToAddress.State, package.ToAddress.Zip, package.ToAddress.ZipPlus4, package.WeightInOunces.ToString(), package.ServiceType.ToString().Replace("_", " "), package.OriginZipcode, package.LabelImageType.ToString(), labeldate, package.ReferenceNumber, package.AddressServiceRequested.ToString(), "", "", "", "");
string xml = web.DownloadString(url);
if (xml.Contains("<Error>"))
{
int idx1 = xml.IndexOf("<Description>") + 13;
int idx2 = xml.IndexOf("</Description>");
int l = xml.Length;
string errDesc = xml.Substring(idx1, idx2 - idx1);
throw new USPSManagerException(errDesc);
}
int i1 = xml.IndexOf("<DeliveryConfirmationLabel>") + 27;
int i2 = xml.IndexOf("</DeliveryConfirmationLabel>");
package.ShippingLabel = StringToUTF8ByteArray(xml.Substring(i1, i2 - i1));
return package;
}
I get the error on
int i1 = xml.IndexOf("<DeliveryConfirmationLabel>") + 27;
The solution to your problem is the same on this stackoverflow question- How to remove 'SAMPLE DO NOT MAIL' from USPS shipping API image
And you can find the steps to get this done from my answer on that question or by directly following this link- https://stackoverflow.com/a/27936025/3748701
USPS returns the Label in Base64 string you'd be required to convert that into an image. In my application i was required to provide the image as downloadable file, so I have returned the file result from the controller-action. Below is the action which gets the Base64 string label from DB, converts it into image and provides as downloadable file-
public ActionResult GetReturnShippingLabel(int orderId, bool showFull)
{
string shippingLabel = new OrderRepository().GetOrderReturnShippingLabel(orderId);
if (!string.IsNullOrEmpty(shippingLabel))
{
byte[] bytes = Convert.FromBase64String(shippingLabel);
Image image = null;
MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length);
ms.Write(bytes, 0, bytes.Length);
image = Image.FromStream(ms, true);
image.RotateFlip(RotateFlipType.Rotate90FlipNone);
if (!showFull)
image = image.GetThumbnailImage(326, 570, null, IntPtr.Zero);
ImageConverter converter = new ImageConverter();
byte[] imgArray = (byte[])converter.ConvertTo(image, typeof(byte[]));
return File(imgArray.ToArray(), "image/gif");
}
else
{
return null;
}
}

Categories