public void TestFixtureSetup()
 {
     _connectionId = new ConnectionId(new ServerId(new ClusterId(1), new DnsEndPoint("localhost", 27017)), 2);
     _innerException = new Exception("inner");
     _writeConcernError = new WriteConcernError(1, "writeConcernError", new BsonDocument("details", "writeConcernError"));
     _writeError = new WriteError(ServerErrorCategory.Uncategorized, 1, "writeError", new BsonDocument("details", "writeError"));
 }
 public void TestFixtureSetup()
 {
     _connectionId      = new ConnectionId(new ServerId(new ClusterId(1), new DnsEndPoint("localhost", 27017)), 2);
     _innerException    = new Exception("inner");
     _writeConcernError = new WriteConcernError(1, "writeConcernError", new BsonDocument("details", "writeConcernError"));
     _writeError        = new WriteError(1, "writeError", new BsonDocument("details", "writeError"));
 }
 public void OneTimeSetUp()
 {
     _connectionId      = new ConnectionId(new ServerId(new ClusterId(1), new DnsEndPoint("localhost", 27017)), 2);
     _innerException    = new Exception("inner");
     _writeConcernError = new WriteConcernError(1, "writeConcernError", new BsonDocument("details", "writeConcernError"));
     _writeError        = new WriteError(ServerErrorCategory.Uncategorized, 1, "writeError", new BsonDocument("details", "writeError"));
 }
 public bool OneTimeSetup()
 {
     __connectionId      = new ConnectionId(new ServerId(new ClusterId(1), new DnsEndPoint("localhost", 27017)), 2);
     __innerException    = new Exception("inner");
     __writeConcernError = new WriteConcernError(1, null, "writeConcernError", new BsonDocument("details", "writeConcernError"), new[] { "RetryableWriteError" });
     __writeError        = new WriteError(ServerErrorCategory.Uncategorized, 1, "writeError", new BsonDocument("details", "writeError"));
     return(true);
 }
Exemplo n.º 5
0
        private void Connect(TcpClient client)
        {
            connection = ConnectionFactory.GetConnection(client);

            connection.Open();
            connection.Received   += message => ResponseReceived(message);
            connection.ReadError  += exception => ReadError?.Invoke(exception);
            connection.WriteError += exception => WriteError?.Invoke(exception);
        }
Exemplo n.º 6
0
 private void writeCallback(IAsyncResult ar)
 {
     try
     {
         netStream.EndWrite(ar);
         WriteCompleted?.Invoke(this, new NetworkMessageWriterWriteCompletedEventArgs(ar.AsyncState as NetworkMessage, TcpClient));
     }
     catch (Exception ex)
     {
         WriteError?.Invoke(this, new NetworkMessageWriterWriteErrorEventArgs(ar.AsyncState as NetworkMessage, TcpClient, ex));
     }
 }
        public void ToString_should_return_expected_result(
            ServerErrorCategory category,
            int code,
            string message,
            string detailsJson,
            string expectedResult)
        {
            var details    = detailsJson == null ? null : BsonDocument.Parse(detailsJson);
            var writeError = new WriteError(category, code, message, details);

            var result = writeError.ToString();

            result.Should().Be(expectedResult);
        }
