Generating PDFs from Image field on new server - pdf

So, I'm trying to a server and I'm moving a website from an older server to a new one. It's changing from 32-bit to 64-bit. The developer (who is no longer here) coded the webstie to upload PDF documents and save them in an Image field. Works great, but not on the new server.
The following code is the page that gets called to display the PDF. Ex: TestMethod.aspx?id=75
<%# Page language="c#" AutoEventWireup="true" %>
<%# Import Namespace="System.Data" %>
<%# Import Namespace="System.Data.SqlClient" %>
<%# Import Namespace="System.Drawing" %>
<%# Import Namespace="System.Drawing.Imaging" %>
<%# Import Namespace="System.IO" %>
<script runat="server">
void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "application/pdf";
Response.Buffer = true;
SqlCommand cmd = new SqlCommand("SELECT method FROM Tests WHERE id = #id");
cmd.Parameters.Add("#id", SqlDbType.Int).Value = Int32.Parse(Request["id"]);
Util.GetBLOB(cmd, Response.OutputStream, 32768);
Response.Flush();
Response.End();
}
</script>
The GetBLOB function is as follows:
public static void GetBLOB(SqlCommand cmd, Stream output, int bufferLength)
{
byte[] outbytes = new byte[bufferLength];
SqlConnection connex = new SqlConnection(ConfigurationSettings.AppSettings["DSN"]);
cmd.Connection = connex;
connex.Open();
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
rdr.Read();
int start = 0;
long retval = rdr.GetBytes(0, 0, null, 0, 0);
retval = rdr.GetBytes(0, start, outbytes, 0, outbytes.Length);
while (retval > 0)
{
output.Write(outbytes, 0, (int)retval);
start += outbytes.Length;
retval = rdr.GetBytes(0, start, outbytes, 0, outbytes.Length);
}
retval = rdr.GetBytes(0, start, null, 0, 0);
outbytes = new byte[retval];
rdr.GetBytes(0, start, outbytes, 0, outbytes.Length);
output.Write(outbytes, 0, (int)retval);
connex.Close();
}
I am very new to ASP.NET and cannot see a simple solution. Does this have anything to do with the server being 64 bit? Thanks for any help.
I get the following error when run:
Specified argument was out of the range of valid values.
Parameter name: offset
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: offset
Source Error:
Line 14: SqlCommand cmd = new SqlCommand("SELECT document FROM TechLibrary WHERE id = #id");
Line 15: cmd.Parameters.Add("#id", SqlDbType.Int).Value = Int32.Parse(Request["id"]);
Line 16: Util.GetBLOB(cmd, Response.OutputStream, 32768);
Line 17:
Line 18: Response.Flush();
Source File: d:\....\TechLibraryDoc.aspx Line: 16
Stack Trace:
[ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: offset]
System.Web.HttpResponseStream.Write(Byte[] buffer, Int32 offset, Int32 count) +169
trace.Util.GetBLOB(SqlCommand cmd, Stream output, Int32 bufferLength) in c:\Inetpub\wwwroot\trace\src\Util.cs:146
ASP.techlibrarydoc_aspx.Page_Load(Object sender, EventArgs e) in d:\.....\TechLibraryDoc.aspx:16
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +43
System.Web.UI.Control.OnLoad(EventArgs e) +91
System.Web.UI.Control.LoadRecursive() +74
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2603
Version

My error was very similar to yours. it turned out that the app we were using was a 32 bit dll used on the 64 bit server.
The app pool in IIS was set to not run 32 bit dlls.
in my opinion, its probably due to the 32-64 bit switch.

Related

How to load .NET 6 project in a .NET 6 console application

