Ejemplo n.º 1
0
        internal static async Task <DbConnection> TryOpenAsync(this DbConnection connection, CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested();

            if (connection.State == ConnectionState.Broken)
            {
                connection.Close();
            }

            if (connection.State != ConnectionState.Open)
            {
                try
                {
                    var watch = Stopwatch.StartNew();
                    await connection.OpenAsync(cancellationToken).ConfigureAwait(false);

                    Tracer.Debug($"The connection of '{connection.ConnectionString}' was opened ({watch.ElapsedMilliseconds}ms).");
                }
                catch (DbException exp)
                {
                    Tracer.Error($"Opening Connection of '{connection.ConnectionString}' throw exception:{exp.Output()}");
                    throw ConnectionException.Throw(ConnectionState.Open, exp);
                }
            }

            return(connection);
        }
        void InitializeProjectClientListener()
        {
            try
            {
                var client = Player.CreateClient(m_Project, m_User, ProjectServer.Client);
                m_Listener = new ClientListener(client); // TODO Should this class also be responsible to instantiate the Client?
                m_Listener.onManifestUpdated += (c, s) => manifestUpdated?.Invoke();
            }
            catch (ConnectionException ex)
            {
                var    unityProject = m_Project;
                string message;
                if (unityProject.Host.IsLocalService)
                {
                    message = "A connection with your local server could not be established. Make sure the Unity Reflect Service is running.";
                }
                else
                {
                    if (unityProject.Host.ServerName == "Cloud")
                    {
                        message = $"A connection with Reflect Cloud could not be established.";
                    }
                    else
                    {
                        message = $"A connection with the server {unityProject.Host.ServerName} could not be established. This server may be outside your local network (LAN) or may not accept external connections due to firewall policies.";
                    }
                }

                ex = new ConnectionException(message, ex);
                //completeWithError(ex);
                //throw ex;
            }
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Resets the state of this object and clears its properties.
 /// </summary>
 public void Reset()
 {
     this.Headers    = null;
     this.Body       = string.Empty;
     this.StatusCode = null;
     this.Exception  = null;
 }
Ejemplo n.º 4
0
        private ConnectionStatus Execute(RestRequest restRequest)
        {
            //RestResponse result = GetClient().execute(restRequest);
            //

            if (!this._resourceLock.WaitOne(this._timeout))
            {
                var m = "Could not start the thrift operation before the timeout of " + this._timeout + "ms completed while waiting for the semaphore";
                return(new ConnectionStatus(this._connectionSettings, new TimeoutException(m)));
            }
            try
            {
                Rest.Client client = null;
                if (!this._clients.TryDequeue(out client))
                {
                    var m      = string.Format("Could dequeue a thrift client from internal socket pool of size {0}", this._poolSize);
                    var status = new ConnectionStatus(this._connectionSettings, new Exception(m));
                    return(status);
                }
                try
                {
                    if (!client.InputProtocol.Transport.IsOpen)
                    {
                        client.InputProtocol.Transport.Open();
                    }

                    var result = client.execute(restRequest);
                    if (result.Status == Status.OK || result.Status == Status.CREATED || result.Status == Status.ACCEPTED)
                    {
                        return(new ConnectionStatus(this._connectionSettings, DecodeStr(result.Body)));
                    }
                    else
                    {
                        var connectionException = new ConnectionException(
                            msg: Enum.GetName(typeof(Status), result.Status),
                            statusCode: (int)result.Status,
                            response: DecodeStr(result.Body)
                            );
                        return(new ConnectionStatus(this._connectionSettings, connectionException));
                    }
                }
                catch
                {
                    throw;
                }
                finally
                {
                    //make sure we make the client available again.
                    this._clients.Enqueue(client);
                }
            }
            catch (Exception e)
            {
                return(new ConnectionStatus(this._connectionSettings, e));
            }
            finally
            {
                this._resourceLock.Release();
            }
        }
 /// <summary>
 /// Resets the state of this object and clears its properties.
 /// </summary>
 public void Reset()
 {
     this.Headers = null;
     this.Body = string.Empty;
     this.StatusCode = null;
     this.Exception = null;
 }
Ejemplo n.º 6
0
        public async Task TryRespondAsync_Generates_Warning_On_Cache_Add_Failure(string username, int token, string query, SearchResponse searchResponse, IPEndPoint endpoint, int responseToken)
        {
            var value   = (username, token, query, searchResponse);
            var cacheEx = new Exception();

            var cache = new Mock <ISearchResponseCache>();

            cache.Setup(m => m.AddOrUpdate(responseToken, value))
            .Throws(cacheEx);

            var(responder, mocks) = GetFixture(new SoulseekClientOptions(
                                                   searchResponseCache: cache.Object,
                                                   searchResponseResolver: (u, t, q) => Task.FromResult(searchResponse)));

            mocks.Client.Setup(m => m.GetUserEndPointAsync(username, It.IsAny <CancellationToken?>()))
            .Returns(Task.FromResult(endpoint));
            mocks.Client.Setup(m => m.GetNextToken())
            .Returns(responseToken);

            var ex = new ConnectionException();

            mocks.PeerConnectionManager.Setup(m => m.GetOrAddMessageConnectionAsync(username, endpoint, responseToken, It.IsAny <CancellationToken>()))
            .Returns(Task.FromException <IMessageConnection>(ex));

            var responded = await responder.TryRespondAsync(username, token, query);

            Assert.False(responded);

            mocks.Diagnostic.Verify(m => m.Warning(It.Is <string>(s => s.ContainsInsensitive("Error caching undelivered search response")), cacheEx), Times.Once);
        }
Ejemplo n.º 7
0
        public async Task TryRespondAsync_Caches_Response_On_Connect_Failure(string username, int token, string query, SearchResponse searchResponse, IPEndPoint endpoint, int responseToken)
        {
            var cache = new Mock <ISearchResponseCache>();

            var(responder, mocks) = GetFixture(new SoulseekClientOptions(
                                                   searchResponseCache: cache.Object,
                                                   searchResponseResolver: (u, t, q) => Task.FromResult(searchResponse)));

            mocks.Client.Setup(m => m.GetUserEndPointAsync(username, It.IsAny <CancellationToken?>()))
            .Returns(Task.FromResult(endpoint));
            mocks.Client.Setup(m => m.GetNextToken())
            .Returns(responseToken);

            var ex = new ConnectionException();

            mocks.PeerConnectionManager.Setup(m => m.GetOrAddMessageConnectionAsync(username, endpoint, responseToken, It.IsAny <CancellationToken>()))
            .Returns(Task.FromException <IMessageConnection>(ex));

            var responded = await responder.TryRespondAsync(username, token, query);

            Assert.False(responded);

            var value = (username, token, query, searchResponse);

            cache.Verify(m => m.AddOrUpdate(responseToken, value), Times.Once);
        }
Ejemplo n.º 8
0
 static bool IsUnrecoverable(Exception exception)
 {
     return(exception switch
     {
         ConnectionException connectionException => !connectionException.IsTransient,
         _ => false
     });
Ejemplo n.º 9
0
        internal static void OpenClose(this DbConnection connection, Action action)
        {
            if (action == null)
            {
                return;
            }

            if (connection.State != ConnectionState.Open)
            {
                try
                {
                    connection.Open();
                }
                catch (DbException exp)
                {
                    throw ConnectionException.Throw(ConnectionState.Open, exp);
                }
            }

            action();
            if (connection.State != ConnectionState.Closed)
            {
                try
                {
                    connection.Close();
                }
                catch (DbException exp)
                {
                    throw ConnectionException.Throw(ConnectionState.Closed, exp);
                }
            }
        }
Ejemplo n.º 10
0
            private void Throw(IPEndPoint endPoint, string message, Exception inner = null)
            {
                var ce = new ConnectionException(endPoint, message, inner);

                _Logger.Error(ce.Message, ce);
                throw ce;
            }
Ejemplo n.º 11
0
 /// <summary>
 /// Resets the state of this object and clears its properties.
 /// </summary>
 public void Reset()
 {
     Headers    = null;
     Body       = string.Empty;
     StatusCode = null;
     Exception  = null;
 }
Ejemplo n.º 12
0
        public void TestSendTestFRTimeoutMaster()
        {
            ConnectionParameters clientParameters = new ConnectionParameters();
            ConnectionParameters serverParameters = new ConnectionParameters();

            clientParameters.T3 = 1;

            Server server = new Server(serverParameters);

            server.SetLocalPort(20213);

            server.Start();

            Connection connection = new Connection("127.0.0.1", 20213, clientParameters);

            connection.Connect();

            connection.SetRawMessageHandler(testSendTestFRTimeoutMasterRawMessageHandler, null);

            ASDU asdu = new ASDU(clientParameters, CauseOfTransmission.SPONTANEOUS, false, false, 0, 1, false);

            asdu.AddInformationObject(new SinglePointInformation(100, false, new QualityDescriptor()));

            connection.SendASDU(asdu);

            Assert.AreEqual(2, connection.GetStatistics().SentMsgCounter);               /* STARTDT + ASDU */

            while (connection.GetStatistics().RcvdMsgCounter < 2)
            {
                Thread.Sleep(1);
            }

            Assert.AreEqual(2, connection.GetStatistics().RcvdMsgCounter);               /* STARTDT_CON + ASDU */

            Thread.Sleep(6000);

            // Expect connection to be closed due to three missing TESTFR_CON responses
            Assert.IsFalse(connection.IsRunning);

            ConnectionException ce = null;

            // Connection is closed. SendASDU should fail
            try {
                connection.SendASDU(asdu);
            }
            catch (ConnectionException e) {
                ce = e;
            }

            Assert.IsNotNull(ce);
            Assert.AreEqual("not connected", ce.Message);

            connection.Close();
            server.Stop();

            Assert.AreEqual(5, connection.GetStatistics().RcvdMsgCounter);               /* STARTDT_CON + ASDU + TESTFR_CON */

            Assert.AreEqual(0, connection.GetStatistics().RcvdTestFrConCounter);
        }
Ejemplo n.º 13
0
        public void Constructor_ReturnsInstance()
        {
            ConnectionException connectionException = new ConnectionException(HttpStatusCode.InternalServerError, "test_string");

            Assert.IsNotNull(connectionException);
            Assert.AreEqual("test_string", connectionException.ReasonPhrase);
            Assert.AreEqual(HttpStatusCode.InternalServerError, connectionException.StatusCode);
        }
Ejemplo n.º 14
0
        public static DataphorFault ExceptionToFault(DataphorException exception)
        {
            DataphorFault fault = new DataphorFault();

            fault.ExceptionClassName = exception.GetType().Name;
            fault.Code          = exception.Code;
            fault.Severity      = exception.Severity;
            fault.Message       = exception.Message;
            fault.Details       = exception.Details;
            fault.ServerContext = exception.ServerContext;
            if (exception.InnerException != null)
            {
                fault.InnerFault = ExceptionToFault(exception.InnerException);
            }

                        #if !SILVERLIGHT
            // Under Silverlight, a ConnectionException will come back as a DataphorException
            // The statement is still present in the Details.
            ConnectionException connectionException = exception as ConnectionException;
            if (connectionException != null)
            {
                fault.Statement = connectionException.Statement;
            }
                        #endif

            SyntaxException syntaxException = exception as SyntaxException;
            if (syntaxException != null)
            {
                fault.Locator   = syntaxException.Locator;
                fault.Line      = syntaxException.Line;
                fault.LinePos   = syntaxException.LinePos;
                fault.Token     = syntaxException.Token;
                fault.TokenType = syntaxException.TokenType;
            }

            CompilerException compilerException = exception as CompilerException;
            if (compilerException != null)
            {
                fault.Locator    = compilerException.Locator;
                fault.Line       = compilerException.Line;
                fault.LinePos    = compilerException.LinePos;
                fault.ErrorLevel = compilerException.ErrorLevel;
            }

            RuntimeException runtimeException = exception as RuntimeException;
            if (runtimeException != null)
            {
                fault.Locator = runtimeException.Locator;
                fault.Line    = runtimeException.Line;
                fault.LinePos = runtimeException.LinePos;
                fault.Context = runtimeException.Context;
            }

            return(fault);
        }
Ejemplo n.º 15
0
        private async Task <HttpResponseMessage> Call(string url, HttpMethod method, CancellationToken cancellationToken, object data = null)
        {
            using (var httpClient = new HttpClient())
            {
                cancellationToken.ThrowIfCancellationRequested();
                if (method == HttpMethod.Get)
                {
                    if (data != null)
                    {
                        var query = data.ToString();
                        url += "?" + query;
                    }
                }

                using (var request = new HttpRequestMessage {
                    RequestUri = new Uri(url), Method = method
                })
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    if (!string.IsNullOrEmpty(Toke))
                    {
                        List <string> values = new List <string>();
                        httpClient.DefaultRequestHeaders.Clear();
                        values.Add(Toke);
                        httpClient.DefaultRequestHeaders.Add("iSystainToken", values);
                        // httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", this.Toke);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    if (method != HttpMethod.Get)
                    {
                        var jsonContent = JsonConvert.SerializeObject(data);
                        request.Content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
                    }



                    HttpResponseMessage response = new HttpResponseMessage();
                    try
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        response = await httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        var excep = new ConnectionException(ex.Message);

                        throw excep;
                    }

                    return(response);
                }
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Helper method for functional tests where we want to record more details.
        /// </summary>
        /// <param name="ex">The exception containing the information to be recorded.</param>
        public static void WriteConnectionExceptionDetails(ConnectionException ex)
        {
            System.Diagnostics.Trace.WriteLine("[WebExceptionStatus]: " + ex.WebExceptionStatus);
            System.Diagnostics.Trace.WriteLine("[Request URL]: " + ex.Request.RequestUri.AbsoluteUri);
            System.Diagnostics.Trace.WriteLine("[Request Headers]: " + string.Join(" ; ", ex.Request.Headers));

            // Check if the exception is an HttpException. If so, log the response headers.
            if (ex is HttpException)
            {
                System.Diagnostics.Trace.WriteLine("[Response Headers]: " + string.Join(" ; ", ((HttpException)ex).Headers));
            }
            System.Diagnostics.Trace.WriteLine("[Response]: " + ex.Response);
        }
Ejemplo n.º 17
0
        public void TestConnectionException()
        {
            // arrange
            var inner = new Exception();

            // act
            var exception = new ConnectionException(inner);

            exception.PreviousAppointmentState = AppointmentState.Modified;

            // assert
            Assert.That(exception.InnerException, Is.EqualTo(inner));
            Assert.That(exception.PreviousAppointmentState, Is.EqualTo(AppointmentState.Modified));
        }
Ejemplo n.º 18
0
 internal static async Task TryOpenAsync(this DbConnection connection, bool autoOpen = true, CancellationToken cancellationToken = default)
 {
     if (autoOpen && connection.State != ConnectionState.Open)
     {
         try
         {
             await connection.OpenAsync(cancellationToken);
         }
         catch (DbException exp)
         {
             throw ConnectionException.Throw(ConnectionState.Open, exp);
         }
     }
 }
Ejemplo n.º 19
0
 internal static void TryClose(this DbConnection connection, bool autoOpen = true)
 {
     if (autoOpen && connection.State != ConnectionState.Closed)
     {
         try
         {
             connection.Close();
         }
         catch (DbException exp)
         {
             throw ConnectionException.Throw(ConnectionState.Closed, exp);
         }
     }
 }
Ejemplo n.º 20
0
        public void HandleLastError(string message)
        {
            Exception newException;

            if (_lastException is WebException)
            {
                newException = new ConnectionException(message, _lastException);
            }
            else
            {
                newException = new InputOutputException(_lastException, message);
            }

            _io.HandleException(newException);
        }
        /// <summary>
        /// Проверить подключение к БД.
        /// </summary>
        public bool TryConnect(out ConnectionException error)
        {
            error = null;

            try
            {
                using DbConnection conn = OpenNewConnection();
                return(true);
            }
            catch (ConnectionException ex)
            {
                error = ex;
                return(false);
            }
        }
        public void ConnectionException_CanBeSerialized()
        {
            // Arrange
            const string dummyMessage   = "dummyMessage";
            IFormatter   dummyFormatter = new BinaryFormatter();
            var          dummyStream    = new MemoryStream();
            var          testSubject    = new ConnectionException(dummyMessage);

            // Act
            dummyFormatter.Serialize(dummyStream, testSubject);
            dummyStream.Position = 0;
            var result = (ConnectionException)dummyFormatter.Deserialize(dummyStream);

            // Assert
            Assert.Equal(dummyMessage, result.Message);
        }
Ejemplo n.º 23
0
        public void ConnectionExceptionConstructors()
        {
            _ = new ConnectionException();
            _ = new ConnectionException("exception");
            _ = new ConnectionException(new Exception("bang"));
            var e = new ConnectionException("exception", new Exception("bang"));

            Assert.That(e.Message, Is.EqualTo("exception"));
            Assert.That(e.InnerException, Is.Not.Null);
            Assert.That(e.InnerException.Message, Is.EqualTo("bang"));

            e = e.SerializeAndDeSerialize();

            Assert.That(e.Message, Is.EqualTo("exception"));
            Assert.That(e.InnerException, Is.Not.Null);
            Assert.That(e.InnerException.Message, Is.EqualTo("bang"));
        }
Ejemplo n.º 24
0
        internal static DbConnection TryOpen(this DbConnection connection)
        {
            if (connection.State != ConnectionState.Open)
            {
                try
                {
                    var watch = Stopwatch.StartNew();
                    connection.Open();
                    Tracer.Debug($"The connection of '{connection.ConnectionString}' was opened ({watch.ElapsedMilliseconds}ms).");
                }
                catch (DbException exp)
                {
                    Tracer.Error($"Opening Connection of '{connection.ConnectionString}' throw exception:{exp.Output()}");
                    throw ConnectionException.Throw(ConnectionState.Open, exp);
                }
            }

            return(connection);
        }
Ejemplo n.º 25
0
        public void ConnectionExceptionConstructorTest()
        {
            // test case 1: no parameters

            ConnectionException exception = new ConnectionException();

            Assert.AreEqual(null, exception.Path);


            // test case 2: message parameter

            exception = new ConnectionException("Exception message.");

            Assert.AreEqual("Exception message.", exception.Message);
            Assert.AreEqual(null, exception.Path);

            // test case 3: message and path parameters

            exception = new ConnectionException("Exception message.", "path");

            Assert.AreEqual("Exception message.", exception.Message);
            Assert.AreEqual("path", exception.Path);


            // test case 4: message and innerexception parameters

            Exception innerException = new Exception();

            exception = new ConnectionException("Exception message.", innerException);

            Assert.AreEqual("Exception message.", exception.Message);
            Assert.AreEqual(null, exception.Path);
            Assert.AreEqual(innerException, exception.InnerException);


            // test case 5: message, path and innerexception parameters

            exception = new ConnectionException("Exception message.", "path", innerException);

            Assert.AreEqual("Exception message.", exception.Message);
            Assert.AreEqual("path", exception.Path);
            Assert.AreEqual(innerException, exception.InnerException);
        }
Ejemplo n.º 26
0
        public async Task TryRespondAsync_Generates_Debug_On_Failure(string username, int token, string query, SearchResponse searchResponse, IPEndPoint endpoint, int responseToken)
        {
            var(responder, mocks) = GetFixture(new SoulseekClientOptions(searchResponseResolver: (u, t, q) => Task.FromResult(searchResponse)));

            mocks.Client.Setup(m => m.GetUserEndPointAsync(username, It.IsAny <CancellationToken?>()))
            .Returns(Task.FromResult(endpoint));
            mocks.Client.Setup(m => m.GetNextToken())
            .Returns(responseToken);

            var ex = new ConnectionException();

            mocks.PeerConnectionManager.Setup(m => m.GetOrAddMessageConnectionAsync(username, endpoint, responseToken, It.IsAny <CancellationToken>()))
            .Returns(Task.FromException <IMessageConnection>(ex));

            var responded = await responder.TryRespondAsync(username, token, query);

            Assert.False(responded);

            mocks.Diagnostic.Verify(m => m.Debug(It.Is <string>(s => s.ContainsInsensitive("Failed to send search response")), ex), Times.Once);
        }
Ejemplo n.º 27
0
            public WhenAnErrorOccursWhenSendingAPing()
            {
                var clientFactory = new Mock <IClientFactory>();

                _client = new Mock <IClient>();
                _client
                .Setup(c => c.SendAsync(It.IsAny <IRedisType>(), It.IsAny <CancellationToken>()))
                .ReturnsAsync(new RedisString("PONG"));
                clientFactory.SetReturnsDefault(Task.FromResult(_client.Object));

                _connection = new BasicConnection(new IPEndPoint(IPAddress.Loopback, 6379), clientFactory.Object);

                _connection.OpenAsync(CancellationToken.None).Wait();

                _client.Reset();
                _client
                .Setup(c => c.SendAsync(It.IsAny <IRedisType>(), It.IsAny <CancellationToken>()))
                .ThrowsAsync(new SocketException());

                _ex = Assert.ThrowsAsync <ConnectionException>(() => _connection.PingAsync(CancellationToken.None)).Result;
            }
Ejemplo n.º 28
0
        //[Ignore("Ignore to save execution time")]
        public void TestConnectWhileAlreadyConnected()
        {
            ConnectionParameters parameters = new ConnectionParameters();

            Server server = new Server(parameters);

            server.SetLocalPort(20213);

            server.Start();

            Connection connection = new Connection("127.0.0.1", 20213, parameters);

            ConnectionException se = null;

            try {
                connection.Connect();
            }
            catch (ConnectionException ex) {
                se = ex;
            }

            Assert.IsNull(se);

            Thread.Sleep(100);

            try {
                connection.Connect();
            }
            catch (ConnectionException ex) {
                se = ex;
            }

            Assert.IsNotNull(se);
            Assert.AreEqual(se.Message, "already connected");
            Assert.AreEqual(10056, ((SocketException)se.InnerException).ErrorCode);

            connection.Close();

            server.Stop();
        }
Ejemplo n.º 29
0
        protected virtual async void OnConnectionException(ConnectionException ex)
        {
            var requestResult = ex?.RequestResult;

            if (requestResult == null || requestResult.RequestCanceled)
            {
                return;
            }

            if (requestResult.ResponseContent != null)
            {
                var contentAsString = await requestResult.ResponseContent.ReadAsStringAsync();

                await UserDialogs.Error(contentAsString ?? requestResult.Exception?.Message);
            }

            MvxTrace.TaggedTrace(MvxTraceLevel.Warning, this.GetType().FullName, Newtonsoft.Json.JsonConvert.SerializeObject(requestResult, Newtonsoft.Json.Formatting.Indented));

            if (ex != null)
            {
                MvxTrace.TaggedTrace(MvxTraceLevel.Warning, this.GetType().FullName, ex.BuildAllMessagesAndStackTrace());
            }
        }
Ejemplo n.º 30
0
        /// <summary>Report a Connection Exception</summary>
        /// <param name="ce"></param>
        public void ReportConnectionExceptionError(ConnectionException ce)
        {
            var errorDescription = "";
            var solutionIdea     = "";

            if (ce.Message == "HostNotFound")
            {
                errorDescription += "The server you tried connecting to doesn't exist.";
                solutionIdea     += "Make sure the host name for the server you tried connecting to is correct.";
            }
            else if (ce.Message == "NoRouteToTost")
            {
                errorDescription += "A socket operation was attempted to an unreachable host";
                solutionIdea     += "Check the host name you tried connecting to. Make sure it's correct.";
            }
            else if (ce.Message == "ConnectionRefused")
            {
                errorDescription += "No connection could be made because the target computer actively refused it. This usually results from trying to connect to a service that is inactive on the foreign host—that is, one with no server application running.";
                solutionIdea     += "Check the host name you tried connecting to, make sure it's correct. You can also try to report this problem to the server owners.";
            }
            else
            {
                errorDescription += "An unknown error occured.";
                solutionIdea     += "Please report this error in the SharpWired bug tracker at http://code.google.com/p/sharpwired/issues/list. Error message is: " + ce;
            }

            solutionIdea += " For now, restart SharpWired before trying again."; // TODO: Remove this once SW recovers from connection problems

            Console.WriteLine("Error! " + errorDescription);
            Console.WriteLine("Bookmark: " + ce.Bookmark);

            if (LoginFailed != null)
            {
                LoginFailed(errorDescription, solutionIdea, ce.Bookmark);
            }
        }
Ejemplo n.º 31
0
        internal static DbConnection TryClose(this DbConnection connection, bool allowClose = true)
        {
            if (!allowClose)
            {
                return(connection);
            }

            if (connection.State == ConnectionState.Open)
            {
                try
                {
                    var watch = Stopwatch.StartNew();
                    connection.Close();
                    Tracer.Debug($"The connection of '{connection.ConnectionString}' was closed ({watch.ElapsedMilliseconds}ms).");
                }
                catch (DbException exp)
                {
                    Tracer.Error($"Closing Connection of '{connection.ConnectionString}' throw exception:{exp.Output()}");
                    throw ConnectionException.Throw(ConnectionState.Open, exp);
                }
            }

            return(connection);
        }
Ejemplo n.º 32
0
        static void updateReportScheduler2(string taskID, ConnectionException.Reason errorReason)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
            {
                conn.Open();

                string sqlInsert = "INSERT INTO [db_knx].[dbo].[ReportScheduler] ([TaskID],[ErrorID],[ErrorException]) VALUES " +
                    " (" + taskID + ",N'" + errorReason + "',N'ConnectionException')";

                using (SqlCommand sqlComm = new SqlCommand(sqlInsert, conn))
                {
                    sqlComm.ExecuteNonQuery();
                }

                conn.Close();
            }
        }
Ejemplo n.º 33
0
        private ElasticsearchResponse Execute(RestRequest restRequest)
        {
            //RestResponse result = GetClient().execute(restRequest);
            //
            var method = Enum.GetName(typeof (Method), restRequest.Method);
            var path = restRequest.Uri.ToString();
            var requestData = restRequest.Body;
            if (!this._resourceLock.WaitOne(this._timeout))
            {
                var m = "Could not start the thrift operation before the timeout of " + this._timeout + "ms completed while waiting for the semaphore";
                return ElasticsearchResponse.CreateError(this._connectionSettings, new TimeoutException(m), method, path, requestData);
            }
            try
            {
                Rest.Client client = null;
                if (!this._clients.TryDequeue(out client))
                {
                    var m = string.Format("Could dequeue a thrift client from internal socket pool of size {0}", this._poolSize);
                    var status = ElasticsearchResponse.CreateError(this._connectionSettings, new Exception(m), method, path, requestData);
                    return status;
                }
                try
                {
                    if (!client.InputProtocol.Transport.IsOpen)
                        client.InputProtocol.Transport.Open();

                    var result = client.execute(restRequest);
                    if (result.Status == Status.OK || result.Status == Status.CREATED || result.Status == Status.ACCEPTED)
                        return ElasticsearchResponse.Create(this._connectionSettings, (int)result.Status, method, path, requestData, result.Body);
                    else
                    {
                        var connectionException = new ConnectionException((int)result.Status);
                        return ElasticsearchResponse.CreateError(this._connectionSettings, connectionException, method, path, requestData);
                    }
                }
                catch
                {
                    throw;
                }
                finally
                {
                    //make sure we make the client available again.
                    this._clients.Enqueue(client);
                }

            }
            catch (Exception e)
            {
                return ElasticsearchResponse.CreateError(this._connectionSettings, e, method, path, requestData);
            }
            finally
            {
                this._resourceLock.Release();
            }
        }
Ejemplo n.º 34
0
        public static PythonRemoteDebugProcess Connect(PythonRemoteDebugPort port) {
            PythonRemoteDebugProcess process = null;

            // Connect to the remote debugging server and obtain process information. If any errors occur, display an error dialog, and keep
            // trying for as long as user clicks "Retry".
            while (true) {
                Stream stream = null;
                ConnectionException connEx = null;
                try {
                    // Process information is not sensitive, so ignore any SSL certificate errors, rather than bugging the user with warning dialogs.
                    stream = PythonRemoteProcess.Connect(port.Uri, false);
                } catch (ConnectionException ex) {
                    connEx = ex;
                }

                using (stream) {
                    if (stream != null) {
                        try {
                            stream.Write(PythonRemoteProcess.InfoCommandBytes);
                            int pid = stream.ReadInt32();
                            string exe = stream.ReadString();
                            string username = stream.ReadString();
                            string version = stream.ReadString();
                            process = new PythonRemoteDebugProcess(port, pid, exe, username, version);
                            break;
                        } catch (IOException ex) {
                            connEx = new ConnectionException(ConnErrorMessages.RemoteNetworkError, ex);
                        }
                    }

                    if (connEx != null) {
                        string errText;
                        switch (connEx.Error) {
                            case ConnErrorMessages.RemoteUnsupportedServer:
                                errText = Strings.RemoteUnsupportedServer_Host.FormatUI(port.Uri);
                                break;
                            case ConnErrorMessages.RemoteSecretMismatch:
                                errText = Strings.RemoteSecretMismatch_Host.FormatUI(new UriBuilder(port.Uri) { UserName = null, Password = null }.Uri);
                                break;
                            case ConnErrorMessages.RemoteSslError:
                                // User has already got a warning dialog and clicked "Cancel" on that, so no further prompts are needed.
                                return null;
                            default:
                                {
                                    // Azure uses HTTP 503 (Service Unavailable) to indicate that websocket connections are not supported. Show a special error message for that.
                                    var wsEx = connEx.InnerException as WebSocketException;
                                    if (wsEx != null) {
                                        var webEx = wsEx.InnerException as WebException;
                                        if (webEx != null) {
                                            var httpResponse = webEx.Response as HttpWebResponse;
                                            if (httpResponse != null && httpResponse.StatusCode == HttpStatusCode.ServiceUnavailable) {
                                                errText = Strings.RemoteAzureServiceUnavailable_Host.FormatUI(port.Uri);
                                                break;
                                            }
                                        }
                                    }

                                    errText = Strings.RemoteServiceUnavailable_Host.FormatUI(port.Uri);
                                    for (var ex = connEx.InnerException; ex != null; ex = ex.InnerException) {
                                        if (ex.InnerException == null) {
                                            errText += "\r\n\r\n{0}\r\n{1}".FormatUI(Strings.AdditionalInformation, ex.Message);
                                        }
                                    }
                                    break;
                                }
                        }

                        DialogResult dlgRes = MessageBox.Show(errText, null, MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
                        if (dlgRes != DialogResult.Retry) {
                            break;
                        }
                    }
                }
            }

            return process;
        }
Ejemplo n.º 35
0
        static void emailWaring(string _id, string _subject, DateTime _start, DateTime _end, string _channels, string _pillar, ConnectorException connectorException, ConnectionException connectionException, NoResponseReceivedException noResponseException)
        {
            string emailBody = string.Empty;

            if (connectorException != null)
            {
                emailBody = "Γεια σας κ. Administrator.<br /><br />" +
                    "Σας ενημερώνουμε ότι η εργασία " + _id + " με την ημερομηνία έναρξης " + _start.ToString("d/M/yyyy H:mm tt") + " και την ημερομηνία λήξης " + _end.ToString("d/M/yyyy H:mm tt") + " ";
                if (_subject.IndexOf("LIGHTS ON") > -1)
                {
                    emailBody += "δεν άναψε";
                }

                if (_subject.IndexOf("LIGHTS OFF") > -1)
                {
                    emailBody += "δεν έσβησε";
                }

                if (_channels == "0")
                {
                    emailBody += " όλες τις ηλεκτρολογικές αναχωρήσεις";
                }
                else
                {
                    emailBody += " τις ηλεκτρολογικές αναχωρήσεις " + _channels;
                }

                emailBody += " του πυλώνα " + getPillarName(_pillar);

                switch (connectorException.ErrorReason)
                {
                    case ConnectorException.Reason.DeviceNotFound:
                        emailBody += " επειδή <span style=\"color:red;\">Η συσκευή KNX δεν μπορεί να βρεθεί</span>.<br/><br/>";
                        break;
                    case ConnectorException.Reason.DeviceNotRespond:
                        emailBody += " επειδή <span style=\"color:red;\">Η συσκευή KNX δεν ανταποκρίνεται στο αναμενόμενο χρόνο</span>.<br/><br/>";
                        break;
                    case ConnectorException.Reason.NoMoreConnections:
                        emailBody += " επειδή : <span style=\"color:red;\">Η συσκευή KNX δεν μπορεί να δεχτεί τη νέα σύνδεση, διότι το ανώτατο οριο των ταυτόχρονων συνδέσεων έχει υπερβεί ήδη</span>.<br/><br/>";
                        break;
                    default:
                        emailBody += " επειδή <span style=\"color:red;\">" + connectorException.ErrorReason + "</span>.<br/>";
                        break;
                }

                emailBody += "Με εκτίμηση,<br/>Σύστημα Διαχείρισης Ηλεκτροφωτισμού";
            }

            if (connectionException != null)
            {
                emailBody = "Γεια σας κ. Administrator.<br /><br />" +
                    "Σας ενημερώνουμε ότι η εργασία " + _id + " με την ημερομηνία έναρξης " + _start.ToString("d/M/yyyy H:mm tt") + " και την ημερομηνία λήξης " + _end.ToString("d/M/yyyy H:mm tt") + " ";
                if (_subject.IndexOf("LIGHTS ON") > -1)
                {
                    emailBody += "δεν άναψε";
                }

                if (_subject.IndexOf("LIGHTS OFF") > -1)
                {
                    emailBody += "δεν έσβησε";
                }

                if (_channels == "0")
                {
                    emailBody += " όλες τις ηλεκτρολογικές αναχωρήσεις";
                }
                else
                {
                    emailBody += " τις ηλεκτρολογικές αναχωρήσεις " + _channels;
                }

                emailBody += " του πυλώνα " + getPillarName(_pillar);

                switch (connectionException.ErrorReason)
                {
                    case ConnectionException.Reason.NotConnected:
                        emailBody += " επειδή <span style=\"color:red;\">Η σύνδεση δεν εγκαθιδρύθηκε</span>.<br/><br/>";
                        break;
                    case ConnectionException.Reason.NoMoreConnections:
                        emailBody += " επειδή <span style=\"color:red;\">Η συσκευή δεν μπορεί να δεχθεί τη νέα σύνδεση, διότι το ανώτατο ποσό των ταυτόχρονων συνδέσεων χρησιμοποιείται ήδη.</span>.<br/><br/>";
                        break;
                    case ConnectionException.Reason.ConnectionRefused:
                        emailBody += " επειδή <span style=\"color:red;\">Η σύνδεση αρνήθηκε από τη συσκευή προορισμού</span>.<br/><br/>";
                        break;
                    default:
                        emailBody += " επειδή <span style=\"color:red;\">" + connectionException.ErrorReason + "</span>.<br/>";
                        break;
                }

                emailBody += "Με εκτίμηση,<br/>Σύστημα Διαχείρισης Ηλεκτροφωτισμού";
            }

            if (noResponseException != null)
            {
                emailBody = "Γεια σας κ. Administrator.<br /><br />" +
                    "Σας ενημερώνουμε ότι η εργασία " + _id + " με την ημερομηνία έναρξης " + _start.ToString("d/M/yyyy H:mm tt") + " και την ημερομηνία λήξης " + _end.ToString("d/M/yyyy H:mm tt") + " ";
                if (_subject.IndexOf("LIGHTS ON") > -1)
                {
                    emailBody += "δεν άναψε";
                }

                if (_subject.IndexOf("LIGHTS OFF") > -1)
                {
                    emailBody += "δεν έσβησε";
                }

                if (_channels == "0")
                {
                    emailBody += " όλες τις ηλεκτρολογικές αναχωρήσεις";
                }
                else
                {
                    emailBody += " τις ηλεκτρολογικές αναχωρήσεις " + _channels;
                }

                emailBody += " του πυλώνα " + getPillarName(_pillar);

                switch (noResponseException.ErrorReason)
                {
                    case NoResponseReceivedException.Reason.Confirmation:
                        emailBody += " επειδή <span style=\"color:red;\">Δεν λήφθηκε επιβεβαίωση για το τηλεγράφημα</span>.<br/><br/>";
                        break;
                    case NoResponseReceivedException.Reason.NegativeConfirmation:
                        emailBody += " επειδή <span style=\"color:red;\">Λήφθηκε μια αρνητική επιβεβαίωση για το τηλεγράφημα</span>.<br/><br/>";
                        break;
                    case NoResponseReceivedException.Reason.Indication:
                        emailBody += " επειδή <span style=\"color:red;\">Καμία ένδειξη για το τηλεγράφημα</span>.<br/><br/>";
                        break;
                    default:
                        emailBody += " επειδή <span style=\"color:red;\">" + noResponseException.ErrorReason + "</span>.<br/>";
                        break;
                }

                emailBody += "Με εκτίμηση,<br/>Σύστημα Διαχείρισης Ηλεκτροφωτισμού";
            }

            if(connectorException == null && connectionException == null && noResponseException == null)
            {
                emailBody = "Γεια σας κ. Administrator.<br /><br />" +
                    "Σας ενημερώνουμε ότι η εργασία " + _id + " με την ημερομηνία έναρξης " + _start.ToString("d/M/yyyy H:mm tt") + " και την ημερομηνία λήξης " + _end.ToString("d/M/yyyy H:mm tt")+" ";
                if (_subject.IndexOf("LIGHTS ON") > -1)
                {
                    emailBody += "άναψε";
                }

                if (_subject.IndexOf("LIGHTS OFF") > -1)
                {
                    emailBody += "έσβησε";
                }

                if (_channels == "0")
                {
                    emailBody += " όλες τις ηλεκτρολογικές αναχωρήσεις";
                }
                else
                {
                    emailBody += " τις ηλεκτρολογικές αναχωρήσεις " + _channels;
                }

                emailBody += " του πυλώνα "+getPillarName(_pillar) + ".<br/><br/>";
                emailBody += "Με εκτίμηση,<br/>Σύστημα Διαχείρισης Ηλεκτροφωτισμού";
            }

            // Send email report to system administrator
            try
            {
                SmtpClient ob = new SmtpClient("smtp.office365.com");
                ob.UseDefaultCredentials = false;
                ob.EnableSsl = true;
                ob.Credentials = new NetworkCredential("*****@*****.**", "83Ruid1987!");

                MailMessage obMsg = new MailMessage();
                obMsg.From = new MailAddress("*****@*****.**", "Σύστημα Διαχείρισης Ηλεκτροφωτισμού (Do not reply)");
                obMsg.To.Add(new MailAddress("*****@*****.**", "Διαχειριστής συστήματος διαχείρισης ηλεκτροφωτισμού"));
                obMsg.Subject = "Ενημέρωση για την εργασία "+_id+".";
                obMsg.IsBodyHtml = true;
                obMsg.Body = emailBody;
                ob.Send(obMsg);
            }
            catch (Exception ex)
            {
                string msg = ex.ToString();
            }
            // Send email report to system administrator
        }
Ejemplo n.º 36
0
        /// <summary>
        /// Executing API calls
        /// </summary>
        /// <param name="payLoad"></param>
        /// <param name="httpRequest"></param>
        /// <returns>A string containing the response from the remote host.</returns>
        public string Execute(string payLoad, HttpWebRequest httpRequest)
        {
            int retriesConfigured = config.ContainsKey(BaseConstants.HttpConnectionRetryConfig) ?
                   Convert.ToInt32(config[BaseConstants.HttpConnectionRetryConfig]) : 0;
            int retries = 0;

            // Reset the request & response details
            this.RequestDetails.Reset();
            this.ResponseDetails.Reset();

            // Store the request details
            this.RequestDetails.Body = payLoad;
            this.RequestDetails.Headers = httpRequest.Headers;
            this.RequestDetails.Url = httpRequest.RequestUri.AbsoluteUri;
            this.RequestDetails.Method = httpRequest.Method;

            try
            {
                do
                {
                    if (retries > 0)
                    {
                        logger.Info("Retrying....");
                        httpRequest = CopyRequest(httpRequest, config, httpRequest.RequestUri.ToString());
                        this.RequestDetails.RetryAttempts++;
                    }
                    try
                    {
                        switch (httpRequest.Method)
                        {
                            case "POST":
                            case "PUT":
                            case "PATCH":
                                using (StreamWriter writerStream = new StreamWriter(httpRequest.GetRequestStream()))
                                {
                                    writerStream.Write(payLoad);
                                    writerStream.Flush();
                                    writerStream.Close();

                                    if (ConfigManager.IsLiveModeEnabled(config))
                                    {
                                        logger.Debug("Request details are hidden in live mode.");
                                    }
                                    else
                                    {
                                        logger.Debug(payLoad);
                                    }
                                }
                                break;

                            default:
                                break;
                        }

                        using (WebResponse responseWeb = httpRequest.GetResponse())
                        {
                            // Store the response information
                            this.ResponseDetails.Headers = responseWeb.Headers;
                            if(responseWeb is HttpWebResponse)
                            {
                                this.ResponseDetails.StatusCode = ((HttpWebResponse)responseWeb).StatusCode;
                            }

                            using (StreamReader readerStream = new StreamReader(responseWeb.GetResponseStream()))
                            {
                                this.ResponseDetails.Body = readerStream.ReadToEnd().Trim();

                                if (ConfigManager.IsLiveModeEnabled(config))
                                {
                                    logger.Debug("Response details are hidden in live mode.");
                                }
                                else
                                {
                                    logger.Debug("Service response: ");
                                    logger.Debug(this.ResponseDetails.Body);
                                }
                                return this.ResponseDetails.Body;
                            }
                        }
                    }
                    catch (WebException ex)
                    {
                        // If provided, get and log the response from the remote host.
                        var response = string.Empty;
                        if (ex.Response != null)
                        {
                            using (var readerStream = new StreamReader(ex.Response.GetResponseStream()))
                            {
                                response = readerStream.ReadToEnd().Trim();
                                logger.Error("Error response:");
                                logger.Error(response);
                            }
                        }
                        logger.Error(ex.Message);

                        ConnectionException rethrowEx = null;

                        // Protocol errors indicate the remote host received the
                        // request, but responded with an error (usually a 4xx or
                        // 5xx error).
                        if (ex.Status == WebExceptionStatus.ProtocolError)
                        {
                            var httpWebResponse = (HttpWebResponse)ex.Response;

                            // If the HTTP status code is flagged as one where we
                            // should continue retrying, then ignore the exception
                            // and continue with the retry attempt.
                            if(httpWebResponse.StatusCode == HttpStatusCode.GatewayTimeout ||
                               httpWebResponse.StatusCode == HttpStatusCode.RequestTimeout ||
                               httpWebResponse.StatusCode == HttpStatusCode.BadGateway)
                            {
                                continue;
                            }

                            rethrowEx = new HttpException(ex.Message, response, httpWebResponse.StatusCode, ex.Status, httpWebResponse.Headers, httpRequest);
                        }
                        else if(ex.Status == WebExceptionStatus.ReceiveFailure ||
                                ex.Status == WebExceptionStatus.ConnectFailure ||
                                ex.Status == WebExceptionStatus.KeepAliveFailure)
                        {
                            logger.Debug("There was a problem connecting to the server: " + ex.Status.ToString());
                            continue;
                        }
                        else if (ex.Status == WebExceptionStatus.Timeout)
                        {
                            // For connection timeout errors, include the connection timeout value that was used.
                            var message = string.Format("{0} (HTTP request timeout was set to {1}ms)", ex.Message, httpRequest.Timeout);
                            rethrowEx = new ConnectionException(message, response, ex.Status, httpRequest);
                        }
                        else
                        {
                            // Non-protocol errors indicate something happened with the underlying connection to the server.
                            rethrowEx = new ConnectionException("Invalid HTTP response: " + ex.Message, response, ex.Status, httpRequest);
                        }

                        if(ex.Response != null && ex.Response is HttpWebResponse)
                        {
                            var httpWebResponse = ex.Response as HttpWebResponse;
                            this.ResponseDetails.StatusCode = httpWebResponse.StatusCode;
                            this.ResponseDetails.Headers = httpWebResponse.Headers;
                        }

                        this.ResponseDetails.Exception = rethrowEx;
                        throw rethrowEx;
                    }
                } while (retries++ < retriesConfigured);
            }
            catch (PayPalException)
            {
                // Rethrow any PayPalExceptions since they already contain the
                // details of the exception.
                throw;
            }
            catch (System.Exception ex)
            {
                // Repackage any other exceptions to give a bit more context to
                // the caller.
                throw new PayPalException("Exception in PayPal.HttpConnection.Execute(): " + ex.Message, ex);
            }

            // If we've gotten this far, it means all attempts at sending the
            // request resulted in a failed attempt.
            throw new PayPalException("Retried " + retriesConfigured + " times.... Exception in PayPal.HttpConnection.Execute(). Check log for more details.");
        }
Ejemplo n.º 37
0
        public static PythonRemoteDebugProcess Connect(PythonRemoteDebugPort port) {
            PythonRemoteDebugProcess process = null;

            // Connect to the remote debugging server and obtain process information. If any errors occur, display an error dialog, and keep
            // trying for as long as user clicks "Retry".
            while (true) {
                Stream stream = null;
                ConnectionException connEx = null;
                try {
                    // Process information is not sensitive, so ignore any SSL certificate errors, rather than bugging the user with warning dialogs.
                    stream = PythonRemoteProcess.Connect(port.Uri, false);
                } catch (ConnectionException ex) {
                    connEx = ex;
                }

                using (stream) {
                    if (stream != null) {
                        try {
                            stream.Write(PythonRemoteProcess.InfoCommandBytes);
                            int pid = stream.ReadInt32();
                            string exe = stream.ReadString();
                            string username = stream.ReadString();
                            string version = stream.ReadString();
                            process = new PythonRemoteDebugProcess(port, pid, exe, username, version);
                            break;
                        } catch (IOException ex) {
                            connEx = new ConnectionException(ConnErrorMessages.RemoteNetworkError, ex);
                        }
                    }

                    if (connEx != null) {
                        string errText;
                        switch (connEx.Error) {
                            case ConnErrorMessages.RemoteUnsupportedServer:
                                errText = string.Format("Remote server at {0} is not a Python Tools for Visual Studio remote debugging server, or its version is not supported.", port.Uri);
                                break;
                            case ConnErrorMessages.RemoteSecretMismatch:
                                errText = string.Format("Secret '{0}' did not match the server secret at {1}. Make sure that the secret is specified correctly in the Qualifier textbox, e.g. tcp://secret@localhost.",
                                    port.Uri.UserInfo, new UriBuilder(port.Uri) { UserName = null, Password = null }.Uri);
                                break;
                            case ConnErrorMessages.RemoteSslError:
                                // User has already got a warning dialog and clicked "Cancel" on that, so no further prompts are needed.
                                return null;
                            default:
                                {
                                    // Azure uses HTTP 503 (Service Unavailable) to indicate that websocket connections are not supported. Show a special error message for that.
                                    var wsEx = connEx.InnerException as WebSocketException;
                                    if (wsEx != null) {
                                        var webEx = wsEx.InnerException as WebException;
                                        if (webEx != null) {
                                            var httpResponse = webEx.Response as HttpWebResponse;
                                            if (httpResponse != null && httpResponse.StatusCode == HttpStatusCode.ServiceUnavailable) {
                                                errText = string.Format("Could not connect to remote Python process at {0}. Make sure that web sockets are enabled for the corresponding web site in Azure portal.", port.Uri);
                                                break;
                                            }
                                        }
                                    }

                                    errText = string.Format("Could not connect to remote Python process at {0}. Make sure that the process is running, and has called ptvsd.enable_attach().", port.Uri);
                                    for (var ex = connEx.InnerException; ex != null; ex = ex.InnerException) {
                                        if (ex.InnerException == null) {
                                            errText += "\r\n\r\nAdditional information:\r\n" + ex.Message;
                                        }
                                    }
                                    break;
                                }
                        }

                        DialogResult dlgRes = MessageBox.Show(errText, null, MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
                        if (dlgRes != DialogResult.Retry) {
                            break;
                        }
                    }
                }
            }

            return process;
        }
Ejemplo n.º 38
0
        protected override Exception ThrowExceptionHelper(DbConnection conn, DbCommand comm, Exception innerException)
        {
            if (innerException is SQLiteException)
            {
                SQLException sqlEx;

                var ex = innerException as SQLiteException;
            #if Mono
                var errorCode = ex.ErrorCode;
            #else
                var errorCode = ex.ResultCode;
            #endif
                switch (errorCode)
                {
                    case SQLiteErrorCode.Corrupt:
            #if Mono
                    case SQLiteErrorCode.NotADatabase:
            #else
                    case SQLiteErrorCode.NotADb:
            #endif
                    case SQLiteErrorCode.Perm:
            #if Mono
                    case SQLiteErrorCode.IOErr:
            #else
                    case SQLiteErrorCode.IoErr:
            #endif

                    case SQLiteErrorCode.CantOpen:
                    case SQLiteErrorCode.Full:
                    case SQLiteErrorCode.Auth:
                        {
                            return new FileAccessException(errorCode.ToString(), innerException);
                        }
                    case SQLiteErrorCode.ReadOnly:
                        {
                            sqlEx = new ReadOnlyException(null, innerException);
                            break;
                        }
                    case SQLiteErrorCode.Locked:
                        {
                            sqlEx = new ConnectionException("file is locked", ex);
                            break;
                        }
                    case SQLiteErrorCode.Constraint:
                        {
                            if (innerException.Message.IndexOf("UNIQUE constraint failed", StringComparison.OrdinalIgnoreCase) >= 0)
                            {
                                sqlEx = new UniqueConstraintException(null, innerException);
                            }
                            else
                            {
                                sqlEx = new ConstraintException(null, innerException);
                            }
                            break;
                        }
                    default:
                        {
                            sqlEx = new SQLException(null, innerException);
                            break;
                        }
                }
                if (conn != null)
                {
                    try
                    {
                        sqlEx.ConnectionString = conn.ConnectionString;
                        sqlEx.ConnectionState = conn.State.ToString();
                    }
                    catch (ObjectDisposedException)
                    {
                        sqlEx.ConnectionState = "Disposed";
                    }
                }
                if (comm != null)
                {
                    sqlEx.CommandText = comm.CommandText;
                    //newEx.Data.Add("CommandText", comm.CommandText);
                }

                return sqlEx;
            }
            else
            {
                return new ORMException(null, innerException);
            }
        }