Exemplo n.º 8
0
 public static IConnectionConfiguration CopyWith(
     this IConnectionConfiguration configuration,
     IRetry connectionRetry                    = null,
     IVersionSupport versionSupport            = null,
     TimeSpan?requestTimeout                   = null,
     int?readBufferSize                        = null,
     int?writeBufferSize                       = null,
     bool?isTcpKeepalive                       = null,
     IEnumerable <IMembershipEncoder> encoders = null,
     ISslConfiguration sslConfiguration        = null,
     ConnectError onDisconnected               = null,
     Connecting onConnecting                   = null,
     Connecting onConnected                    = null,
     Writing onWriting            = null,
     StartingBytes onWritingBytes = null,
     FinishedBytes onWroteBytes   = null,
     WriteSuccess onWritten       = null,
     WriteError onWriteFailed     = null,
     Reading onReading            = null,
     StartingBytes onReadingBytes = null,
     FinishedBytes onReadBytes    = null,
     ReadSuccess onRead           = null,
     ReadError onReadFailed       = null,
     ProduceRequestMessages onProduceRequestMessages = null)
 {
     return(new ConnectionConfiguration(
                connectionRetry ?? configuration.ConnectionRetry,
                versionSupport ?? configuration.VersionSupport,
                requestTimeout ?? configuration.RequestTimeout,
                readBufferSize ?? configuration.ReadBufferSize,
                writeBufferSize ?? configuration.WriteBufferSize,
                isTcpKeepalive ?? configuration.IsTcpKeepalive,
                encoders ?? configuration.Encoders.Values,
                sslConfiguration ?? configuration.SslConfiguration,
                onDisconnected ?? configuration.OnDisconnected,
                onConnecting ?? configuration.OnConnecting,
                onConnected ?? configuration.OnConnected,
                onWriting ?? configuration.OnWriting,
                onWritingBytes ?? configuration.OnWritingBytes,
                onWroteBytes ?? configuration.OnWroteBytes,
                onWritten ?? configuration.OnWritten,
                onWriteFailed ?? configuration.OnWriteFailed,
                onReading ?? configuration.OnReading,
                onReadingBytes ?? configuration.OnReadingBytes,
                onReadBytes ?? configuration.OnReadBytes,
                onRead ?? configuration.OnRead,
                onReadFailed ?? configuration.OnReadFailed,
                onProduceRequestMessages ?? configuration.OnProduceRequestMessages));
 }
        public void ShouldReturnFalseIfPassedMongoWriteExceptionWithWriteErrorAsNull()
        {
            // Arrange
            var connectionId = new ConnectionId(new ServerId(new ClusterId(1), new DnsEndPoint("localhost", 27017)), 2);
            WriteError writeError = null;
            WriteConcernError writeConcernError = null;
            Exception innerException = new InvalidOperationException();
            var exception = new MongoWriteException(connectionId, writeError, writeConcernError, innerException);

            // Act
            var result = exception.IsUniqueViolation();

            // Assert
            result.Should().BeFalse();
        }
Exemplo n.º 10
0
        public void WriteAsync(NetworkMessage netMessage)
        {
            try
            {
                TcpClient.SendBufferSize = NetworkMessage.MAX_DATA_SIZE_IN_BYTES;
                byte[] buffer = new NetworkMessageFormatter <NetworkMessage>().Serialize(netMessage);

                netStream = TcpClient.GetStream();
                netStream.BeginWrite(buffer, 0, buffer.Length, writeCallback, netMessage);
            }
            catch (Exception ex)
            {
                WriteError?.Invoke(this, new NetworkMessageWriterWriteErrorEventArgs(netMessage, TcpClient, ex));
            }
        }