I am attempting to load a .NET 6 project (SDK Style) in a .NET 6 console application. My entire project is fairly simple - it actually attempts to load its own .csproj file when it runs from the default output folder:
using Microsoft.Build.Evaluation;
namespace ProjLoading
{
internal class Program
{
static void Main(string[] args)
{
var projectLocation = "../../../ProjLoading.csproj";
var project = new Project(projectLocation, null, null, new ProjectCollection());
}
}
}
I am using the following nuget packages:
Microsoft.Build (17.2.0)
Microsoft.Build.Utilities.Core (17.2.0)
When I run the code, I get the following exception:
Microsoft.Build.Exceptions.InvalidProjectFileException: 'The SDK 'Microsoft.NET.Sdk' specified could not be found. C:\Users\vchel\source\repos\ProjLoading\ProjLoading\ProjLoading.csproj'
This exception was originally thrown at this call stack:
Microsoft.Build.Shared.ProjectErrorUtilities.ThrowInvalidProject(string, Microsoft.Build.Shared.IElementLocation, string, object[])
Microsoft.Build.Evaluation.Evaluator<P, I, M, D>.ExpandAndLoadImportsFromUnescapedImportExpressionConditioned(string, Microsoft.Build.Construction.ProjectImportElement, out System.Collections.Generic.List<Microsoft.Build.Construction.ProjectRootElement>, out Microsoft.Build.BackEnd.SdkResolution.SdkResult, bool)
Microsoft.Build.Evaluation.Evaluator<P, I, M, D>.ExpandAndLoadImports(string, Microsoft.Build.Construction.ProjectImportElement, out Microsoft.Build.BackEnd.SdkResolution.SdkResult)
Microsoft.Build.Evaluation.Evaluator<P, I, M, D>.EvaluateImportElement(string, Microsoft.Build.Construction.ProjectImportElement)
Microsoft.Build.Evaluation.Evaluator<P, I, M, D>.PerformDepthFirstPass(Microsoft.Build.Construction.ProjectRootElement)
Microsoft.Build.Evaluation.Evaluator<P, I, M, D>.Evaluate()
Microsoft.Build.Evaluation.Project.ProjectImpl.Reevaluate(Microsoft.Build.BackEnd.Logging.ILoggingService, Microsoft.Build.Evaluation.ProjectLoadSettings, Microsoft.Build.Evaluation.Context.EvaluationContext)
Microsoft.Build.Evaluation.Project.ProjectImpl.ReevaluateIfNecessary(Microsoft.Build.BackEnd.Logging.ILoggingService, Microsoft.Build.Evaluation.ProjectLoadSettings, Microsoft.Build.Evaluation.Context.EvaluationContext)
Microsoft.Build.Evaluation.Project.ProjectImpl.Initialize(System.Collections.Generic.IDictionary<string, string>, string, string, Microsoft.Build.Evaluation.ProjectLoadSettings, Microsoft.Build.Evaluation.Context.EvaluationContext)
Microsoft.Build.Evaluation.Project.Project(string, System.Collections.Generic.IDictionary<string, string>, string, string, Microsoft.Build.Evaluation.ProjectCollection, Microsoft.Build.Evaluation.ProjectLoadSettings, Microsoft.Build.Evaluation.Context.EvaluationContext, Microsoft.Build.FileSystem.IDirectoryCacheFactory)
...
[Call Stack Truncated]
I am building/running this console application from Visual Studio 2022 (17.2.2).
How can I solve this problem?
I don't understand why, but I ran across this solution and it has solved the problem:
https://blog.rsuter.com/missing-sdk-when-using-the-microsoft-build-package-in-net-core/
In case the link dies in the future, my full project now sets the environment variable MSBUILD_EXE_PATH to the latest version of msbuild as shown in the following code:
using Microsoft.Build.Evaluation;
using System.Diagnostics;
using System.Text.RegularExpressions;
namespace ProjLoading
{
internal class Program
{
static void Main(string[] args)
{
var startInfo = new ProcessStartInfo("dotnet", "--list-sdks")
{
RedirectStandardOutput = true
};
var process = Process.Start(startInfo);
process.WaitForExit(1000);
var output = process.StandardOutput.ReadToEnd();
var sdkPaths = Regex.Matches(output, "([0-9]+.[0-9]+.[0-9]+) \\[(.*)\\]")
.OfType<Match>()
.Select(m => System.IO.Path.Combine(m.Groups[2].Value, m.Groups[1].Value, "MSBuild.dll"));
var sdkPath = sdkPaths.Last();
Environment.SetEnvironmentVariable("MSBUILD_EXE_PATH", sdkPath);
var projectLocation = "../../../ProjLoading.csproj";
var project = new Project(projectLocation, null, null, new ProjectCollection());
}
}
}

