Inheritance: SystemException
        public void CustomMediaRetryPolicyTestExceededMaxRetryAttempts()
        {
            MediaRetryPolicy target = new TestMediaServicesClassFactoryForCustomRetryPolicy(null).GetBlobStorageClientRetryPolicy();

            int exceptionCount = 4;
            int expected = 10;
            //This is the new exception included for retrypolicy in the customretrypolicy
            var fakeException = new IOException("CustomRetryPolicyException");

            Func<int> func = () =>
            {
                if (--exceptionCount > 0) throw fakeException;
                return expected;
            };

            try
            {
                target.ExecuteAction(func);
            }
            catch (AggregateException ax)
            {
                IOException x = (IOException)ax.Flatten().InnerException;
                Assert.AreEqual(1, exceptionCount);
                Assert.AreEqual(fakeException, x);
                //Exception is retried only for max retrial attempts,
                //In this case there are max of 2 attempts for blob retry policy.
                Assert.AreEqual(exceptionCount, 1);
                throw;
            }
        }
示例#2
0
        private void ReadFrameCallback(IAsyncResult transportResult)
        {
            GlobalLog.Assert(transportResult.AsyncState is WorkerAsyncResult, "StreamFramer::ReadFrameCallback|The state expected to be WorkerAsyncResult, received:{0}.", transportResult.GetType().FullName);
            if (transportResult.CompletedSynchronously)
            {
                return;
            }

            WorkerAsyncResult workerResult = (WorkerAsyncResult)transportResult.AsyncState;

            try
            {
                ReadFrameComplete(transportResult);
            }
            catch (Exception e) {
                if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException)
                {
                    throw;
                }

                if (!(e is IOException))
                {
                    e = new System.IO.IOException(SR.GetString(SR.net_io_readfailure, e.Message), e);
                }

                // Let's call user callback and he call us back and we will throw
                workerResult.InvokeCallback(e);
            }
        }
示例#3
0
        private void ReadFrameCallback(IAsyncResult transportResult)
        {
            if ((transportResult.AsyncState is WorkerAsyncResult) && GlobalLog.IsEnabled)
            {
                GlobalLog.Assert("StreamFramer::ReadFrameCallback|The state expected to be WorkerAsyncResult, received:{0}.", transportResult.GetType().FullName);
            }

            if (transportResult.CompletedSynchronously)
            {
                return;
            }

            WorkerAsyncResult workerResult = (WorkerAsyncResult)transportResult.AsyncState;

            try
            {
                ReadFrameComplete(transportResult);
            }
            catch (Exception e)
            {
                if (e is OutOfMemoryException)
                {
                    throw;
                }

                if (!(e is IOException))
                {
                    e = new System.IO.IOException(SR.Format(SR.net_io_readfailure, e.Message), e);
                }

                workerResult.InvokeCallback(e);
            }
        }
 private PostEditorStorageException(IOException ex)
     : base(StringId.PostEditorStorageExceptionTitle2,
     StringId.PostEditorStorageExceptionMessage2,
     ex.GetType().Name,
     ex.Message)
 {
 }
示例#5
0
        static private bool listarArchivos(List <string> archivos, List <string> hojas, List <string> renglon, List <string> columna)
        {//http://spreadsheetlight.com/sample-code/
            System.IO.IOException res = null;
            SLDocument            sl  = null;

            try
            {
                sl = new SLDocument(@"..\archivos.xlsx", "Hoja1");
                int    cont = 1;
                string archivo;
                while (!string.IsNullOrWhiteSpace(archivo = sl.GetCellValueAsString(++cont, 1)))
                {
                    archivos.Add(archivo);
                    hojas.Add(sl.GetCellValueAsString(cont, 2));
                    renglon.Add(sl.GetCellValueAsString(cont, 3));
                    columna.Add(sl.GetCellValueAsString(cont, 4));
                }
                sl.CloseWithoutSaving();
            }
            catch (System.IO.IOException e)
            {
                res = e;
                Console.WriteLine("el archivo \"archivos.xlsx\" no existe o se encuentra abierto");
                Console.ReadKey();
            }
            return(res == null);
        }
示例#6
0
        private void ReadFrameCallback(IAsyncResult transportResult)
        {
            if (!(transportResult.AsyncState is WorkerAsyncResult))
            {
                NetEventSource.Fail(this, $"The state expected to be WorkerAsyncResult, received {transportResult}.");
            }

            if (transportResult.CompletedSynchronously)
            {
                return;
            }

            WorkerAsyncResult workerResult = (WorkerAsyncResult)transportResult.AsyncState;

            try
            {
                ReadFrameComplete(transportResult);
            }
            catch (Exception e)
            {
                if (e is OutOfMemoryException)
                {
                    throw;
                }

                if (!(e is IOException))
                {
                    e = new System.IO.IOException(SR.Format(SR.net_io_readfailure, e.Message), e);
                }

                workerResult.InvokeCallback(e);
            }
        }
		private void AsyncRead (Handle handle, Result result, byte[] buf,
					ulong bytesRequested, ulong bytesRead)
		{
			if (result == Result.Ok) {
				Array.Copy (buf, 0, buffer, offset + count - bytesRemaining, (int)bytesRead);
				bytesRemaining -= (int)bytesRead;
				if (bytesRemaining > 0) {
					buf = new byte[bytesRemaining];
					Async.Read (handle, out buf[0], (uint)bytesRemaining,
						    new AsyncReadCallback (AsyncRead));
				} else if (cback != null) {
					asyncResult.SetComplete (null, count);
					cback (asyncResult);
				}
			} else if (result == Result.ErrorEof) {
				Array.Copy (buf, 0, buffer, offset + count - bytesRemaining, (int)bytesRead);
				bytesRemaining -= (int)bytesRead;
				asyncResult.SetComplete (null, count - bytesRemaining);
				
				if (cback != null)
					cback (asyncResult);
			} else if (cback != null) {
				Exception e = new IOException (Vfs.ResultToString (result));
				asyncResult.SetComplete (e, -1);
				cback (asyncResult);
			}
		}