Exemplo n.º 11
0
 /// <summary>
 /// Configuration for the tcp connection.
 /// </summary>
 /// <param name="connectionRetry">Retry details for (re)establishing the connection.</param>
 /// <param name="versionSupport">Support for different protocol versions for Kakfa requests and responses.</param>
 /// <param name="requestTimeout">The maximum time to wait for requests.</param>
 /// <param name="readBufferSize">The buffer size to use for the socket, when receiving bytes.</param>
 /// <param name="writeBufferSize">The buffer size to use for the socket, when sending bytes.</param>
 /// <param name="isTcpKeepalive">TCP keepalive option.</param>
 /// <param name="encoders">Custom Encoding support for different protocol types</param>
 /// <param name="sslConfiguration">Configuration for SSL encrypted communication</param>
 /// <param name="onDisconnected">Triggered when the tcp socket is disconnected.</param>
 /// <param name="onConnecting">Triggered when the tcp socket is connecting.</param>
 /// <param name="onConnected">Triggered after the tcp socket is successfully connected.</param>
 /// <param name="onWriting">Triggered when writing to the tcp stream.</param>
 /// <param name="onWritingBytes">Triggered when writing a chunk of bytes to the tcp stream.</param>
 /// <param name="onWroteBytes">Triggered after successfully writing a chunk of bytes to the tcp stream.</param>
 /// <param name="onWritten">Triggered after having successfully written to the tcp stream.</param>
 /// <param name="onWriteFailed">Triggered after failing to write to the tcp stream.</param>
 /// <param name="onReading">Triggered when starting to read a message's bytes from the tcp stream.</param>
 /// <param name="onReadingBytes">Triggered when reading a chunk of bytes from the tcp stream.</param>
 /// <param name="onReadBytes">Triggered after successfully reading a chunk of bytes from the tcp stream.</param>
 /// <param name="onRead">Triggered after having successfully read a message's bytes from the tcp stream.</param>
 /// <param name="onReadFailed">Triggered after failing to read from the tcp stream.</param>
 /// <param name="onProduceRequestMessages">Triggered when encoding ProduceRequest messages.</param>
 public ConnectionConfiguration(
     IRetry connectionRetry                    = null,
     IVersionSupport versionSupport            = null,
     TimeSpan?requestTimeout                   = null,
     int?readBufferSize                        = null,
     int?writeBufferSize                       = null,
     bool?isTcpKeepalive                       = null,
     IEnumerable <IMembershipEncoder> encoders = null,
     ISslConfiguration sslConfiguration        = null,
     ConnectError onDisconnected               = null,
     Connecting onConnecting                   = null,
     Connecting onConnected                    = null,
     Writing onWriting            = null,
     StartingBytes onWritingBytes = null,
     FinishedBytes onWroteBytes   = null,
     WriteSuccess onWritten       = null,
     WriteError onWriteFailed     = null,
     Reading onReading            = null,
     StartingBytes onReadingBytes = null,
     FinishedBytes onReadBytes    = null,
     ReadSuccess onRead           = null,
     ReadError onReadFailed       = null,
     ProduceRequestMessages onProduceRequestMessages = null
     )
 {
     ConnectionRetry          = connectionRetry ?? Defaults.ConnectionRetry();
     VersionSupport           = versionSupport ?? Connections.VersionSupport.Kafka10;
     RequestTimeout           = requestTimeout ?? TimeSpan.FromSeconds(Defaults.RequestTimeoutSeconds);
     ReadBufferSize           = readBufferSize.GetValueOrDefault(Defaults.BufferSize);
     WriteBufferSize          = writeBufferSize.GetValueOrDefault(Defaults.BufferSize);
     IsTcpKeepalive           = isTcpKeepalive ?? Defaults.IsTcpKeepalive;
     Encoders                 = Defaults.Encoders(encoders);
     SslConfiguration         = sslConfiguration;
     OnDisconnected           = onDisconnected;
     OnConnecting             = onConnecting;
     OnConnected              = onConnected;
     OnWriting                = onWriting;
     OnWritingBytes           = onWritingBytes;
     OnWroteBytes             = onWroteBytes;
     OnWritten                = onWritten;
     OnWriteFailed            = onWriteFailed;
     OnReading                = onReading;
     OnReadingBytes           = onReadingBytes;
     OnReadBytes              = onReadBytes;
     OnRead                   = onRead;
     OnReadFailed             = onReadFailed;
     OnProduceRequestMessages = onProduceRequestMessages;
 }
Exemplo n.º 12
0
        private void ListenThread()
        {
            listener.Start();

            while (running)
            {
                TcpClient        client           = listener.AcceptTcpClient();
                ClientConnection clientConnection = new ClientConnection(ConnectionFactory.GetConnection(client), new Client(false));

                clientConnection.Connection.Received   += message => MessageReceived(message, clientConnection);
                clientConnection.Connection.ReadError  += exception => ReadError?.Invoke(exception, clientConnection.Connection, clientConnection.Client);
                clientConnection.Connection.WriteError += exception => WriteError?.Invoke(exception, clientConnection.Connection, clientConnection.Client);
                clientConnection.Connection.Open();

                connections.Add(clientConnection);
            }
        }
