Exception converting Office files to PDF using ABCpdf.NET onWindows Server 2008 - windows-server-2008

Has anyone delt with this exception from ABCpdf? We're running on Server 2008 and only have issues converting Office files (Word and Excel). This all worked well on Server 2003. Because we're only having issues with Office files I wonder if it's related to the XPS support on Server 2008? The code that calls into this function is running as a Windows Service.
Private Overloads Function ConvertMicrosoftOfficeDocToPdf(ByVal inputFile As Byte(), ByVal fileExt As String) As Byte()
Dim abcDoc As WebSupergoo.ABCpdf7.Doc = Nothing
Try
abcDoc = New WebSupergoo.ABCpdf7.Doc()
Dim xro As New WebSupergoo.ABCpdf7.XReadOptions()
xro.FileExtension = fileExt
Try
abcDoc.Read(inputFile, xro)
Catch ex As Exception
System.Diagnostics.Trace.Write(ex.ToString())
Throw ex
End Try
Dim fileBytes As Byte() = abcDoc.GetData()
Return fileBytes
Finally
If Not abcDoc Is Nothing Then
abcDoc.Clear()
abcDoc.Dispose()
End If
End Try
End Function
WebSupergoo.ABCpdf7.Internal.PDFException:
Attempted to read or write protected
memory. This is often an indication
that other memory is corrupt. --->
System.AccessViolationException:
Attempted to read or write protected
memory. This is often an indication
that other memory is corrupt.
at WebSupergoo.ABCpdf7.Internal.NDoc._InvokeMethod(IntPtr
inDoc, Int32 inMethod, Int32 inIndex,
Int32 inFlags, String inParams,
String& outErr)
at WebSupergoo.ABCpdf7.Internal.NDoc.InvokeMethod(IntPtr
inDoc, Int32 inMethod, Int32 inIndex,
Int32 inFlags, String inParams,
String& outErr)
at WebSupergoo.ABCpdf7.Doc.PrintToXps(String
inputFile, String outputFile, Int32
timeout, String printerName)
at WebSupergoo.ABCpdf7.Operations.XpsImportOperation.ImportAny(Doc
doc, String path, Int32 timeout)
at WebSupergoo.ABCpdf7.XReadOptions.ImportXpsAny(Doc
doc, String path, Boolean clear)
at WebSupergoo.ABCpdf7.XReadOptions.Read(Doc
doc, Byte[] data, ReadModuleType
module)
at WebSupergoo.ABCpdf7.XReadOptions.Read(Doc
doc, Byte[] data)

Added a folder called "Desktop" here:
C:\Windows\SysWOW64\config\systemprofile\
http://social.msdn.microsoft.com/Forums/en/innovateonoffice/thread/b81a3c4e-62db-488b-af06-44421818ef91

Actual problem is that the folder where you are trying write the file, give the write permission to IIS_IUSR. Then it should work.

Related

Lucene Update not working Index Writer