示例#8
0
        static private bool llenarFormatos(List <string> alLista, List <string> archivos, List <string> hojas, List <string> renglon, List <string> columna)
        {//http://spreadsheetlight.com/sample-code/
            System.IO.IOException res = null;
            SLDocument            sl  = null;

            for (int i = 0; i < archivos.Count; i++)
            {
                try
                {
                    sl = new SLDocument(@"..\" + archivos.ElementAt(i) + ".xlsx", hojas.ElementAt(i));
                    int alNumero = int.Parse(renglon.ElementAt(i));
                    for (int j = 0; j < alLista.Count; j++)
                    {
                        sl.SetCellValue(alNumero++, int.Parse(columna.ElementAt(i)), alLista.ElementAt(j));
                    }
                    string strNombre;
                    while (!string.IsNullOrWhiteSpace(strNombre = sl.GetCellValueAsString(alNumero, int.Parse(columna.ElementAt(i)))))
                    {
                        sl.SetCellValue(alNumero++, int.Parse(columna.ElementAt(i)), "");
                    }
                    sl.Save();
                }
                catch (System.IO.IOException e)
                {
                    res = e;
                    Console.WriteLine("el archivo \"" + archivos.ElementAt(i) + ".xlsx\" no existe o se encuentra abierto");
                    Console.ReadKey();
                }
            }
            return(res == null);
        }
        public void AddFileInUseTests()
        {
            // Arrange
            var fileName = @"x:\test\temp.txt";
            var exception = new IOException("file in use");
            var stream = new MemoryStream();
            var zip = new ZipArchive(stream, ZipArchiveMode.Create);
            var tracer = new Mock<ITracer>();
            var file = new Mock<FileInfoBase>();

            // setup
            file.Setup(f => f.OpenRead())
                .Throws(exception);
            file.SetupGet(f => f.FullName)
                .Returns(fileName);
            tracer.Setup(t => t.Trace(It.IsAny<string>(), It.IsAny<IDictionary<string, string>>()))
                  .Callback((string message, IDictionary<string, string> attributes) =>
                  {
                      Assert.Contains("error", attributes["type"]);
                      Assert.Contains(fileName, attributes["text"]);
                      Assert.Contains("file in use", attributes["text"]);
                  });

            // Act
            zip.AddFile(file.Object, tracer.Object, String.Empty);
            zip.Dispose();

            // Assert
            tracer.Verify(t => t.Trace(It.IsAny<string>(), It.IsAny<IDictionary<string, string>>()), Times.Once());
            zip = new ZipArchive(ReOpen(stream));
            Assert.Equal(0, zip.Entries.Count);
        }
 /// <summary>The default constructor for CannotFetchDataException.</summary>
 /// <remarks>The default constructor for CannotFetchDataException.</remarks>
 /// <param name="ex"></param>
 public CannotFetchDataException(IOException ex, string serviceName)
     : this(ex is
         UnknownHostException ? CannotFetchDataException.MSG.UNKNOWN_HOST_EXCEPTION : CannotFetchDataException.MSG
         .IO_EXCEPTION, serviceName)
 {
     cause = ex;
     this.serviceName = serviceName;
 }
 static bool IsSharingViolation(IOException ex)
 {
     // http://stackoverflow.com/questions/425956/how-do-i-determine-if-an-ioexception-is-thrown-because-of-a-sharing-violation
     // don't ask...
     var hResult = System.Runtime.InteropServices.Marshal.GetHRForException(ex);
     const int sharingViolation = 32;
     return (hResult & 0xFFFF) == sharingViolation;
 }
        public static void ShowScanningError(IOException exception)
        {
            var message = exception.Message;
            var options = MessageBoxButton.OK;
            var icon = MessageBoxImage.Error;

            ShowMessageBox(message, options, icon);
        }
示例#13
0
        public void StorageTransientErrorDetectionStrategyTestIOException()
        {
            var exception = new System.IO.IOException();

            bool actual = new StorageTransientErrorDetectionStrategy().IsTransient(exception);

            Assert.IsTrue(actual);
        }
示例#14
0
 public override void SetLength(long value)
 {
     if (BreakHow == BreakHowType.ThrowOnSetLength)
     {
         ThrownException = new IOException();
         throw ThrownException;
     }
 }
示例#15
0
 public void T202_FileFormatException()
 {
     var e2 = new IOException("Test");
     var e = new FileFormatException("Test", e2);
     Assert.Equal("Test", e.Message);
     Assert.Null(e.SourceUri);
     Assert.Same(e2, e.InnerException);
 }
示例#16
0
        public void TestLogExceptionAppendsArgs()
        {
            var exception = new IOException("io");

            _logger.LogException(exception, "Foo {0}", "Bar");
            var result = _writer.ToString();

            Assert.That(result, Is.StringEnding("Foo Bar\r\n"));
        }
示例#17
0
        public void TestLogExceptionPrepends()
        {
            var exception = new IOException("io");

            _logger.LogException(exception, "Foo {0}", "Bar");
            var result = _writer.ToString();

            Assert.That(result, Is.StringStarting("Exception: IOException, io\r\n"));
        }
        public IOException error(Exception why)
        {
            if (why == null)
                throw new ArgumentNullException ("why");

            IOException e;
            e = new IOException("Encryption error: " + why.Message, why);
            return e;
        }
示例#19
0
		static ClusterBase()
		{
			var allDead = new IOException("All nodes are dead.");

			// cached tasks for error reporting
			failSingle = new TaskCompletionSource<IOperation>();
			failBroadcast = new TaskCompletionSource<IOperation[]>();
			failSingle.SetException(allDead);
			failBroadcast.SetException(allDead);
		}
示例#20
0
        static int GetHResult(IOException exception, int defaultValue)
        {
            if (exception == null)
                throw new ArgumentNullException("exception");

            var field = exception.GetType().GetField("_HResult", BindingFlags.NonPublic | BindingFlags.Instance);
            if (field != null)
                return Convert.ToInt32(field.GetValue(exception));

            return defaultValue;
        }
        internal static int GetErrorCode(IOException ioe)
        {
#if !WindowsCE && !SILVERLIGHT && !NETFX_CORE
            var permission = new System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode);
            permission.Demand();

            return Marshal.GetHRForException(ioe) & 0xFFFF;
#else
            return 0;
#endif
        }
        // Convert HttpListenerExceptions to IOExceptions
        protected override bool TryWrapException(Exception ex, out Exception wrapped)
        {
            if (ex is HttpListenerException)
            {
                wrapped = new IOException(string.Empty, ex);
                return true;
            }

            wrapped = null;
            return false;
        }