Exemplo n.º 13
0
        public void constructor_should_initialize_subject()
        {
            var category = ServerErrorCategory.Uncategorized;
            var code     = 1;
            var message  = "Document failed validation";
            var details  = new BsonDocument
            {
                { "failingDocumentId", new ObjectId() },
                { "details", new BsonDocument() },
                { "reason", "reason" }
            };

            var subject = new WriteError(category, code, message, details);

            subject.Category.Should().Be(category);
            subject.Message.Should().Be(message);
            subject.Details.Should().Be(details);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Configuration for the tcp connection.
        /// </summary>
        /// <param name="connectionRetry">Retry details for (re)establishing the connection.</param>
        /// <param name="versionSupport">Support for different protocol versions for Kakfa requests and responses.</param>
        /// <param name="requestTimeout">The maximum time to wait for requests.</param>
        /// <param name="encoders">Custom Encoding support for different protocol types</param>
        /// <param name="sslConfiguration">Configuration for SSL encrypted communication</param>
        /// <param name="onDisconnected">Triggered when the tcp socket is disconnected.</param>
        /// <param name="onConnecting">Triggered when the tcp socket is connecting.</param>
        /// <param name="onConnected">Triggered after the tcp socket is successfully connected.</param>
        /// <param name="onWriteEnqueued">Triggered after enqueing async write task for writing to the tcp stream.</param>
        /// <param name="onWriting">Triggered when writing to the tcp stream.</param>
        /// <param name="onWritten">Triggered after having successfully written to the tcp stream.</param>
        /// <param name="onWriteFailed">Triggered after failing to write to the tcp stream.</param>
        /// <param name="onReading">Triggered when starting to read a message's bytes from the tcp stream.</param>
        /// <param name="onReadingChunk">Triggered when reading a chunk of bytes from the tcp stream.</param>
        /// <param name="onReadChunk">Triggered after successfully reading a chunk of bytes from the tcp stream.</param>
        /// <param name="onRead">Triggered after having successfully read a message's bytes from the tcp stream.</param>
        /// <param name="onReadFailed">Triggered after failing to read from the tcp stream.</param>
        /// <param name="onProduceRequestMessages">Triggered when encoding ProduceRequest messages.</param>
        public ConnectionConfiguration(
            IRetry connectionRetry         = null,
            IVersionSupport versionSupport = null,
            TimeSpan?requestTimeout        = null,
            IEnumerable <IProtocolTypeEncoder> encoders = null,
            ISslConfiguration sslConfiguration          = null,
            ConnectError onDisconnected = null,
            Connecting onConnecting     = null,
            Connecting onConnected      = null,
            Writing onWriteEnqueued     = null,
            Writing onWriting           = null,
            WriteSuccess onWritten      = null,
            WriteError onWriteFailed    = null,
            Reading onReading           = null,
            ReadingChunk onReadingChunk = null,
            ReadChunk onReadChunk       = null,
            Read onRead            = null,
            ReadError onReadFailed = null,
            ProduceRequestMessages onProduceRequestMessages = null
            )
        {
            ConnectionRetry = connectionRetry ?? Defaults.ConnectionRetry();
            VersionSupport  = versionSupport ?? Connections.VersionSupport.Kafka8;
            RequestTimeout  = requestTimeout ?? TimeSpan.FromSeconds(Defaults.RequestTimeoutSeconds);
            Encoders        = encoders != null
                ? encoders.ToImmutableDictionary(e => e.Type)
                : ImmutableDictionary <string, IProtocolTypeEncoder> .Empty;

            SslConfiguration         = sslConfiguration;
            OnDisconnected           = onDisconnected;
            OnConnecting             = onConnecting;
            OnConnected              = onConnected;
            OnWriteEnqueued          = onWriteEnqueued;
            OnWriting                = onWriting;
            OnWritten                = onWritten;
            OnWriteFailed            = onWriteFailed;
            OnReading                = onReading;
            OnReadingChunk           = onReadingChunk;
            OnReadChunk              = onReadChunk;
            OnRead                   = onRead;
            OnReadFailed             = onReadFailed;
            OnProduceRequestMessages = onProduceRequestMessages;
        }
Exemplo n.º 15
0
        ///
        /// ------------------------------------------------------------------------------------------------
        /// Name		HandleUnhandledException
        ///
        /// <summary>	Handles the unhandled exception event and caches an event report which is read
        ///             when the app next launches.
        /// </summary>
        /// <param name="sender">		Event source.</param>
        /// <param name="e">			Exception arguments.</param>
        ///
        /// <remarks>
        /// </remarks>
        /// ------------------------------------------------------------------------------------------------
        ///
        private void HandleUnhandledException(object sender, RaiseThrowableEventArgs e)
        {
            IOException   ioex;
            Exception     ex;
            Task          task;
            ErrorReport   report;
            StringBuilder sb;

            try
            {
                ioex = e.Exception as IOException;
                ex   = e.Exception as Exception;
                if (ioex != null)
                {
                    report = new ErrorReport("Unhandled Native Exception", ioex);
                }
                else if (ex != null)
                {
                    report = new ErrorReport("Unhandled Managed Exception", ex);
                }
                else
                {
                    report = new ErrorReport("Unhandled Unrecognised Exception", e.ToString());
                }
                // Make a record of the state of the data when the error occurred.
                sb = new StringBuilder();
                // sb.AppendLine("Premises Data:");
                //  sb.AppendLine(AppData.PremisesModel.Cache);
                //   sb.AppendLine();
                report.AddFurtherInfo(sb.ToString());
                task = new Task(async delegate { await writingfile(report); });
                task.Start();
                task.Wait(1000);
            }
            catch (Exception WriteError)
            {
                report = new ErrorReport("Error File Creation Exception", WriteError.ToString());
                task   = new Task(async delegate { await writingfile(report); });
                task.Start();
                task.Wait(1000);
                LogTracking.LogTrace(WriteError.ToString());
            }
        }
Exemplo n.º 16
0
 static Log()
 {
     #region ---日志地址---
     string dirpath = System.Configuration.ConfigurationManager.AppSettings.Get("LogPath");
     //string dirpath = ConfigurationManager.Get("LogPath");
     if (string.IsNullOrEmpty(dirpath))
     {
         dirpath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData);
     }
     softName = System.Configuration.ConfigurationManager.AppSettings.Get("SoftName");
     if (string.IsNullOrEmpty(softName))
     {
         softName = System.Diagnostics.Process.GetCurrentProcess().MainModule.ModuleName;
     }
     logDir = System.IO.Path.Combine(dirpath, softName);
     try
     {
         if (!System.IO.Directory.Exists(logDir))
         {
             System.IO.Directory.CreateDirectory(logDir);
         }
     }
     catch (System.Exception ex)
     {
         System.Diagnostics.Debug.WriteLine(ex.ToString());
     }
     #endregion
     d = (string message) =>
     {
         writeLine(LogType.debug, message);
     };
     i = (string message) =>
     {
         writeLine(LogType.info, message);
     };
     e = (string message, System.Exception ex) =>
     {
         writeLine(LogType.error, message, ex);
     };
     System.AppDomain.CurrentDomain.ProcessExit += (object sender, System.EventArgs args) => { Dispose(); };
 }