VB.NET Exception when running System.Security.Cryptography.ECDsa.Create (ECCurve curve)

I am getting an exception when I use the System.Security.Cryptography.ECCurve.NamedCurves.brainpoolP256r1 property of Framework 4.7.
The exception I am getting is (stackoverflow):
The specified 'brainpoolP256r1' curve or its parameters are not valid
for this platform. Stackoverflow:
in System.Security.Cryptography.CngKey.Create (ECCurve curve, Func`2
algorithihmResolver) in
System.Security.Cryptography.ECDsaCng.GenerateKey (ECCurve curve) in System.Security.Cryptography.ECDsa.Create (ECCurve curve)
In local machines that I have in the office it works for me in all, but in the different servers that I have tried, it has not worked in any.
Dim pubKeyX As Byte() = _Key.Skip(1).Take(32).ToArray()
Dim pubKeyY As Byte() = _Key.Skip(33).ToArray()
Dim params As New ECParameters() With
{
.Q = New ECPoint With
{
.X = pubKeyX,
.Y = pubKeyY
},
.Curve = _ECCurve
}
Dim oRes As ECDsa = ECDsa.Create(_ECCurve)
This last line is the one that causes the exception

Not able to save after deleting rows using EPPlus

I have a very simple code to open a copy template excel file put some data into it and delete the remaining empty rows. This works with most of the template files but with few of them i get exception when i try to save the file after deleting not required rows.
In the sample code i have omitted the data addition code and just kept the delete row functionality. When i run this code i get error if i try to delete rows after 1025.
static void Main(string[] args)
{
try
{
FileInfo fis = new FileInfo(#"D:\ExcelTest\TestFile.xlsx");
FileInfo fi = new FileInfo(Path.Combine(fis.DirectoryName, Guid.NewGuid() + fis.Extension));
fis.CopyTo(fi.FullName);
using (ExcelPackage excelPackage = new ExcelPackage(fi))
{
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets["C3R"];
int rowstodelete = (171 * 6) - 23;
worksheet.DeleteRow(24, rowstodelete, true);
excelPackage.Save();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
System.InvalidOperationException: Error saving file D:\ExcelTest\fabf5a3f-714f-4422-a760-73190f34b951.xlsx ---> System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.\r\n at System.Collections.Generic.Dictionary`2.get_Item(TKey key)\r\n at OfficeOpenXml.ExcelWorksheet.UpdateRowCellData(StreamWriter sw)\r\n at OfficeOpenXml.ExcelWorksheet.SaveXml(Stream stream)\r\n at OfficeOpenXml.ExcelWorksheet.SaveHandler(ZipOutputStream stream, CompressionLevel compressionLevel, String fileName)\r\n at OfficeOpenXml.Packaging.ZipPackagePart.WriteZip(ZipOutputStream os)\r\n at OfficeOpenXml.Packaging.ZipPackage.Save(Stream stream)\r\n at OfficeOpenXml.ExcelPackage.Save()\r\n --- End of inner exception stack trace ---\r\n at OfficeOpenXml.ExcelPackage.Save()\r\n at ConsoleApplication1.Program.Main(String[] args) in C:\Users\sm511\Documents\Visual Studio 2015\Projects\ConsoleApplication1\Program.cs:line 27
The excel file causing problem

Converting XDP to PDF using Live Cycle replaces question marks(?) with space at multiple places. How can that be fixed?

I have been trying to convert XDP to PDF using Adobe Live Cycle. Most of my forms turn up good. But while converting some of them, I fine ??? replaced in place of blank spaces at certain places. Any suggestions to how can I rectify that?
Below is the code snippet that I am using:
public byte[] generatePDF(TextDocument xdpDocument) {
try {
Assert.notNull(xdpDocument, "XDP Document must be passed.");
Assert.hasLength(xdpDocument.getContent(), "XDPDocument content cannot be null");
// Create a ServiceClientFactory object
ServiceClientFactory myFactory = ServiceClientFactory.createInstance(createConnectionProperties());
// Create an OutputClient object
FormsServiceClient formsClient = new FormsServiceClient(myFactory);
formsClient.resetCache();
String text = xdpDocument.getContent();
String charSet = xdpDocument.getCharsetName();
if (charSet == null || charSet.trim().length() == 0) {
charSet = StandardCharsets.UTF_8.name();
}
byte[] bytes = text.getBytes();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
Document inTemplate = new Document(byteArrayInputStream);
// Set PDF run-time options
// Set rendering run-time options
RenderOptionsSpec renderOptionsSpec = new RenderOptionsSpec();
renderOptionsSpec.setLinearizedPDF(true);
renderOptionsSpec.setAcrobatVersion(AcrobatVersion.Acrobat_9);
PDFFormRenderSpec pdfFormRenderSpec = new PDFFormRenderSpec();
pdfFormRenderSpec.setGenerateServerAppearance(true);
pdfFormRenderSpec.setCharset("UTF8");
FormsResult formOut = formsClient.renderPDFForm2(inTemplate, null, pdfFormRenderSpec, null, null);
Document xfaPdfOutput = formOut.getOutputContent();
//If the input file is already static PDF, then below method will throw an exception - handle it
OutputClient outClient = new OutputClient(myFactory);
outClient.resetCache();
Document staticPdfOutput = outClient.transformPDF(xfaPdfOutput, TransformationFormat.PDF, null, null, null);
byte[] data = StreamIO.toBytes(staticPdfOutput.getInputStream());
return data;
} catch(IllegalArgumentException ex) {
logger.error("Input validation failed for generatePDF request " + ex.getMessage());
throw new EformsException(ErrorExceptionCode.INPUT_REQUIRED + " - " + ex.getMessage(), ErrorExceptionCode.INPUT_REQUIRED);
} catch (Exception e) {
logger.error("Exception occurred in Adobe Services while generating PDF from xdpDocument..", e);
throw new EformsException(ErrorExceptionCode.PDF_XDP_CONVERSION_EXCEPTION, e);
}
}
I suggest trying 2 things:
Check the font. Switch to something very common like Arial / Times New Roman and see if the characters are still lost
Check the character encoding. It might not be a simple question mark character you are using and if so the character encoding will be important. The easiest way is to make sure your question mark is ascii char 63 (decimal).
I hope that helps.

Why NoPointerExcepeion when decompression by apache compress?

click and see The NoPointerExcepeion
I generate tar.gz files and send 2 others 4 decompress, but their progrem has error above(their progrem was not created by me), only one file has that error.
But when using command 'tar -xzvf ***' on my computer and their computer, no problem occured...
So I want 2 know what was wrong in my progrem below:
public static void archive(ArrayList<File> files, File destFile) throws Exception {
TarArchiveOutputStream taos = new TarArchiveOutputStream(new FileOutputStream(destFile));
taos.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
for (File file : files) {
//LOG.info("file Name: "+file.getName());
archiveFile(file, taos, "");
}
}
private static void archiveFile(File file, TarArchiveOutputStream taos, String dir) throws Exception {
TarArchiveEntry entry = new TarArchiveEntry(dir + file.getName());
entry.setSize(file.length());
taos.putArchiveEntry(entry);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
int count;
byte data[] = new byte[BUFFER];
while ((count = bis.read(data, 0, BUFFER)) != -1) {
taos.write(data, 0, count);
}
bis.close();
taos.closeArchiveEntry();
}
The stack trace looks like a bug in Apache Commons Compress https://issues.apache.org/jira/browse/COMPRESS-223 that has been fixed with version 1.7 (released almost three years ago).