示例#23
0
        static bool IsSharingViolation(
            IOException ioEx)
        {
            var field = ioEx
                .GetType().GetField("_HResult", BindingFlags.NonPublic | BindingFlags.Instance);
            if (field == null) return false;

            var hres = (int) field.GetValue(ioEx);
            Debug.WriteLine("Error '{0}' {1}", ioEx.Message, hres);

            return hres == HResultSharingViolation;
        }
示例#24
0
        // Stolen from UdonSharpUtils because it's in a different assembly, todo: move it somewhere more accessible
        static string ReadFileTextSync(string filePath, float timeoutSeconds)
        {
            bool sourceLoaded = false;

            string fileText = "";

            System.DateTime startTime = System.DateTime.Now;

            while (true)
            {
                System.IO.IOException exception = null;

                try
                {
                    fileText     = System.IO.File.ReadAllText(filePath);
                    sourceLoaded = true;
                }
                catch (System.IO.IOException e)
                {
                    exception = e;

                    if (e is System.IO.FileNotFoundException ||
                        e is System.IO.DirectoryNotFoundException)
                    {
                        throw e;
                    }
                }

                if (sourceLoaded)
                {
                    break;
                }
                else
                {
                    System.Threading.Thread.Sleep(20);
                }

                System.TimeSpan timeFromStart = System.DateTime.Now - startTime;

                if (timeFromStart.TotalSeconds > timeoutSeconds)
                {
                    UnityEngine.Debug.LogError($"Timeout when attempting to read file {filePath}");
                    if (exception != null)
                    {
                        throw exception;
                    }
                }
            }

            return(fileText);
        }