Exemplo n.º 17
0
        private void writeCallback(IAsyncResult ar)
        {
            try
            {
                netStream.EndWrite(ar);
                WriteCompleted?.BeginInvoke(this, new NetworkMessageWriterWriteCompletedEventArgs(ar.AsyncState as NetworkMessage, TcpClient), null, null);
            }
            catch (Exception ex)
            {
                WriteError?.BeginInvoke(this, new NetworkMessageWriterWriteErrorEventArgs(ar.AsyncState as NetworkMessage, TcpClient, ex), null, null);

                if (OnErrorStopWritingAndCloseClient)
                {
                    netStream?.Close();
                    TcpClient?.Close();

                    WriteCompleted = null;
                    WriteError     = null;
                }
            }
        }
Exemplo n.º 18
0
        private void WriteThread()
        {
            while (running)
            {
                while (messageBuffer.Count > 0)
                {
                    byte[] data       = serializer.Serialize(messageBuffer.Dequeue());
                    byte[] dataLength = BitConverter.GetBytes(data.Length);

                    try
                    {
                        stream.Write(dataLength, 0, 4);
                        stream.Write(data, 0, data.Length);
                    }
                    catch (Exception ex)
                    {
                        WriteError?.Invoke(ex);
                    }
                }

                Thread.Sleep(THREAD_WAITING_TIME);
            }
        }
Exemplo n.º 19
0
 public ErrorInfoVM(WriteError errorInfo, MenuItemVM menuItem)
 {
     this.errorInfo = errorInfo;
     this.menuItem  = menuItem;
 }
Exemplo n.º 20
0
 /// <summary>
 /// 初始化Success,Error
 /// </summary>
 /// <param name="success">是否正确回复</param>
 /// <param name="error">错误信息</param>
 public WriteResult(bool success, WriteError error)
 {
     Success = success;
     Error   = error;
 }