I have updated a large application from .Net 4.0 to .Net 4.52 and it has broken some indexing and search functions that I have that use Lucene. I updated to the latest NuGet Packages for Lucene and I keep getting the following errors.
Type 'Lucene.Net.Index.IndexWriter' is not defined.
Type 'Lucene.Net.Documents.Document' is not defined.
Type 'IndexWriter' is not defined.
To name a few. The search functions were originally written by another developer so I am not completely familiar with it but it looks like they may have moved some namespaces when they updated Lucene to 3.0.3 but I can't find what they updated to.
Any help would be greatly appreciated!
Thanks
Code Example Below
References:
Imports Microsoft.WindowsAzure.Storage.Blob
Imports Microsoft.WindowsAzure.Storage
Imports Lucene.Net
Imports Lucene.Net.Documents
Imports Lucene.Net.Store
Imports Lucene.Net.Index
Imports Lucene.Net.Analysis
The Lucene.Net.Store says it doesn't contain any public members.
Example function that says Lucene.Net.Index.IndexWriter is not defined
Private Function IndexNewDocument(id As String, savePath As String, targetContainer As String, indexer As Lucene.Net.Index.IndexWriter, b As CloudBlockBlob) As Boolean
Dim sw As Stopwatch = Stopwatch.StartNew
Dim filename As String = ""
Dim dt As DateTime = Now
Try
' Retrieve the document and pull the metadata for reindexing
Dim docReturn As DocumentReturn = DocumentDownloadAdapter.GetDocument(_StorageEndpoint, _NewDocumentContainerName, id)
filename = docReturn.Filename
dt = docReturn.DateAdded
' Get the blob reader for indexing
Dim docReader As IBlobDocumentReader = FileProcessor.GetBlobDocumentReader(docReturn.FileBytes, docReturn.Filename, savePath)
' push the index to the blob storage database
pushIndexDocument(id, filename, dt, docReader, indexer)
sw.Stop()
OnDocumentIndexSuccessful(id, filename, sw.Elapsed)
Return True
Catch ex As EmptyPDFException
CommonCodeLib.ErrorReport("AzureStorageAccountAdapter.indexDocument", ex, "")
' DELETE FILE FROM NEW BLOB INDEX
Try
b.Delete()
Catch exDelete As Exception
CommonCodeLib.ErrorReport("AzureStorageAccountAdapter.indexDocument: Problem Deleting blob", exDelete, "")
End Try
Try
Dim username As String = getDocumentUsername(targetContainer, id)
EmailAdapter.SendExceptionEmail(ex, GetEmailList(ConfigurationHelper.IndexEmailToList), GetEmailList(ConfigurationHelper.IndexEmailCCList), username)
Catch exEmail As Exception
CommonCodeLib.ErrorReport("AzureStorageAccountAdapter.indexDocument: Problem Emailing Exception", exEmail, "")
End Try
Return False
Catch ex As InvalidDocumentTypeException
CommonCodeLib.ErrorReport("AzureStorageAccountAdapter.indexDocument", ex, "")
' DELETE FILE FROM NEW BLOB INDEX
Try
b.Delete()
Catch exDelete As Exception
CommonCodeLib.ErrorReport("AzureStorageAccountAdapter.indexDocument: Problem Deleting blob", exDelete, "")
End Try
Try
Dim username As String = getDocumentUsername(targetContainer, id)
EmailAdapter.SendExceptionEmail(ex, GetEmailList(ConfigurationHelper.IndexEmailToList), GetEmailList(ConfigurationHelper.IndexEmailCCList), username)
Catch exEmail As Exception
CommonCodeLib.ErrorReport("AzureStorageAccountAdapter.indexDocument: Problem Emailing Exception", exEmail, "")
End Try
Return False
Catch ex As Exception
CommonCodeLib.ErrorReport("AzureStorageAccountAdapter.indexDocument", ex.ToString, "")
sw.Stop()
OnDocumentIndexFailed(id, filename, sw.Elapsed, ex)
Return False
End Try
End Function

Copy audio file from Windows Form Application Resource to Hard drive

Using Visual Studio 2013
I have been attempting to copy an audio .wav file from a vb.net Windows Form Application to no avail. I have attempted a few methods:
File.Copy(My.Resource.click1, "c:\destination folder", True)
I have tried calling a Sub
Dim ms As New MemoryStream
My.Resources.click1.CopyTo(ms)
Dim ByteArray() As Byte = ms.ToArray
sfr(toPath2 & "\click1.wav", ByteArray)
Public Sub sfr(ByVal FilePath As Byte, ByVal File As Object)
Dim FByte() As Byte = File
My.Computer.FileSystem.WriteAllBytes(FilePath, FByte, True)
End Sub
I have also tried
File.WriteAllText(toPath2 & "\click1.wav", My.Resources.click1)
How does one copy an audio resource to the hard drive?
Here is a VB.Net version of the tested C# version:
Dim asm As Assembly = Assembly.GetExecutingAssembly()
Dim file As String = String.Format("{0}.click1.wav", asm.GetName().Name)
Dim fileStream As Stream = asm.GetManifestResourceStream(file)
SaveStreamToFile("c:\Temp\click1.wav", fileStream) '<--here is the call to save to disk
Public Sub SaveStreamToFile(fileFullPath As String, stream As Stream)
If stream.Length = 0 Then
Return
End If
' Create a FileStream object to write a stream to a file
Using fileStream As FileStream = System.IO.File.Create(fileFullPath, CInt(stream.Length))
' Fill the bytes[] array with the stream data
Dim bytesInStream As Byte() = New Byte(stream.Length - 1) {}
stream.Read(bytesInStream, 0, CInt(bytesInStream.Length))
' Use FileStream object to write to the specified file
fileStream.Write(bytesInStream, 0, bytesInStream.Length)
End Using
End Sub
+1 on detailing your attempts before posting, let me know how you go.
Here is the Code Nice And Easy :
Dim FilePath AS String = Application.StartupPath + "\From_Resource.wav"
IO.File.WriteAllBytes(FilePath,My.Resource.click1)
and then you can check if it exists :
If IO.File.Exists(FilePath) Then MsgBox("File Exists")
and one more trick , Play it in Default Player :
Process.Start(FilePath)
Thank you all for your suggestions. This is what I came up with to perform the task that I needed.
Dim ms As New MemoryStream
My.Resources.click1.CopyTo(ms)
Dim AudioFile() As Byte = ms.ToArray
File.WriteAllBytes(toPath2 & "\click1.wav", AudioFile) '<-- toPath2 is a specific folder I am saving to
ms.Close()