示例#25
0
        /// <summary>
        /// Gets the HRESULT of the specified exception.
        /// </summary>
        /// <param name="exception">The exception to test. May not be null.</param>
        /// <param name="defaultValue">The default value in case of an error.</param>
        /// <returns>The HRESULT value.</returns>
        private static int GetHResult(IOException exception, int defaultValue)
        {
            if (exception == null)
                throw new ArgumentNullException("exception");

            try
            {
                return (int)exception.GetType().GetProperty("HResult", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(exception, null);
            }
            catch
            {
                return defaultValue;
            }
        }
        public NativeFileReader(string file)
        {
            // FILE_SHARE_READ = 1
            hFileHandle = FileNativeMethods.CreateFile(file, GENERIC_READ, 1, 0, (uint)FileMode.Open, FILE_FLAG_NO_BUFFERING, 0);

            // Invalid handle value
            if (hFileHandle == (IntPtr)(-1))
            {
                IOException eb = new IOException("File can not open", null);
                throw eb;
            }

            m_FileSize = FileNativeMethods.SetFilePointer(hFileHandle, 0, 0, SeekOrigin.End);
            Position = 0;
        }
        public void DataRefreshError_IsRaisedOnUpstreamDataRefreshErrors()
        {
            Exception upstreamException = null;
            Subject.Upstream = Mocked<IPublicSuffixDataSource>().Object;
            Subject.DataRefreshError += (s, e) =>
            {
                upstreamException = e.Exception;
            };

            var mockError = new IOException();
            Mocked<IPublicSuffixDataSource>()
                .Raise(s => s.DataRefreshError += null, new PublicSuffixErrorEventArgs(mockError));

            upstreamException.Should().Be(mockError);
        }
        public String RegistrarExcepcion(Exception excepcion, String origen)
        {
            string mensaje = "";

            try
            {
                if (excepcion is System.ApplicationException)
                {
                    System.ApplicationException exc = (System.ApplicationException)excepcion;
                    mensaje = EscribirApplicationException(exc, origen);
                }
                else if (excepcion is System.IO.InvalidDataException)
                {
                    System.IO.InvalidDataException exc = (System.IO.InvalidDataException)excepcion;
                    mensaje = EscribirInvalidDataException(exc, origen);
                }
                else if (excepcion is System.IO.IOException)
                {
                    System.IO.IOException exc = (System.IO.IOException)excepcion;
                    mensaje = EscribirIOEx(exc, origen);
                }
                else if (excepcion is System.FormatException)
                {
                    System.FormatException exc = excepcion as System.FormatException;
                    mensaje = EscribirFormatException(exc, origen);
                }
                else if (excepcion is System.Data.SqlClient.SqlException)
                {
                    System.Data.SqlClient.SqlException exc = excepcion as System.Data.SqlClient.SqlException;
                    mensaje = EscribirSqlEx(exc, origen);
                }
                else if (excepcion is System.Data.OleDb.OleDbException)
                {
                    System.Data.OleDb.OleDbException exc = excepcion as System.Data.OleDb.OleDbException;
                    mensaje = EscribirOleDbEx(exc, origen);
                }
                else
                {
                    mensaje = EscribirGenericEx(excepcion, origen);
                }
            }
            catch (Exception ex)
            {
                mensaje = "Error interno de la Aplicación. Por favor informar a Sopórte Técnico.\n\n";
                mensaje = mensaje + EscribirLocalEx(ex, this.ToString() + ".RegistrarExcepcion");
            }
            return(mensaje);
        }
 private Exception ConvertIOException(IOException ioException)
 {
     if (ioException.InnerException is TimeoutException)
     {
         return new TimeoutException(ioException.InnerException.Message, ioException);
     }
     if (ioException.InnerException is CommunicationObjectAbortedException)
     {
         return new CommunicationObjectAbortedException(ioException.InnerException.Message, ioException);
     }
     if (ioException.InnerException is CommunicationException)
     {
         return new CommunicationException(ioException.InnerException.Message, ioException);
     }
     return new CommunicationException(System.ServiceModel.SR.GetString("StreamError"), ioException);
 }
示例#30
0
        public override void  Sync(System.String name)
        {
            EnsureOpen();
            System.IO.FileInfo fullFile = new System.IO.FileInfo(System.IO.Path.Combine(internalDirectory.FullName, name));
            bool success    = false;
            int  retryCount = 0;

            System.IO.IOException exc = null;
            while (!success && retryCount < 5)
            {
                retryCount++;
                System.IO.FileStream file = null;
                try
                {
                    try
                    {
                        file = new System.IO.FileStream(fullFile.FullName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite);
                        FileSupport.Sync(file);
                        success = true;
                    }
                    finally
                    {
                        if (file != null)
                        {
                            file.Close();
                        }
                    }
                }
                catch (System.IO.IOException ioe)
                {
                    if (exc == null)
                    {
                        exc = ioe;
                    }

                    // Pause 5 msec
                    System.Threading.Thread.Sleep(5);
                }
            }

            if (!success && exc != null)
            {
                // Throw original exception
                throw exc;
            }
        }
        public void EndInvoke_CompletedWithException()
        {
            object state = "STATE";
            Exception exception = new IOException();
            var target = new SftpDownloadAsyncResult(null, state);
            target.SetAsCompleted(exception, true);

            try
            {
                target.EndInvoke();
                Assert.Fail();
            }
            catch (IOException ex)
            {
                Assert.AreSame(exception, ex);
            }
        }
示例#32
0
        public STT.Task ListFailTest()
        {
            var mock  = new M.Mock <SIO.TextWriter>();
            var inner = new SIO.IOException();

            mock.Setup(stream => stream.WriteLineAsync(M.It.IsAny <string>())).Throws(inner);
            _mockEnv.Setup(env => env.StreamOut).Returns(mock.Object);
            var environment = _mockEnv.Object;
            var option      = new AO.List();

            return(Utility.FromOk(Operation(environment).List(option))
                   .ContinueWith(task => {
                Assert.Equal(STT.TaskStatus.Faulted, task.Status);
                var error = (ListOperationException)task.Exception.InnerExceptions.Single();
                Assert.Equal(option, error.Option);
                Assert.Equal(inner, ((S.AggregateException)error.InnerException).InnerExceptions.Single());
            }));
        }
示例#33
0
        public void Connect()
        {
            if (connection != null)
                return;
            TimeSpan sleepTime = new TimeSpan(0,0,0,0,100);
            TimeSpan maxAutoConnectRetryTime = new TimeSpan(0, 0, 0, 0, options.MaxAutoConnectRetryTime);
            DateTime start = DateTime.Now;

            while (true)
            {
                IOException lastError = null;
                IPEndPoint addr = hostAddress.HostAddress;
                try
                {
                    connection = new TimeOutSocket().Connect(addr, options.ConnectTimeout);
                    connection.NoDelay = (!options.UseNagle);
                    connection.SendTimeout = options.SendTimeout;
                    connection.ReceiveTimeout = options.ReceiveTimeout;
                    input = connection.GetStream();
                    output = connection.GetStream();
                    return;
                }
                catch(Exception e)
                {
                    lastError = new IOException("Couldn't connect to ["
                            + addr.ToString() + "] exception:" + e);
                    Close();
                }

                TimeSpan executeTime = DateTime.Now - start;
                if (executeTime >= maxAutoConnectRetryTime)
                    throw lastError;
                if (sleepTime + executeTime > maxAutoConnectRetryTime)
                    sleepTime = maxAutoConnectRetryTime - executeTime;
                try
                {
                    Thread.Sleep(sleepTime);
                }
                catch (Exception){}
                sleepTime = sleepTime + sleepTime;
            }
        }
        public void SetAsCompleted_Exception_CompletedSynchronously()
        {
            var downloadCompleted = new ManualResetEvent(false);
            object state = "STATE";
            Exception exception = new IOException();
            IAsyncResult callbackResult = null;
            var target = new SftpDownloadAsyncResult(asyncResult =>
                {
                    downloadCompleted.Set();
                    callbackResult = asyncResult;
                }, state);

            target.SetAsCompleted(exception, true);

            Assert.AreSame(target, callbackResult);
            Assert.IsFalse(target.IsDownloadCanceled);
            Assert.IsTrue(target.IsCompleted);
            Assert.IsTrue(target.CompletedSynchronously);
            Assert.IsTrue(downloadCompleted.WaitOne(TimeSpan.Zero));
        }
示例#35
0
 public override void Dispose()
 {
     Parent.OnIndexOutputClosed(this);
     // only close the file if it has not been closed yet
     if (IsOpen)
     {
         System.IO.IOException priorE = null;
         try
         {
             base.Dispose();
         }
         catch (System.IO.IOException ioe)
         {
             priorE = ioe;
         }
         finally
         {
             IsOpen = false;
             IOUtils.CloseWhileHandlingException(priorE, File);
         }
     }
 }
示例#36
0
        /// <summary>
        /// Copies the file <i>src</i> to <seealso cref="Directory"/> <i>to</i> under the new
        /// file name <i>dest</i>.
        /// <p>
        /// If you want to copy the entire source directory to the destination one, you
        /// can do so like this:
        ///
        /// <pre class="prettyprint">
        /// Directory to; // the directory to copy to
        /// for (String file : dir.listAll()) {
        ///   dir.copy(to, file, newFile, IOContext.DEFAULT); // newFile can be either file, or a new name
        /// }
        /// </pre>
        /// <p>
        /// <b>NOTE:</b> this method does not check whether <i>dest</i> exist and will
        /// overwrite it if it does.
        /// </summary>
        public virtual void Copy(Directory to, string src, string dest, IOContext context)
        {
            IndexOutput os  = null;
            IndexInput  @is = null;

            System.IO.IOException priorException = null;
            try
            {
                os  = to.CreateOutput(dest, context);
                @is = OpenInput(src, context);
                os.CopyBytes(@is, @is.Length());
            }
            catch (System.IO.IOException ioe)
            {
                priorException = ioe;
            }
            finally
            {
                bool success = false;
                try
                {
                    IOUtils.CloseWhileHandlingException(priorException, os, @is);
                    success = true;
                }
                finally
                {
                    if (!success)
                    {
                        try
                        {
                            to.DeleteFile(dest);
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
            }
        }
示例#37
0
		protected FiscalResponse(byte[] buffer)
		{
			var invalidPacketException = new IOException("Invalid packet received.");
			if (buffer.Length < 27)
				throw invalidPacketException;
			if (buffer[0] != 0x01)
				throw invalidPacketException;
			if (buffer[buffer.Length - 1] != 0x03)
				throw invalidPacketException;
			var indexOfSeparator = Array.IndexOf<byte>(buffer, 0x04);
			var indexOfPostamble = Array.IndexOf<byte>(buffer, 0x05);
			if (indexOfSeparator == -1 || indexOfPostamble == -1)
				throw invalidPacketException;
			if (indexOfPostamble - indexOfSeparator != 9)
				throw invalidPacketException;
			var dataBytes = buffer.Skip(10).Take(indexOfSeparator - 10).ToArray();
			if (dataBytes.Length < 2)
				throw invalidPacketException;
			if (dataBytes.First() != 0x30)
				ErrorCode = dataBytes.GetString();
			else
				data = dataBytes.Skip(2).Take(dataBytes.Length - 2).ToArray();
		}
示例#38
0
 public virtual void load()
 {
     try
     {
         fromText(RawParseUtils.decode(IO.ReadFully(getFile())));
     }
     catch (FileNotFoundException)
     {
         clear();
     }
     catch (DirectoryNotFoundException)
     {
         clear();
     }
     catch (IOException e)
     {
         var e2 = new IOException("Cannot read " + getFile(), e);
         throw e2;
     }
     catch (ConfigInvalidException e)
     {
         throw new ConfigInvalidException("Cannot read " + getFile(), e);
     }
 }
示例#39
0
        static private bool leerLista(List <string> alLista)
        {//http://spreadsheetlight.com/sample-code/
            System.IO.IOException res = null;
            SLDocument            sl  = null;

            try
            {
                sl = new SLDocument(@"..\lista.xlsx", "Hoja1");
                int    alNumero = 0;
                string alNombre;
                while (!string.IsNullOrWhiteSpace(alNombre = sl.GetCellValueAsString(++alNumero, 1)))
                {
                    alLista.Add(alNombre);
                }
                sl.CloseWithoutSaving();
            }
            catch (System.IO.IOException e)
            {
                res = e;
                Console.WriteLine("el archivo \"lista.xlsx\" no existe o se encuentra abierto");
                Console.ReadKey();
            }
            return(res == null);
        }
        public void FromException_ProducesAFaultedTask()
        {
            var ex = new IOException();

            var result = TaskMonad.TaskMonad.FromException<TestValue>(ex);

            Assert.IsNotNull(result);
            Assert.AreEqual(TaskStatus.Faulted, result.Status);
            Assert.IsNotNull(result.Exception);
            Assert.AreEqual(1, result.Exception.InnerExceptions.Count);
            Assert.AreSame(ex, result.Exception.InnerException);
        }
        public void CloneResult_ProducesAFaultedTaskFromAFaultedTask()
        {
            var ex = new IOException();

            var task = TaskMonad.TaskMonad.FromException<TestValue>(ex);

            var result = task.CloneResult();

            Assert.IsNotNull(result);
            Assert.AreEqual(TaskStatus.Faulted, result.Status);
            Assert.AreSame(ex, result.Exception.GetBaseException());
        }
示例#42
0
        private async Task DoReceive()
        {
            Exception error = null;

            try
            {
                var socketError = await ProcessReceives();

                var ex = new SocketException((int)socketError);
                if (ex.SocketErrorCode == SocketError.ConnectionReset)
                {
                    error = new ConnectionResetException(ex.Message, ex);
                    _trace.ConnectionReset(ConnectionId);
                }
                else if (ex.SocketErrorCode == SocketError.OperationAborted ||
                         ex.SocketErrorCode == SocketError.ConnectionAborted ||
                         ex.SocketErrorCode == SocketError.Interrupted ||
                         ex.SocketErrorCode == SocketError.InvalidArgument)
                {
                    if (!_aborted)
                    {
                        // Calling Dispose after ReceiveAsync can cause an "InvalidArgument" error on *nix.
                        error = new ConnectionAbortedException();
                        _trace.ConnectionError(ConnectionId, error);
                    }
                }
                else if (socketError != SocketError.Success)
                {
                    error = ex;
                    _trace.ConnectionError(ConnectionId, error);
                }
            }
            catch (SocketException ex) when(ex.SocketErrorCode == SocketError.ConnectionReset)
            {
                error = new ConnectionResetException(ex.Message, ex);
                _trace.ConnectionReset(ConnectionId);
            }
            catch (SocketException ex) when(ex.SocketErrorCode == SocketError.OperationAborted ||
                                            ex.SocketErrorCode == SocketError.ConnectionAborted ||
                                            ex.SocketErrorCode == SocketError.Interrupted ||
                                            ex.SocketErrorCode == SocketError.InvalidArgument)
            {
                if (!_aborted)
                {
                    // Calling Dispose after ReceiveAsync can cause an "InvalidArgument" error on *nix.
                    error = new ConnectionAbortedException();
                    _trace.ConnectionError(ConnectionId, error);
                }
            }
            catch (ObjectDisposedException)
            {
                if (!_aborted)
                {
                    error = new ConnectionAbortedException();
                    _trace.ConnectionError(ConnectionId, error);
                }
            }
            catch (IOException ex)
            {
                error = ex;
                _trace.ConnectionError(ConnectionId, error);
            }
            catch (Exception ex)
            {
                error = new IOException(ex.Message, ex);
                _trace.ConnectionError(ConnectionId, error);
            }
            finally
            {
                if (_aborted)
                {
                    error = error ?? new ConnectionAbortedException();
                }

                ReceiveError = error;
                Input.Complete();
            }
        }
示例#43
0
		internal virtual void Reject(IOException err)
		{
			SetResult(ReceiveCommand.Result.REJECTED_OTHER_REASON, MessageFormat.Format(JGitText
				.Get().lockError, err.Message));
		}
示例#44
0
        private void OnDataAvailable(IAsyncResult result)
        {
            var callback = (DataAvailableCallback)result.AsyncState;
            Exception readException = null;

            try
            {
                // complete read operation
                _readPos = 0;
                _dataCount = _stream.EndRead(result);

                if (_dataCount <= 0)
                    readException = new IOException("No data available");
            }
            catch (Exception ex)
            {
                // unable to read data, connection is broken?
                readException = ex;
            }

            // invoke client callback
            callback(readException, _dataAvailableState);
        }
示例#45
0
 public static void LogIOException(string caller, System.IO.IOException e)
 {
     LogError(caller + ": " + e.Message);
 }
示例#46
0
        // IO COMPLETION CALLBACK
        //
        // This callback is responsible for getting the complete protocol frame.
        // 1. it reads the header.
        // 2. it determines the frame size.
        // 3. loops while not all frame received or an error.
        //
        private void ReadFrameComplete(IAsyncResult transportResult)
        {
            do
            {
                if (!(transportResult.AsyncState is WorkerAsyncResult))
                {
                    if (GlobalLog.IsEnabled)
                    {
                        GlobalLog.AssertFormat("StreamFramer::ReadFrameComplete|The state expected to be WorkerAsyncResult, received:{0}.", transportResult.GetType().FullName);
                    }

                    Debug.Fail("StreamFramer::ReadFrameComplete|The state expected to be WorkerAsyncResult, received:" + transportResult.GetType().FullName + ".");
                }

                WorkerAsyncResult workerResult = (WorkerAsyncResult)transportResult.AsyncState;

                int bytesRead = _transportAPM.EndRead(transportResult);
                workerResult.Offset += bytesRead;

                if (!(workerResult.Offset <= workerResult.End))
                {
                    if (GlobalLog.IsEnabled)
                    {
                        GlobalLog.AssertFormat("StreamFramer::ReadFrameCallback|WRONG: offset - end = {0}", workerResult.Offset - workerResult.End);
                    }

                    Debug.Fail("StreamFramer::ReadFrameCallback|WRONG: offset - end = " + (workerResult.Offset - workerResult.End));
                }

                if (bytesRead <= 0)
                {
                    // (by design) This indicates the stream has receives EOF
                    // If we are in the middle of a Frame - fail, otherwise - produce EOF
                    object result = null;
                    if (!workerResult.HeaderDone && workerResult.Offset == 0)
                    {
                        result = (object)-1;
                    }
                    else
                    {
                        result = new System.IO.IOException(SR.net_frame_read_io);
                    }

                    workerResult.InvokeCallback(result);
                    return;
                }

                if (workerResult.Offset >= workerResult.End)
                {
                    if (!workerResult.HeaderDone)
                    {
                        workerResult.HeaderDone = true;
                        // This indicates the header has been read succesfully
                        _curReadHeader.CopyFrom(workerResult.Buffer, 0, _readVerifier);
                        int payloadSize = _curReadHeader.PayloadSize;
                        if (payloadSize < 0)
                        {
                            // Let's call user callback and he call us back and we will throw
                            workerResult.InvokeCallback(new System.IO.IOException(SR.Format(SR.net_frame_read_size)));
                        }

                        if (payloadSize == 0)
                        {
                            // report emtpy frame (NOT eof!) to the caller, he might be interested in
                            workerResult.InvokeCallback(0);
                            return;
                        }

                        if (payloadSize > _curReadHeader.MaxMessageSize)
                        {
                            throw new InvalidOperationException(SR.Format(SR.net_frame_size,
                                                                          _curReadHeader.MaxMessageSize.ToString(NumberFormatInfo.InvariantInfo),
                                                                          payloadSize.ToString(NumberFormatInfo.InvariantInfo)));
                        }

                        // Start reading the remaining frame data (note header does not count).
                        byte[] frame = new byte[payloadSize];
                        // Save the ref of the data block
                        workerResult.Buffer = frame;
                        workerResult.End    = frame.Length;
                        workerResult.Offset = 0;

                        // Transport.BeginRead below will pickup those changes.
                    }
                    else
                    {
                        workerResult.HeaderDone = false; // Reset for optional object reuse.
                        workerResult.InvokeCallback(workerResult.End);
                        return;
                    }
                }

                // This means we need more data to complete the data block.
                transportResult = _transportAPM.BeginRead(workerResult.Buffer, workerResult.Offset, workerResult.End - workerResult.Offset,
                                                          _readFrameCallback, workerResult);
            } while (transportResult.CompletedSynchronously);
        }
示例#47
0
        private async Task <Exception> DoReceive()
        {
            Exception error = null;

            try
            {
                var buffer    = new ArraySegment <byte>(new byte[MinAllocBufferSize]);
                var awaitable = _receiveAwaitable;
                awaitable.EventArgs.SetBuffer(buffer.Array, buffer.Offset, buffer.Count);
                while (true)
                {
                    if (!await _socket.ReceiveAsync(awaitable))
                    {
                        throw new SocketException((int)awaitable.EventArgs.SocketError);
                    }

                    var bytesReceived = awaitable.EventArgs.BytesTransferred;

                    if (bytesReceived == 0)
                    {
                        // FIN
                        _trace.ConnectionReadFin(ConnectionId);
                        break;
                    }

#if NETCOREAPP2_0
                    Received(buffer.Slice(buffer.Offset, bytesReceived));
#else
                    Received(new ArraySegment <byte>(buffer.Array, buffer.Offset, bytesReceived));
#endif
                }
            }
            catch (SocketException ex) when(ex.SocketErrorCode == SocketError.ConnectionReset)
            {
                error = new ConnectionResetException(ex.Message, ex);
                _trace.ConnectionReset(ConnectionId);
            }
            catch (SocketException ex) when(ex.SocketErrorCode == SocketError.OperationAborted ||
                                            ex.SocketErrorCode == SocketError.ConnectionAborted ||
                                            ex.SocketErrorCode == SocketError.Interrupted ||
                                            ex.SocketErrorCode == SocketError.InvalidArgument)
            {
                if (!_aborted)
                {
                    // Calling Dispose after ReceiveAsync can cause an "InvalidArgument" error on *nix.
                    error = new ConnectionAbortedException();
                    _trace.ConnectionError(ConnectionId, error);
                }
            }
            catch (ObjectDisposedException)
            {
                if (!_aborted)
                {
                    error = new ConnectionAbortedException();
                    _trace.ConnectionError(ConnectionId, error);
                }
            }
            catch (IOException ex)
            {
                error = ex;
                _trace.ConnectionError(ConnectionId, error);
            }
            catch (Exception ex)
            {
                error = new IOException(ex.Message, ex);
                _trace.ConnectionError(ConnectionId, error);
            }
            finally
            {
                if (_aborted)
                {
                    error = error ?? new ConnectionAbortedException();
                }
            }

            return(error);
        }
示例#48
0
            public System.Object Run(IndexCommit commit)
            {
                if (commit != null)
                {
                    if (directory != commit.Directory)
                    {
                        throw new System.IO.IOException("the specified commit does not match the specified Directory");
                    }
                    return(DoBody(commit.SegmentsFileName));
                }

                System.String segmentFileName   = null;
                long          lastGen           = -1;
                long          gen               = 0;
                int           genLookaheadCount = 0;

                System.IO.IOException exc = null;
                bool retry = false;

                int method = 0;

                // Loop until we succeed in calling doBody() without
                // hitting an IOException.  An IOException most likely
                // means a commit was in process and has finished, in
                // the time it took us to load the now-old infos files
                // (and segments files).  It's also possible it's a
                // true error (corrupt index).  To distinguish these,
                // on each retry we must see "forward progress" on
                // which generation we are trying to load.  If we
                // don't, then the original error is real and we throw
                // it.

                // We have three methods for determining the current
                // generation.  We try the first two in parallel, and
                // fall back to the third when necessary.

                while (true)
                {
                    if (0 == method)
                    {
                        // Method 1: list the directory and use the highest
                        // segments_N file.  This method works well as long
                        // as there is no stale caching on the directory
                        // contents (NOTE: NFS clients often have such stale
                        // caching):
                        System.String[] files = null;

                        long genA = -1;

                        files = directory.ListAll();

                        if (files != null)
                        {
                            genA = Lucene.Net.Index.SegmentInfos.GetCurrentSegmentGeneration(files);
                        }

                        Lucene.Net.Index.SegmentInfos.Message("directory listing genA=" + genA);

                        // Method 2: open segments.gen and read its
                        // contents.  Then we take the larger of the two
                        // gens.  This way, if either approach is hitting
                        // a stale cache (NFS) we have a better chance of
                        // getting the right generation.
                        long genB = -1;
                        for (int i = 0; i < Lucene.Net.Index.SegmentInfos.defaultGenFileRetryCount; i++)
                        {
                            IndexInput genInput = null;
                            try
                            {
                                genInput = directory.OpenInput(IndexFileNames.SEGMENTS_GEN);
                            }
                            catch (System.IO.FileNotFoundException e)
                            {
                                Lucene.Net.Index.SegmentInfos.Message("segments.gen open: FileNotFoundException " + e);
                                break;
                            }
                            catch (System.IO.IOException e)
                            {
                                Lucene.Net.Index.SegmentInfos.Message("segments.gen open: IOException " + e);
                            }

                            if (genInput != null)
                            {
                                try
                                {
                                    int version = genInput.ReadInt();
                                    if (version == Lucene.Net.Index.SegmentInfos.FORMAT_LOCKLESS)
                                    {
                                        long gen0 = genInput.ReadLong();
                                        long gen1 = genInput.ReadLong();
                                        Lucene.Net.Index.SegmentInfos.Message("fallback check: " + gen0 + "; " + gen1);
                                        if (gen0 == gen1)
                                        {
                                            // The file is consistent.
                                            genB = gen0;
                                            break;
                                        }
                                    }
                                }
                                catch (System.IO.IOException)
                                {
                                    // will retry
                                }
                                finally
                                {
                                    genInput.Close();
                                }
                            }

                            System.Threading.Thread.Sleep(new TimeSpan((System.Int64) 10000 * Lucene.Net.Index.SegmentInfos.defaultGenFileRetryPauseMsec));
                        }

                        Lucene.Net.Index.SegmentInfos.Message(IndexFileNames.SEGMENTS_GEN + " check: genB=" + genB);

                        // Pick the larger of the two gen's:
                        if (genA > genB)
                        {
                            gen = genA;
                        }
                        else
                        {
                            gen = genB;
                        }

                        if (gen == -1)
                        {
                            throw new System.IO.FileNotFoundException("no segments* file found in " + directory + ": files:" + string.Join(" ", files));
                        }
                    }

                    // Third method (fallback if first & second methods
                    // are not reliable): since both directory cache and
                    // file contents cache seem to be stale, just
                    // advance the generation.
                    if (1 == method || (0 == method && lastGen == gen && retry))
                    {
                        method = 1;

                        if (genLookaheadCount < Lucene.Net.Index.SegmentInfos.defaultGenLookaheadCount)
                        {
                            gen++;
                            genLookaheadCount++;
                            Lucene.Net.Index.SegmentInfos.Message("look ahead increment gen to " + gen);
                        }
                    }

                    if (lastGen == gen)
                    {
                        // This means we're about to try the same
                        // segments_N last tried.  This is allowed,
                        // exactly once, because writer could have been in
                        // the process of writing segments_N last time.

                        if (retry)
                        {
                            // OK, we've tried the same segments_N file
                            // twice in a row, so this must be a real
                            // error.  We throw the original exception we
                            // got.
                            throw exc;
                        }

                        retry = true;
                    }
                    else if (0 == method)
                    {
                        // Segment file has advanced since our last loop, so
                        // reset retry:
                        retry = false;
                    }

                    lastGen = gen;

                    segmentFileName = IndexFileNames.FileNameFromGeneration(IndexFileNames.SEGMENTS, "", gen);

                    try
                    {
                        System.Object v = DoBody(segmentFileName);
                        Lucene.Net.Index.SegmentInfos.Message("success on " + segmentFileName);

                        return(v);
                    }
                    catch (System.IO.IOException err)
                    {
                        // Save the original root cause:
                        if (exc == null)
                        {
                            exc = err;
                        }

                        Lucene.Net.Index.SegmentInfos.Message("primary Exception on '" + segmentFileName + "': " + err + "'; will retry: retry=" + retry + "; gen = " + gen);

                        if (!retry && gen > 1)
                        {
                            // This is our first time trying this segments
                            // file (because retry is false), and, there is
                            // possibly a segments_(N-1) (because gen > 1).
                            // So, check if the segments_(N-1) exists and
                            // try it if so:
                            System.String prevSegmentFileName = IndexFileNames.FileNameFromGeneration(IndexFileNames.SEGMENTS, "", gen - 1);

                            bool prevExists;
                            prevExists = directory.FileExists(prevSegmentFileName);

                            if (prevExists)
                            {
                                Lucene.Net.Index.SegmentInfos.Message("fallback to prior segment file '" + prevSegmentFileName + "'");
                                try
                                {
                                    System.Object v = DoBody(prevSegmentFileName);
                                    if (exc != null)
                                    {
                                        Lucene.Net.Index.SegmentInfos.Message("success on fallback " + prevSegmentFileName);
                                    }
                                    return(v);
                                }
                                catch (System.IO.IOException err2)
                                {
                                    Lucene.Net.Index.SegmentInfos.Message("secondary Exception on '" + prevSegmentFileName + "': " + err2 + "'; will retry");
                                }
                            }
                        }
                    }
                }
            }
        private static bool FileIsLocked(System.IO.IOException ioException)
        {
            var errorCode = (uint)Marshal.GetHRForException(ioException);

            return(errorCode == HRFileLocked || errorCode == HRPortionOfFileLocked);
        }