Destination array was not long anough when reading mp3 file with NAudio - naudio

I've got this code:
static void Main(string[] args)
{
try
{
Mp3FileReader reader = new Mp3FileReader(#"C:\testAudio.mp3");
long count = reader.Length;
if (count <= int.MaxValue)
{
byte[] info = new byte[count];
reader.Read(info, 0, (int)count);
Console.WriteLine("Succesfull read");
}
else
Console.WriteLine("Could not read");
}
catch(Exception ex)
{
Console.WriteLine(ex);
}
}
that prints out the following exception message:
System.ArgumentException: Destination array was not long enough. Check destIndex and length, and the array's lower bounds.
at System.Array.Copy(Array sourceArray, Int32 sourceIndex, Array destinationArray, Int32 destinationIndex, Int32 length, Boolean reliable)
at System.Array.Copy(Array sourceArray, Int32 sourceIndex, Array destinationArray, Int32 destinationIndex, Int32 length)
at NAudio.Wave.AcmMp3FrameDecompressor.DecompressFrame(Mp3Frame frame, Byte[] dest, Int32 destOffset) in C:\NAudio-Source\NAudio\FileFormats\Mp3\Mp3FrameDecompressor.cs:line 50
at NAudio.Wave.Mp3FileReader.Read(Byte[] sampleBuffer, Int32 offset, Int32 numBytes) in C:\NAudio-Source\NAudio\Wave\WaveStreams\Mp3FileReader.cs:line 338
at Tester.Program.Main(String[] args) in C:\Tester\Program.cs:line 30
I've downloaded NAudio code and I've been debugging it but I can't find the cause of the error, although, as you can see on the stack trace is in NAudio-Source\NAudio\FileFormats\Mp3\Mp3FrameDecompressor.cs:line 50
Am I doing something wrong? By the way, it only happens with a few mp3 files, others are read just fine. I could send one conflicted file if needed.
-------------------------EDIT TO REFER TO THREAD ON NAUDIO CODEPLEX--------------------------------
See this issue on Codeplex Same question on Codeplex NAudio

Don't try to read the entire file in one hit. Instead, read around one seconds worth at a time and keep going until Read returns 0.

Related

Epplus Desktop Application - Unable to determine the identity of domain

I have just starting my excel interop code to epplus and did it when savng an excel document but I can't read an existing file. I searched but every result is related with web applications, I am developing a desktop application.
My code is so simple:
Dim File As FileInfo = New FileInfo(DosyaAd)
Using package As New ExcelPackage(File)
Dim She As ExcelWorksheet
She = package.Workbook.Worksheets("BF")
End using
I got this error at: She = package.Workbook.Worksheets("BF")
System.IO.IsolatedStorage.IsolatedStorageException was unhandled by user code
HResult=-2146233264
Message=Unable to determine the identity of domain.
Source=mscorlib
StackTrace:
at System.IO.IsolatedStorage.IsolatedStorage._GetAccountingInfo(Evidence evidence, Type evidenceType, IsolatedStorageScope fAssmDomApp, Object& oNormalized)
at System.IO.IsolatedStorage.IsolatedStorage.GetAccountingInfo(Evidence evidence, Type evidenceType, IsolatedStorageScope fAssmDomApp, String& typeName, String& instanceName)
at System.IO.IsolatedStorage.IsolatedStorage._InitStore(IsolatedStorageScope scope, Evidence domainEv, Type domainEvidenceType, Evidence assemEv, Type assemblyEvidenceType, Evidence appEv, Type appEvidenceType)
at System.IO.IsolatedStorage.IsolatedStorage.InitStore(IsolatedStorageScope scope, Type domainEvidenceType, Type assemblyEvidenceType)
at System.IO.IsolatedStorage.IsolatedStorageFile.GetStore(IsolatedStorageScope scope, Type domainEvidenceType, Type assemblyEvidenceType)
at MS.Internal.IO.Packaging.PackagingUtilities.ReliableIsolatedStorageFileFolder.GetCurrentStore()
at MS.Internal.IO.Packaging.PackagingUtilities.ReliableIsolatedStorageFileFolder..ctor()
at MS.Internal.IO.Packaging.PackagingUtilities.GetDefaultIsolatedStorageFile()
at MS.Internal.IO.Packaging.PackagingUtilities.CreateUserScopedIsolatedStorageFileStreamWithRandomName(Int32 retryCount, String& fileName)
at MS.Internal.IO.Packaging.SparseMemoryStream.SwitchModeIfNecessary()
at MS.Internal.IO.Packaging.SparseMemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count)
at MS.Internal.IO.Packaging.DeflateEmulationTransform.Decompress(Stream source, Stream sink)
at MS.Internal.IO.Packaging.CompressEmulationStream..ctor(Stream baseStream, Stream tempStream, Int64 position, IDeflateTransform transformer)
at MS.Internal.IO.Packaging.CompressStream.ChangeMode(Mode newMode)
at MS.Internal.IO.Packaging.CompressStream.Seek(Int64 offset, SeekOrigin origin)
at MS.Internal.IO.Zip.ProgressiveCrcCalculatingStream.Seek(Int64 offset, SeekOrigin origin)
at MS.Internal.IO.Zip.ZipIOModeEnforcingStream.Read(Byte[] buffer, Int32 offset, Int32 count)
at System.IO.StreamReader.ReadBuffer(Char[] userBuffer, Int32 userOffset, Int32 desiredChars, Boolean& readToUserBuffer)
at System.IO.StreamReader.Read(Char[] buffer, Int32 index, Int32 count)
at System.IO.StreamReader.ReadBlock(Char[] buffer, Int32 index, Int32 count)
at OfficeOpenXml.ExcelWorksheet.GetWorkSheetXml(Stream stream, Int64 start, Int64 end, Encoding& encoding)
at OfficeOpenXml.ExcelWorksheet.CreateXml()
at OfficeOpenXml.ExcelWorksheet..ctor(XmlNamespaceManager ns, ExcelPackage excelPackage, String relID, Uri uriWorksheet, String sheetName, Int32 sheetID, Int32 positionID, eWorkSheetHidden hide)
at OfficeOpenXml.ExcelWorksheets..ctor(ExcelPackage pck, XmlNamespaceManager nsm, XmlNode topNode)
at OfficeOpenXml.ExcelWorkbook.get_Worksheets()
at OfficeOpenXml.ExcelWorkbook.GetDefinedNames()
at OfficeOpenXml.ExcelPackage.get_Workbook()
.........
If this workbook was generated in Microsoft Office or through the interop, the workbook may contain features that are not available through the EPPLus library, such as lines and themes, and others listed here.
I have not experienced it myself, but I have heard from others that issues come up when the Worksheet contains a lot of content.