How do I allow concurrent reads and writes to a serialized binary file

I wrote a module to serialize a generic list into a binary file. If I wanted to allow multiple users to write to a file at the same time, or multiple users to read from the file at the same time, what do I need to do? I know there is a FileAccess enumeration I can pass to my filestream, but I am not sure what the limitations are, or what to set it as.
If FileAccess is for something else, what other solutions are there? (no databases)
Dim _Format As New BinaryFormatter
Public Function SavePack(Of T)(Filename As String, Output As T) As Boolean
SavePack(New FileStream(Filename, FileMode.Create), Output)
End Function
Public Function SavePack(Of T)(Stream As FileStream, Output As T) As Boolean
Dim Result As Boolean = False
Try
_Format.Serialize(Stream, Output)
Catch ex As Exception
Stream.Close()
End Try
Return Result
End Function

vb.net image save to memory stream results in an ArgumentNullException

In VB.NET I have the following function that allows me to calculate a hash for an image I have not yet saved to a file :
Public Function pictureHash(ByVal image As System.Drawing.Image) As String
Try
If image Is Nothing Then Return Nothing
Dim ha As HashAlgorithm = HashAlgorithm.Create()
Dim ms As New MemoryStream()
image.Save(ms, image.RawFormat)
ms.Position = 0
Dim imageHash As Byte() = ha.ComputeHash(ms)
ms.Close()
Return BitConverter.ToString(imageHash)
Catch ex As Exception
Return Nothing
End Try
End Function
The problem is I get an ArgumentNullException on the instruction image.Save(ms, image.rawFormat).
Here is the detail of the exception :
System.ArgumentNullException occurred
Message="Value cannot be null. Parameter name: encoder"
ParamName="encoder"
Source="System.Drawing"
StackTrace:
at System.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams)
at System.Drawing.Image.Save(Stream stream, ImageFormat format)
at MyProgram.pictureHash(Image image)
The thing is, when I look at the stack trace, the last call to Image.Save with 3 parameters (the one that crashes) isn't even made by me, but by the previous Image.Save call.
Any idea what should I do ?
Many thanks in advance for your help,
Regards,
Joël
According to the community content for the Image.Save method, certain image formats do not have an associated encoder and fail with the error you are reporting.
Could you not use a standard format (e.g. bmp or png) when saving the file to the MemoryStream? To do this replace the call to Save with something similar to:
image.Save(ms, ImageFormat.Png)

System.out of Memory Exception for String Builder in SSIS Script Task

