예제 #1
0
        public void Dispose()
        {
            if (Directory.Exists(_backupPath))
            {
                CopyOverDirectory(_backupPath, _basePath);

                // Directory.Delete sometimes fails with error that the directory is not empty.
                // This is a known problem where the actual Delete call is not 100% synchronous
                // the OS reports a success but the file/folder is not fully removed yet.
                // So implement a simple retry with a short timeout.
                IOException exception = null;
                for (int retryCount = 5; retryCount > 0; retryCount--)
                {
                    try
                    {
                        Directory.Delete(_backupPath, recursive: true);
                        if (!Directory.Exists(_backupPath))
                        {
                            return;
                        }
                    }
                    catch (IOException ex)
                    {
                        exception = ex;
                    }

                    System.Threading.Thread.Sleep(200);
                }

                throw new Exception(
                          $"Failed to delete the backup folder {_backupPath} even after retries.\r\n"
                          + (exception == null ? "" : exception.ToString()));
            }
        }
        private void salvaArquivo()
        {
            string       caminho = @"../information.txt";
            StreamWriter stream  = new StreamWriter(caminho);

            try
            {
                if (!(File.Exists(caminho)))
                {
                    File.CreateText(caminho);
                }
                stream.WriteLine(tbRWArquivo.Text);
                MessageBox.Show(
                    "Arquivo salvo em \"./wfaBuscaArquivo/wfaBuscaArquivo/bin/information.txt\"",
                    "Gravado com sucesso!",
                    MessageBoxButtons.OK);
            }
            catch (IOException IOException)
            {
                MessageBox.Show(
                    IOException.ToString(),
                    "Erro Inesperado",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
            finally
            {
                stream.Close();
            }
        }
예제 #3
0
 /// <summary>
 /// Check the exception was about cross-directory renames
 /// -if not, rethrow it.
 /// </summary>
 /// <param name="e">exception raised</param>
 /// <exception cref="System.IO.IOException"/>
 private void VerifyUnsupportedDirRenameException(IOException e)
 {
     if (!e.ToString().Contains(FTPFileSystem.ESameDirectoryOnly))
     {
         throw e;
     }
 }
예제 #4
0
 private void LoadOptionsFromFile()
 {
     if (File.Exists(@"data/options.ini"))
     {
         try
         {
             string[] optionsFile = File.ReadAllLines(@"data/options.ini");
             if (optionsFile[0] == "language polish" || optionsFile[0] == "language Polish")
             {
                 ProgramOptions.ActualLanguage = ProgramOptions.Languages.Polish;
             }
             else
             {
                 ProgramOptions.ActualLanguage = ProgramOptions.Languages.English;
             }
             ProgramOptions.ScrollToBottom    = Convert.ToBoolean(optionsFile[1].Substring(9));
             ProgramOptions.IsRememberEnabled = Convert.ToBoolean(optionsFile[2].Substring(9));
             if (ProgramOptions.IsRememberEnabled == true)
             {
                 loginBox.Text      = optionsFile[3].Substring(6);
                 loginLabel.Content = "";
             }
         }
         catch (Exception IOException)
         {
             System.Diagnostics.Debug.WriteLine(IOException.ToString() + "\nReplacing bad file with default one");
             string[] DefaultOptions = new string[] { "language english", "tobottom true", "remember false", "" };
             File.WriteAllLines(@"data/options.ini", DefaultOptions);
         }
     }
 }
예제 #5
0
        /// <exception cref="System.Exception"/>
        private IOException VerifyExceptionClass(IOException e, Type expectedClass)
        {
            NUnit.Framework.Assert.IsNotNull("Null Exception", e);
            IOException wrapped = NetUtils.WrapException("desthost", DestPort, "localhost", LocalPort
                                                         , e);

            Log.Info(wrapped.ToString(), wrapped);
            if (!(wrapped.GetType().Equals(expectedClass)))
            {
                throw Extensions.InitCause(new AssertionFailedError("Wrong exception class; expected "
                                                                    + expectedClass + " got " + wrapped.GetType() + ": " + wrapped), wrapped);
            }
            return(wrapped);
        }
예제 #6
0
        internal static SQLException convertException(IOException io, int sqlCode, string sqlState)
        {
            SQLException sql = null;

            if (io is MessageException)
            {
                MessageException me       = (MessageException)io;
                Message[]        messages = me.Messages;
                string           reason   = messages[0].ToString();
                sql = new SQLException(reason, sqlState, sqlCode);
                sql.initCause(io);
            }
            else
            {
                string reason = io.ToString();
                sql = new SQLException(reason, sqlState, sqlCode);
                sql.initCause(io);
            }

            return(sql);
        }
        public async Task Handle()
        {
            if (FastcgiServerAsync.Debug)
            {
                await Console.Out.WriteLineAsync(String.Format("Handling Client"));
            }
            var ClientStream = Client.GetStream();

            try
            {
                while (Client.Connected)
                {
                    FastcgiPacket Packet;
                    try
                    {
                        Packet = await new FastcgiPacket().ReadFromAsync(ClientStream);
                    }
                    catch (IOException)
                    {
                        Console.Error.WriteLineAsync("Error Reading");
                        break;
                    }
                    FastcgiServerClientRequestHandlerAsync Handler;
                    if (!this.Handlers.TryGetValue(Packet.RequestId, out Handler))
                    {
                        Handler = this.Handlers[Packet.RequestId] = new FastcgiServerClientRequestHandlerAsync(this, ClientStream, Packet.RequestId);
                    }
                    await Handler.HandlePacket(Client, Packet);
                }
            }
            catch (IOException IOException)
            {
                if (FastcgiServerAsync.Debug)
                {
                    Console.Error.WriteAsync(IOException.ToString());
                }
            }
        }
예제 #8
0
    public async Task TruncatesErrorDetailsIfTheyAreTooLong()
    {
        _simpleRetryStrategySettings.ErrorDetailsHeaderMaxLength = 300;

        var message              = NewMessage("known-id");
        var exception            = new IOException(new string('*', 1024));
        var originalErrorDetails = exception.ToString();

        await WithContext(async context =>
        {
            await _handler.HandlePoisonMessage(message, context, exception);
        });

        var failedMessage         = _network.GetNextOrNull("error");
        var truncatedErrorDetails = failedMessage.Headers[Headers.ErrorDetails];

        Console.WriteLine($@"

-------------------------------------------------------------




The error details originally looked like this:

{originalErrorDetails}

(length: {originalErrorDetails.Length})

The forwarded message contained these error details:

{truncatedErrorDetails}

(length: {truncatedErrorDetails.Length})
");

        Assert.That(truncatedErrorDetails.Length, Is.LessThanOrEqualTo(_simpleRetryStrategySettings.ErrorDetailsHeaderMaxLength));
    }
 private void analyzeInput(string pathname)
 {
     if (File.Exists(pathname))
     {
         StreamReader stream = new StreamReader(pathname);
         try
         {
             tbRWArquivo.Text  = obtemInfoArquivo(pathname);
             tbRWArquivo.Text += stream.ReadToEnd();
         }
         catch (IOException IOException)
         {
             MessageBox.Show(
                 IOException.ToString(),
                 "Erro Inesperado",
                 MessageBoxButtons.OK,
                 MessageBoxIcon.Error);
         }
         finally
         {
             stream.Close();
         }
     }
     else if (Directory.Exists(pathname))
     {
         tbRWArquivo.Text  = obtemInfoArquivo(pathname);
         tbRWArquivo.Text += listarDiretorios(pathname);
     }
     else
     {
         MessageBox.Show(
             "Caminho não encontrado",
             "Erro de Arquivo",
             MessageBoxButtons.OK,
             MessageBoxIcon.Error);
     }
 }
 public void OnLoadError(IOException ex)
 {
     OnMediaFailed(new MediaFailedEventArgs(ex.ToString(), ex));
 }
예제 #11
0
 public override String ToString()
 {
     return(String.Format("{0:s}I/O error reading from source.\n{1:s}", base.ToString(), cause.ToString()));
 }
예제 #12
0
        private void adduserbutton_Click(object sender, EventArgs e)
        {
            //Check if name already exists.

            bool Err_flag = false;

            if (File.Exists("Users.dat"))
            {
                FileStream   fs = new FileStream("Users.dat", FileMode.Open, FileAccess.Read);
                StreamReader sr = new StreamReader(fs);

                string record = sr.ReadLine();
                while (record != null)
                {
                    if (record.Split('|')[0].ToLower() == Namefield.Text.ToLower())
                    {
                        Errorlabel.Text = "Sorry, Name already exists.";
                        Err_flag        = true;
                        break;
                    }
                    record = sr.ReadLine();
                }
                sr.Close();
                fs.Close();
            }
            //End of name check.

            //Password matching check.
            if (pass1.Text != pass2.Text)
            {
                Err_flag         = true;
                Errorlabel.Text += "\nError: Passwords Don't match, Perhaps type slower?";
            }
            //End password matching check


            //Gender specification
            string gender;

            if (this.female == true)
            {
                gender = "Female";
            }
            else
            {
                gender = "Male";
            }
            //End Gender specification

            //If no errors, create a new user object and call the "create" method to create a record and write it to users.dat
            if (Err_flag == false)
            {
                user newuser = new user();
                if (!newuser.create(Namefield.Text, pass1.Text, gender))
                {
                    IOException err = new IOException();
                    MetroFramework.MetroMessageBox.Show(this, "Error" + err.ToString(), "Error", MessageBoxButtons.OK);
                }
                else
                {
                    MetroFramework.MetroMessageBox.Show(this, "User Created.\nYou may now login with your new credentials.", "Success!", MessageBoxButtons.OK);
                    this.Hide();
                    LoginForm LF = new LoginForm();
                    LF.Show();
                }
            }
        }
        public async void HandleErrorAsync_ExceptionThatShouldBeCatchedANDLastAttempt_MessageShouldBeSentToAppropriateDeadLetterQueue(bool explicitAcknowledgments,
                                                                                                                                      bool storedeadletter)
        {
            //prepare
            MessageProperties messageProperties = new MessageProperties();

            messageProperties.Headers = new Dictionary <string, object>();
            messageProperties.Headers["retrycount"] = _maxRetry;

            BookingCreated bookingCreated = new BookingCreated {
                BookingName = "test"
            };
            string bookingCreatedEventType = "bookingCreatedEventType";
            IntegrationEvent <BookingCreated> integrationEvent = new IntegrationEvent <BookingCreated>(bookingCreated, bookingCreatedEventType);
            var       message   = JsonConvert.SerializeObject(integrationEvent);
            var       body      = Encoding.UTF8.GetBytes(message);
            Exception exception = new IOException("IOException");

            ExecutionHandlingStrategy executionHandlingStrategy = new ExecutionHandlingStrategy(_subscriberName, _easyNetQPublisher,
                                                                                                _maxRetry, _modelNamingConventionController.Object, explicitAcknowledgments, _publisher.Object, storedeadletter);

            _mockBus.Setup(x => x.ExchangeDeclareAsync(_exchangeName, ExchangeType.Topic,
                                                       false, true, false, false, null, false))
            .Returns((string exchangename, string exchanegType,
                      bool passive, bool durable, bool autoDelete, bool internalflag,
                      string alternateExchange, bool delayed) =>
                     { return(Task.FromResult(_mockExchange.Object)); });


            _modelNamingConventionController.Setup(x => x.GetDeadLetterQueueMessageEventType(bookingCreatedEventType))
            .Returns((string eventType) => string.Concat("deadletter.", eventType));

            _modelNamingConventionController.Setup(x => x.GetDeadLetterQueueRoutingKey(_subscriberName))
            .Returns((string subscriberName) => string.Concat("deadletter.", subscriberName));

            //Main flow
            string            actualRouting    = string.Empty;
            MessageProperties actualProperties = null;

            byte[]    actualMsg      = null;
            IExchange actualExchange = null;

            _mockBus.Setup(x => x.PublishAsync(It.IsAny <IExchange>(), It.IsAny <string>(), false, It.IsAny <MessageProperties>(), It.IsAny <byte[]>()))
            .Returns((IExchange exchange, string routing, bool mandatory,
                      MessageProperties properties, byte[] msg) =>
                     { return(Task.FromResult(true)); })
            .Callback <IExchange, string, bool, MessageProperties, byte[]>(
                (exchange, routing, mandatory, properties, msg) =>
            {
                actualExchange   = exchange;
                actualRouting    = routing;
                actualProperties = properties;
                actualMsg        = msg;
            });
            //END Main flow

            //Tracking flow
            IntegrationEvent <DeadLetterEventDescriptor <JObject> > actualTrackingMessage = null;
            string actualTrackingMessageRouting = string.Empty;
            bool   actualPersistantMode         = false;

            _publisher.Setup(x => x.PublishEventAsync(It.IsAny <IntegrationEvent <DeadLetterEventDescriptor <JObject> > >(), It.IsAny <string>(), true))
            .Returns(Task.FromResult(true))
            .Callback <IntegrationEvent <DeadLetterEventDescriptor <JObject> >, string, bool>(
                (trackingMessage, routing, persistantMode) =>
            {
                actualTrackingMessage        = trackingMessage;
                actualTrackingMessageRouting = routing;
                actualPersistantMode         = persistantMode;
            });

            //END Tracking flow


            //act
            Mock <ISubscription>    mockedSubscription      = new Mock <ISubscription>();
            MessageExecutionContext messageExecutionContext =
                new MessageExecutionContext(body, messageProperties, null)
            {
                Exception         = exception,
                SerializedMessage = message,
                Subscription      = mockedSubscription.Object,
                IntergrationEventParsingResult = null,
                DeadLetterIntegrationEvent     = null
            };

            await executionHandlingStrategy.HandleErrorAsync(messageExecutionContext);

            //check
            var expectedDeadLetterEventDescriptor =
                new DeadLetterEventDescriptor <JObject>
            {
                CountOfAttempts  = _maxRetry,
                LastAttemptError = exception.ToString(),
                Original         = JsonConvert.DeserializeObject <IntegrationEvent <JObject> >(message)
            };

            var expectedDeadletterqueueevent = new IntegrationEvent <DeadLetterEventDescriptor <JObject> >
            {
                CorrelationId = integrationEvent.CorrelationId,
                EventType     = string.Concat("deadletter.", bookingCreatedEventType),
                Content       = expectedDeadLetterEventDescriptor
            };

            //Check publishing dead letter message
            if (storedeadletter)
            {
                var actuaDeadLetterQueuelSerializedMessage = Encoding.UTF8.GetString(actualMsg);
                IntegrationEvent <DeadLetterEventDescriptor <JObject> > actualDeadLetterQueueIntegrationEvent =
                    JsonConvert.DeserializeObject <IntegrationEvent <DeadLetterEventDescriptor <JObject> > >(actuaDeadLetterQueuelSerializedMessage);


                actualDeadLetterQueueIntegrationEvent.CorrelationId.Should().Be(expectedDeadletterqueueevent.CorrelationId);
                actualDeadLetterQueueIntegrationEvent.Content.ShouldBeEquivalentTo(expectedDeadletterqueueevent.Content);
                actualDeadLetterQueueIntegrationEvent.EventType.Should()
                .Be(expectedDeadletterqueueevent.EventType);

                actualRouting.Should().Be(string.Concat("deadletter.", _subscriberName));
                actualExchange.Should().Be(_mockExchange.Object);
                actualProperties.DeliveryMode.Should().Be(2);//persistant delivery mode
            }
            else
            {
                _mockBus.Verify(v => v.PublishAsync(It.IsAny <IExchange>(), It.IsAny <string>(), false, It.IsAny <MessageProperties>(), It.IsAny <byte[]>()), Times.Never);
            }

            //Check Subsciption notification
            mockedSubscription.Verify(s => s.NotifyAboutDeadLetterAsync(messageExecutionContext.SerializedMessage, messageExecutionContext.Exception), Times.Once);
            mockedSubscription.Verify(s => s.InvokeAsync(It.IsAny <string>()), Times.Never);

            //Check Tracking flow
            if (explicitAcknowledgments == false)
            {
                //check, that No deadletter message for tracking is sent.
                _publisher.Verify(v => v.PublishEventAsync(It.IsAny <IntegrationEvent <DeadLetterEventDescriptor <JObject> > >(), It.IsAny <string>(), It.IsAny <bool>()), Times.Never);
            }
            else
            {
                //check, that deadltter message for tracking is equal to the one sent to the deadletter queue. Routing key must be the same
                _publisher.Verify(v => v.PublishEventAsync(It.IsAny <IntegrationEvent <DeadLetterEventDescriptor <JObject> > >(), It.IsAny <string>(), It.IsAny <bool>()), Times.Once);

                actualTrackingMessageRouting.Should().Be(string.Concat("deadletter.", _subscriberName));
                actualPersistantMode.Should().BeTrue();
                actualTrackingMessage.CorrelationId.Should().Be(expectedDeadletterqueueevent.CorrelationId);
                actualTrackingMessage.Content.ShouldBeEquivalentTo(expectedDeadletterqueueevent.Content);
                actualTrackingMessage.EventType.Should()
                .Be(expectedDeadletterqueueevent.EventType);
            }
        }