confuse about EndUploadFromStream

I am confusing with a problem about upload blobs asynchronously, hopes find answer here.
Please take a look at my code snippet first,
public void UploadMultipleBlobs(List<string> filelocations, string containerName, AsyncCallback callback = null, string path = null)
{
try
{
Parallel.ForEach(filelocations, fileLocation =>
{
//File to Stream
MemoryStream str = new MemoryStream();
byte[] file = File.ReadAllBytes(fileLocation);
str.Write(file, 0, file.Length);
str.Seek(0, SeekOrigin.Begin);
//Operations
if (callback == null)
callback = new AsyncCallback(OnUploadCompleted);
BlobRequestOptions blobRequestOptions = new BlobRequestOptions();
blobRequestOptions.Timeout = new TimeSpan(1, 0, 0);
blobRequestOptions.RetryPolicy = retry;
CloudBlob currentBlob = container.GetBlobReference(blobName);
var result = currentBlob.BeginUploadFromStream(str, blobRequestOptions, callback, new Object[] { currentBlob, str });
currentBlob.EndUploadFromStream(result);
});
}
catch
{
throw;
}
}
private void OnUploadCompleted(IAsyncResult result)
{
try
{
// Get array passed to callback
Object[] states = (Object[])result.AsyncState;
var blob = (CloudBlob)states[0];
var stream = (MemoryStream)states[1];
// End the operation
//blob.EndUploadFromStream(result);
// Close the stream
stream.Close();
}
catch
{
throw;
}
}
I need to upload mutil files to Azure blob, number of files may be 10-50,000, each file is about 10KB-50KB. The code snippet works fine for me currently. However, if I call EndUploadFromStream in callback, it always throw an exception when uploading over 2,000 files. I mean if I remove EndUploadFromStream in upload method and call EndUploadFromStream in callback(OnUploadCompleted method), the exception happens. The exception message as below:
Unable to read data from the transport connection: The connection was closed., StackTrace: at Microsoft.WindowsAzure.StorageClient.Tasks.Task`1.get_Result()
at Microsoft.WindowsAzure.StorageClient.CloudBlob.EndUploadFromStream(IAsyncResult asyncResult)
I don't know why it happens...hopes got answer from you guys.
Thanks.
The Begin/End code looks OK. I notice that you're not doing anything to wait for the asynchronous operations to complete, so the problem may be related to that. eg, if you're running this from a console application then the application may exit before all the uploads have completed and then give you those errors. That would not be a problem if the EndUploadFromStream() call is inside the Parallel.ForEach() because it will cause the Parallel.ForEach() call to block until all the uploads have completed.
So try adding code to wait for all the uploads to complete and see if that fixes it. A simple way would be a counter that is initialized to the total number of uploads, and then decremented (using Interlocked.Decremement() for thread safety) inside of the callback. Another options would be use Task.FromAsync() to get an array of Task objects, then using Task.WaitAll() to wait for them to complete.
As an aside, using both Parallel.ForEach() and Begin/End methods at the same time is usually redundant - Begin/End is asynchronous already so there's usually no point using multiple threads to invoke it. Since you have such a big list of items it might make some difference in this case, but probably not much. You're probably better off using a simple foreach loop instead of Parallel.ForEach() unless you've actually measured a significant difference.

What things should I consider when I get an intermittent exception in Visual Basic .net (debugging in Visual Studio Express 2010)?

I'm testing my Visual Basic .net application by running it in Visual Studio express.
Sometimes it runs OK, but other times I get an exception (details below, if useful). I'm not sure why I get the exception as the particular part of the application that I am testing re-uses code that works OK for other features.
What should I check, what would give me a hint as to the root cause.
Things I tried so far are:
Rewriting some of the code to be more robust. The outcome of this was that this approach was getting out of control - I was correcting everything. I made changes such asing alternative libraries (e.g. replacing CInt with convertTo etc). Some lazy declarations, but it occurred to me that there was no problem with these with the code before my changes. And every change I seemed to solve uncovered yet another problem, another different exception
So I thought something must be fundamentally wrong with my installation, and a search found discussion group posts from people experiencing something similar. The suggested remedy would be to re-install the .net framework. So I did that and the problems still occured.
Any thoughts on approach to get to the root of the problem? I'm not asking for a solution but some fresh ideas would be very welcome.
Update:
I've added in the following code to get more detail (+1 thanks #Meta-Knight)
Dim exceptionMessage As String = ex.Message
Console.WriteLine("Message: \n" & exceptionMessage)
Dim exceptionTargetSite As String = ex.TargetSite.ToString
Console.WriteLine("Inner: \n" & ex.TargetSite.ToString)
Dim exceptionSource As String = ex.Source
Console.WriteLine("Source\n:" & exceptionSource)
' put the stack trace into a variable
' (this helps debugging - put a break point after this is assigned
' to see the contents)
Dim stackTrace As String = ex.StackTrace.ToString()
Console.WriteLine("Stack trace\n:" & stackTrace)
More details about exception
Error - Exception Message
"Arithmetic operation resulted in an overflow."
Exception Target Site:
"Int32 ToInteger(System.String)"
Exception Source:
"Microsoft.VisualBasic"
at Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(String Value) at MyCo_3rd-Party-Industrial-Printing-System.Customer_EanUpc_serialNumberGeneratorAssembly.btnPrint_Click(Object sender, EventArgs e) in C:\labelprint\MyCo 3rd-Party-Industrial-Printing-System v2\MyCo 3rd-Party-Industrial-Printing-System\PrintForms\Customer_EanUpc_serialNumberGeneratorAssembly.vb:line 271 at System.Windows.Forms.Control.OnClick(EventArgs e) at System.Windows.Forms.Button.OnClick(EventArgs e) at System.Windows.Forms.Button.PerformClick() at System.Windows.Forms.Form.ProcessDialogKey(Keys keyData) at System.Windows.Forms.Control.ProcessDialogKey(Keys keyData) at System.Windows.Forms.Control.PreProcessMessage(Message& msg) at System.Windows.Forms.Control.PreProcessControlMessageInternal(Control target, Message& msg) at System.Windows.Forms.Application.ThreadContext.PreTranslateMessage(MSG& msg) at System.Windows.Forms.Application.ThreadContext.System.Windows.Forms.UnsafeNativeMethods.IMsoComponent.FPreTranslateMessage(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.RunDialog(Form form) at System.Windows.Forms.Form.ShowDialog(IWin32Window owner) at System.Windows.Forms.Form.ShowDialog() at MyCo_3rd-Party-Industrial-Printing-System.utlForm.openNewModalForm(String form) in C:\labelprint\MyCo 3rd-Party-Industrial-Printing-System v2\MyCo 3rd-Party-Industrial-Printing-System\Utilities\utlForm.vb:line 128
Update 2:
The code around line 272 was:
For i As Integer = 1 To CInt(numQuantity)
If generationMethods() Then
The code around line 272 is now (I've adjusted it):
Dim numQuantityAsStr As String = numQuantity.Text
Dim numQuantityAsInt As Integer = Convert.ToInt32(numQuantityAsStr)
For i As Integer = 1 To numQuantityAsInt
If generationMethods() Then
numQuantity is a String variable for a field in the Windows form I am using and this has a value put in it by the user, the field is used to specify the quantity of something so this variable is converted to a integer so that it can be used in a for loop. The test value I am using is always entering 1 in this field, and sometimes this causes the exception.
My alteration uses what I think is a more modern type conversion Convert.ToInt32 rather than CInt I've also introduced intermediate steps to help debug.
The exception now does not occur here but I did try this the other week and another separate exception popped up (if I remember) from somewhere else so we'll see if this fixes it. Any thoughts as to why using a different conversion utility would solve the problem?
Update 3:
An Exception now occurs elsewhere:
(But why?! This one is thrown from library code!)
The following code caused it:
Dim dateNowAsStr As String = DateTime.Now.Date.ToString
Exception Message:
"Value to add was out of range. Parameter name: value"
Exception target site:
"System.DateTime Add(Double, Int32)"
Exception source:
"mscorlib"
" at System.DateTime.Add(Double value, Int32 scale) at System.TimeZoneInfo.TransitionTimeToDateTime(Int32 year, TransitionTime transitionTime) at System.TimeZoneInfo.GetDaylightTime(Int32 year, AdjustmentRule rule) at System.TimeZoneInfo.GetIsDaylightSavingsFromUtc(DateTime time, Int32 Year, TimeSpan utc, AdjustmentRule rule, Boolean& isAmbiguousLocalDst) at System.TimeZoneInfo.GetDateTimeNowUtcOffsetFromUtc(DateTime time, Boolean& isAmbiguousLocalDst) at System.DateTime.get_Now() at GenerationLibrary.GenerationUtilities.callserialNumberGenerator(String serialNumberGeneratorSnFile, String serialNumberGeneratorRange, DefaultSettingsHandler settings) in C:\labelprint\MyCo 3rd-Party-Industrial-Printing-System v2\GenerationLibrary\GenerationUtilities.vb:line 28 at GenerationLibrary.MyCoSnGeneration.constructMyCoSn(DataRow& oDataRow, DefaultSettingsHandler& settings) in C:\labelprint\MyCo 3rd-Party-Industrial-Printing-System v2\GenerationLibrary\MyCoSnGeneration.vb:line 18 at MyCo_3rd-Party-Industrial-Printing-System.Customer_EanUpc_serialNumberGeneratorAssembly.generationMethods() in C:\labelprint\MyCo 3rd-Party-Industrial-Printing-System v2\MyCo 3rd-Party-Industrial-Printing-System\PrintForms\Customer_EanUpc_serialNumberGeneratorAssembly.vb:line 40 at MyCo_3rd-Party-Industrial-Printing-System.Customer_EanUpc_serialNumberGeneratorAssembly.btnPrint_Click(Object sender, EventArgs e) in C:\labelprint\MyCo 3rd-Party-Industrial-Printing-System v2\MyCo 3rd-Party-Industrial-Printing-System\PrintForms\Customer_EanUpc_serialNumberGeneratorAssembly.vb:line 275 at System.Windows.Forms.Control.OnClick(EventArgs e) at System.Windows.Forms.Button.OnClick(EventArgs e) at System.Windows.Forms.Button.PerformClick() at System.Windows.Forms.Form.ProcessDialogKey(Keys keyData) at System.Windows.Forms.Control.ProcessDialogKey(Keys keyData) at System.Windows.Forms.Control.PreProcessMessage(Message& msg) at System.Windows.Forms.Control.PreProcessControlMessageInternal(Control target, Message& msg) at System.Windows.Forms.Application.ThreadContext.PreTranslateMessage(MSG& msg) at System.Windows.Forms.Application.ThreadContext.System.Windows.Forms.UnsafeNativeMethods.IMsoComponent.FPreTranslateMessage(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.RunDialog(Form form) at System.Windows.Forms.Form.ShowDialog(IWin32Window owner) at System.Windows.Forms.Form.ShowDialog() at MyCo_3rd-Party-Industrial-Printing-System.utlForm.openNewModalForm(String form) in C:\labelprint\MyCo 3rd-Party-Industrial-Printing-System v2\MyCo 3rd-Party-Industrial-Printing-System\Utilities\utlForm.vb:line 128"
Update 4
BUT
Dim dateNowAsStr As String = CStr(DateTime.Now)
does not cause the exception
Before rewriting or reinstalling anything, you should try to identify the source and the reason for the error.
The first thing to do is to analyse the error message and stack trace. If you include debugging files (.pdb) with your application's files, you will get more detailed information such as the line number which can be helpful.
If that doesn't give enough information about the circumstances of the error, then you can add some logging to your app. By logging what the user does in your app it might help reproduce the problem.
Finally you can always get help by searching on google or asking on StackOverflow, but make sure to include the actual error message, not just the stack trace... You should also post the code where the error happens.
Edit:
So the actual error is: "Arithmetic operation resulted in an overflow."
Googling this would have helped: you would have found out that such an error happens when you're trying to convert a number which is out of bounds for an integer. If you expect to have some very large numbers you can try converting to Long instead.
I think you can start by looking at what is at line 271 of the Customer_EanUpc_serialNumberGeneratorAssembly.vb source code file.
Which is located: C:\labelprint\MyCo 3rd-Party-Industrial-Printing-System v2\MyCo 3rd-Party-Industrial-Printing-System\PrintForms\ directory.
It looks like the problem is related to a conversion between string to integer where maybe it failed because the string cannot be converted to integer... maybe it has alphanumeric characters...
"Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(String Value)"
Did you already check that?
Why you get the error some times and not always could be because (and I'm guessing here) the code in serialNumberGeneratorAssembly sometimes generates numeric only values (that can be correctly converted to integer) and some other times generates alphanumeric serial numbers (that throw the convertion exception).
UPDATE: the code that generates the Serial Numbers is generating numbers bigger than an Integer value. Try converting to Long instead of Integer... or have a look at System.Numerics.BigInteger in case those numbers are too big.
That explains the: "Arithmetic operation resulted in an overflow." exception message.

Monodroid camera + preview

Please someone help me. I have tried to convert http://drobosson.blogspot.com/2011/01/google-android-camera-preview-data.html and http://marakana.com/forums/android/examples/39.html to Monodroid (C#) and have had no success. I have followed the instructions (as far as I can see) and I do not know how to preview the camera (I am not even on taking a PICTURE yet).
Here is my current code - it fails on the Android.Hardware.Camera.Open() method with a Java.Lang.RuntimeException (Stacktrace says "at Android.Runtime.JNIEnv.CallStaticObjectMethod (IntPtr jclass, IntPtr jmethod) [0x00000] in :0 at Android.Hardware.Camera.Open()...")
I have added the camera permission in the manifest.
Code:
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.CameraPage);
_surfaceView = FindViewById<SurfaceView>(Resource.Id.imgCapture);
_debug = FindViewById<TextView>(Resource.Id.lblCameraDebug);
try
{
_camera = Android.Hardware.Camera.Open();
//Android.Hardware.Camera.Parameters camparam = _camera.GetParameters();
//camparam.SetPreviewSize(_surfaceView.Width, _surfaceView.Height);
//_camera.SetParameters(camparam);
//_camera.SetPreviewDisplay(_surfaceView.Holder);
//_camera.StartPreview();
}
catch(Exception ex)
{
_debug.Text = string.Format("Error: {0} - StackTrace: {1}", ex.Message,ex.StackTrace);
}
}
https://github.com/xamarin/monodroid-samples/blob/master/ApiDemo/Graphics/CameraPreview.cs
This clears most of it up. It's a starting point, not a solution.
It does NOT solve:
1. Rotation / Orientation (but that should be in the parameters)
2. Getting it onto a form element using axml (not as an entire page)
3. Taking a picture.

Apache MINA networking - How to get data from org.apache.mina.core.service.IoHandlerAdapter messageRecieved(IoSession, Object)

public void messageReceived(IoSession session, Object message) throws Exception
{
// do something
}
Can anyone tell me how to get data from the Object?
It's really quite simple, just cast the message into an IoBuffer and pull out the bytes.
// cast message to io buffer
IoBuffer data = (IoBuffer) message;
// create a byte array to hold the bytes
byte[] buf = new byte[data.limit()];
// pull the bytes out
data.get(buf);
// look at the message as a string
System.out.println("Message: " + new String(buf));
Cast message to the object type you used in the client's session.write.