I am using a VB script in SSIS Script Task to add header and Trailer to a flat file. The code was working fine until recently i came across a problem where the rows in the file are more than usual and resulting in a failure on script task with error`Error:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
at System.String.GetStringForStringBuilder(String value, Int32 startIndex, Int32 length, Int32 capacity)
at System.Text.StringBuilder.GetNewString(String currentString, Int32 requiredLength)
at System.Text.StringBuilder.Append(Char[] value, Int32 startIndex, Int32 charCount)
at System.IO.StreamReader.ReadToEnd()
at System.IO.File.ReadAllText(String path, Encoding encoding)
at System.IO.File.ReadAllText(String path)`
Can any one help me in fixing the problem please.I think instead of "String Builder" i need to use other string related method. I am getting error at
fileContents.Append(File.ReadAllText(Dts.Connections("DestinationConnection").ConnectionString))
Here is my code:
Public Sub Main()
Dim fileContents As New StringBuilder()
Dim finalfile As String
Dim firstline As String
Dim lastline As String
Dts.VariableDispenser.LockForRead("FirstLine")
Dts.VariableDispenser.LockForRead("LastLine")
Dts.VariableDispenser.LockForRead("FileName")
firstline = CType(Dts.Variables("FirstLine").Value, String)
finalfile = CType(Dts.Variables("FileName").Value, String)
lastline= CType(Dts.Variables("LastLine").Value, String)
'Write header, then append file contents and write back out.
fileContents.AppendLine(String.Format("{0}", firstline))
fileContents.Append(File.ReadAllText(Dts.Connections("DestinationConnection").ConnectionString))
fileContents.AppendLine(String.Format("{0}", lastline))
File.WriteAllText(finalfile, fileContents.ToString())
Dts.TaskResult = ScriptResults.Success
End Sub
Well, one simple way would be to just avoid the StringBuilder: open a TextWriter with File.CreateText, write the first line, then write File.ReadAllText(...), then write the final line.
However, that will only save you some memory - it will roughly halve the memory required, as you won't need it in both the StringBuilder and a string (which is what I think will happen now).
A much better alternative would be to:
Open the writer
Write the header line
Open the other file for reading
Loop over the file, reading a chunk of characters at a time and writing it to the new file, until you're done
Close the other file implicitly (use a Using statement for this)
Write the trailing line
Close the write implicitly (use a Using statement)
That way even if you've got huge files, you only need a small chunk of data in memory at a time.
The problem is File.ReadAllText has limitations when it comes to reading a large file because the entire file is read into memory.
What you will need to do is replace the File.ReadAllText with reading the file line by line and append it accordingly.
EDITED FOR AN EXAMPLE:
Option Explicit
Dim oFSO, sFile, oFile, sText
Set oFSO = CreateObject("Scripting.FileSystemObject")
sFile = "your text file"
If oFSO.FileExists(sFile) Then
Set oFile = oFSO.OpenTextFile(sFile, 1)
Do While Not oFile.AtEndOfStream
sText = oFile.ReadLine
If Trim(sText) <> "" Then
fileContents.AppendLine(sText)
End If
Loop
oFile.Close
Else
WScript.Echo "The file was not there."
End If
It's possible you may still have an issue with the fileContents StringBuilder. The original error shown though was thrown from the File.ReadAllText method. So hopefully, this does the trick.
If not, I would just forget about the fileContents StringBuilder all together and write out the header. Then read from the file line by line and write it out line by line, then finally write the footer.
An alternative (and much more SSIS-like) solution would be to create a Data Flow Task that reads your existing file, pipes it through a Script Component that adds the header and footer, and writes it to the file system. Here's what it might look like in SSIS 2005:
The Script Component will be a Transformation with the SynchronousInputID of its output set to False, so that it can generate header and footer rows:
And the VB source of the transform should look something like this:
Public Class ScriptMain
Inherits UserComponent
Dim headerWritten As Boolean = False
Public Overrides Sub IncomingRows_ProcessInputRow(ByVal Row As IncomingRowsBuffer)
If Not headerWritten Then
WriteHeader()
End If
OutgoingRowsBuffer.AddRow()
OutgoingRowsBuffer.theLine = Row.theLine
End Sub
Public Overrides Sub FinishOutputs()
MyBase.FinishOutputs()
WriteFooter()
End Sub
Private Sub WriteHeader()
OutgoingRowsBuffer.AddRow()
OutgoingRowsBuffer.theLine = "The First Header Line"
headerWritten = True
End Sub
Private Sub WriteFooter()
OutgoingRowsBuffer.AddRow()
OutgoingRowsBuffer.theLine = "Here's a footer line"
OutgoingRowsBuffer.AddRow()
OutgoingRowsBuffer.theLine = "Here's another one"
End Sub
End Class
This lets you use the streaming capabilities of SSIS to your advantage.