Exemple #1
0
        /// <summary>
        /// Generates an exception depending on the code of the error.
        /// </summary>
        /// <returns>An exception which can be thrown.</returns>
        public Exception GetException()
        {
            Exception exception;

            switch (Code)
            {
            /* Argument-Errors */
            case 0x30000010:
                exception = new ArgumentNullException(Message, InnerException?.GetException());
                break;

            case 0x30000011:
                exception = new ArgumentException(Message, InnerException?.GetException());
                break;

            case 0x30000012:
                exception = new ArgumentNullException(Data["PropertyName"], Message);
                break;

            /* Query-Errors */
            case 0x30000030:
                exception = new ConstraintException(Message, InnerException?.GetException());
                break;

            case 0x30000031:
            /* PasswordUpdate-Errors */
            case 0x000000A0:
                exception = new ObjectNotFoundException(Message, InnerException?.GetException());
                break;

            /* Security-Errors */
            case 0x30000070:
            case 0x30000071:
            case 0x30000072:
                exception = new SecurityException(Message, InnerException?.GetException());
                break;

            /* Login-Errors */
            case 0x30000080:
                exception = new InvalidCredentialException(Message, InnerException?.GetException());
                break;

            /* Registration-Errors */
            case 0x30000090:
                exception = new ArgumentException(Message, InnerException?.GetException());
                break;

            default:
                exception = new Exception(Message, InnerException?.GetException());
                break;
            }

            foreach (KeyValuePair <string, string> entry in Data)
            {
                exception.Data.Add(entry.Key, entry.Value);
            }

            exception.Data.Add("ErrorCode", Code);
            return(exception);
        }
        private static Task HandleExceptionAsync(HttpContext context, Exception ex, ILogger logger)
        {
            //   throw ex;
            var code = ex switch
            {
                NotFoundException _ => HttpStatusCode.NotFound,
                InvalidCredentialException _ => HttpStatusCode.Forbidden,
                AuthenticationException _ => HttpStatusCode.Unauthorized,
                InvalidStateException _ => HttpStatusCode.BadRequest,
                IllegalArgumentException _ => HttpStatusCode.BadRequest,
                _ => HttpStatusCode.InternalServerError
            };

            var logErrMsg = $"{ex.Message} - {context.Request.Path}{context.Request.QueryString}";

            if (code == HttpStatusCode.InternalServerError)
            {
                logger.LogError(logErrMsg);
            }
            else
            {
                logger.LogInformation(logErrMsg);
            }

            var result = JsonConvert.SerializeObject(new { error = ex.Message });

            context.Response.ContentType = "application/json";
            context.Response.StatusCode  = (int)code;
            return(context.Response.WriteAsync(result));
        }
    }
Exemple #3
0
        public void Constructor_String_PassedInMessageCorrect()
        {
            const string passedInMessage = "base was called";

            InvalidCredentialException invalidCredentialException = new InvalidCredentialException(passedInMessage);

            Assert.Equal(passedInMessage, invalidCredentialException.Message);
        }
        public void InvalidCredentialException_ReturnsDefaultErrorMessage()
        {
            // Act
            var error = new InvalidCredentialException();

            // Assert
            Assert.Equal("Invalid username or password. Please try again", error.Message);
            Assert.Equal(typeof(InvalidCredentialException), error.GetType());
        }
        public void InvalidCredentialException_ReturnsProvidedErrorMessage(string errorMessage)
        {
            // Act
            var error = new InvalidCredentialException(errorMessage);

            // Assert
            Assert.Equal(errorMessage, error.Message);
            Assert.Equal(typeof(InvalidCredentialException), error.GetType());
        }
Exemple #6
0
        public void Constructor_String_Exception_MessagesCorrect()
        {
            const string passedInMessage       = "base was called";
            const string innerExceptionMessage = "this is the inner exception message";

            InvalidCredentialException invalidCredentialException = new InvalidCredentialException(passedInMessage, new Exception(innerExceptionMessage));

            Assert.Equal(passedInMessage, invalidCredentialException.Message);
            Assert.Equal(innerExceptionMessage, invalidCredentialException.InnerException.Message);
        }
        //
        //  This is to reset auth state on the remote side.
        //  If this write succeeds we will allow auth retrying.
        //
        private void StartSendAuthResetSignal(LazyAsyncResult lazyResult, byte[] message, Exception exception)
        {
            _framer.WriteHeader.MessageId = FrameHeader.HandshakeErrId;

            Win32Exception win32exception = exception as Win32Exception;

            if (win32exception != null && win32exception.NativeErrorCode == (int)Interop.SecurityStatus.LogonDenied)
            {
                if (IsServer)
                {
                    exception = new InvalidCredentialException(SR.net_auth_bad_client_creds, exception);
                }
                else
                {
                    exception = new InvalidCredentialException(SR.net_auth_bad_client_creds_or_target_mismatch, exception);
                }
            }

            if (!(exception is AuthenticationException))
            {
                exception = new AuthenticationException(SR.net_auth_SSPI, exception);
            }

            if (lazyResult == null)
            {
                _framer.WriteMessage(message);
            }
            else
            {
                lazyResult.Result = exception;
                IAsyncResult ar = _framer.BeginWriteMessage(message, s_writeCallback, lazyResult);
                if (!ar.CompletedSynchronously)
                {
                    return;
                }

                _framer.EndWriteMessage(ar);
            }

            _canRetryAuthentication = true;
            throw exception;
        }
Exemple #8
0
        //
        //  This is to reset auth state on the remote side.
        //  If this write succeeds we will allow auth retrying.
        //
        private void StartSendAuthResetSignal(LazyAsyncResult lazyResult, byte[] message, Exception exception)
        {
            _framer.WriteHeader.MessageId = FrameHeader.HandshakeErrId;

            if (IsLogonDeniedException(exception))
            {
                if (IsServer)
                {
                    exception = new InvalidCredentialException(SR.net_auth_bad_client_creds, exception);
                }
                else
                {
                    exception = new InvalidCredentialException(SR.net_auth_bad_client_creds_or_target_mismatch, exception);
                }
            }

            if (!(exception is AuthenticationException))
            {
                exception = new AuthenticationException(SR.net_auth_SSPI, exception);
            }

            if (lazyResult == null)
            {
                _framer.WriteMessage(message);
            }
            else
            {
                lazyResult.Result = exception;
                IAsyncResult ar = _framer.BeginWriteMessage(message, s_writeCallback, lazyResult);
                if (!ar.CompletedSynchronously)
                {
                    return;
                }

                _framer.EndWriteMessage(ar);
            }

            _canRetryAuthentication = true;
            ExceptionDispatchInfo.Throw(exception);
        }
Exemple #9
0
        private Exception GetMostRelevantException(Exception ex)
        {
            Exception parentException = ex;

            while (parentException.InnerException != null && parentException is TargetInvocationException)
            {
                parentException = parentException.InnerException;
            }

            bool          isSoapException = parentException is SoapException;
            SoapException soapEx          = null;

            // Should this exception be wrapped?
            if (isSoapException && (soapEx = (SoapException)parentException).Detail.FirstChild.Name.EndsWith("invalidCredentialsFault"))
            {
                parentException = new InvalidCredentialException(parentException);
            }
            else if (isSoapException && soapEx.Detail.FirstChild.Name.EndsWith("exceededRequestLimitFault"))
            {
                parentException = new ConcurrentSessionException(parentException);
            }
            return(parentException);
        }
Exemple #10
0
        private void StartSendAuthResetSignal(LazyAsyncResult lazyResult, byte[] message, Exception exception)
        {
            this._Framer.WriteHeader.MessageId = 0x15;
            Win32Exception exception2 = exception as Win32Exception;

            if ((exception2 != null) && (exception2.NativeErrorCode == -2146893044))
            {
                if (this.IsServer)
                {
                    exception = new InvalidCredentialException(SR.GetString("net_auth_bad_client_creds"), exception);
                }
                else
                {
                    exception = new InvalidCredentialException(SR.GetString("net_auth_bad_client_creds_or_target_mismatch"), exception);
                }
            }
            if (!(exception is AuthenticationException))
            {
                exception = new AuthenticationException(SR.GetString("net_auth_SSPI"), exception);
            }
            if (lazyResult == null)
            {
                this._Framer.WriteMessage(message);
            }
            else
            {
                lazyResult.Result = exception;
                IAsyncResult asyncResult = this._Framer.BeginWriteMessage(message, _WriteCallback, lazyResult);
                if (!asyncResult.CompletedSynchronously)
                {
                    return;
                }
                this._Framer.EndWriteMessage(asyncResult);
            }
            this._CanRetryAuthentication = true;
            throw exception;
        }
Exemple #11
0
        public void Constructor_NoParameter_DefaultMessageIsNotNull()
        {
            InvalidCredentialException invalidCredentialException = new InvalidCredentialException();

            Assert.NotNull(invalidCredentialException.Message);
        }
        public void TestExceptions()
        {
            {
                AlreadyExistsException v1 = new AlreadyExistsException("ex");
                AlreadyExistsException v2 = (AlreadyExistsException)CloneObject(v1);
                Assert.AreEqual("ex", v2.Message);
            }

            {
                ConfigurationException v1 = new ConfigurationException("ex");
                ConfigurationException v2 = (ConfigurationException)CloneObject(v1);
                Assert.AreEqual("ex", v2.Message);
            }

            {
                ConnectionBrokenException v1 = new ConnectionBrokenException("ex");
                ConnectionBrokenException v2 = (ConnectionBrokenException)CloneObject(v1);
                Assert.AreEqual("ex", v2.Message);
            }

            {
                ConnectionFailedException v1 = new ConnectionFailedException("ex");
                ConnectionFailedException v2 = (ConnectionFailedException)CloneObject(v1);
                Assert.AreEqual("ex", v2.Message);
            }

            {
                ConnectorException v1 = new ConnectorException("ex");
                ConnectorException v2 = (ConnectorException)CloneObject(v1);
                Assert.AreEqual("ex", v2.Message);
            }
            {
                ConnectorIOException v1 = new ConnectorIOException("ex");
                ConnectorIOException v2 = (ConnectorIOException)CloneObject(v1);
                Assert.AreEqual("ex", v2.Message);
            }
            {
                ConnectorSecurityException v1 = new ConnectorSecurityException("ex");
                ConnectorSecurityException v2 = (ConnectorSecurityException)CloneObject(v1);
                Assert.AreEqual("ex", v2.Message);
            }

            {
                InvalidCredentialException v1 = new InvalidCredentialException("ex");
                InvalidCredentialException v2 = (InvalidCredentialException)CloneObject(v1);
                Assert.AreEqual("ex", v2.Message);
            }

            {
                InvalidPasswordException v1 = new InvalidPasswordException("ex");
                InvalidPasswordException v2 = (InvalidPasswordException)CloneObject(v1);
                Assert.AreEqual("ex", v2.Message);
            }

            {
                PasswordExpiredException v1 = new PasswordExpiredException("ex");
                v1.Uid = (new Uid("myuid"));
                PasswordExpiredException v2 = (PasswordExpiredException)CloneObject(v1);
                Assert.AreEqual("ex", v2.Message);
                Assert.AreEqual("myuid", v2.Uid.GetUidValue());
            }

            {
                OperationTimeoutException v1 = new OperationTimeoutException("ex");
                OperationTimeoutException v2 = (OperationTimeoutException)CloneObject(v1);
                Assert.AreEqual("ex", v2.Message);
            }

            {
                PermissionDeniedException v1 = new PermissionDeniedException("ex");
                PermissionDeniedException v2 = (PermissionDeniedException)CloneObject(v1);
                Assert.AreEqual("ex", v2.Message);
            }

            {
                UnknownUidException v1 = new UnknownUidException("ex");
                UnknownUidException v2 = (UnknownUidException)CloneObject(v1);
                Assert.AreEqual("ex", v2.Message);
            }

            {
                ArgumentException v1 = new ArgumentException("my msg");
                ArgumentException v2 = (ArgumentException)CloneObject(v1);
                Assert.AreEqual("my msg", v2.Message);
            }

            {
                ArgumentNullException v1 = new ArgumentNullException(null, "my msg 1");
                ArgumentException     v2 = (ArgumentException)CloneObject(v1);
                Assert.AreEqual("my msg 1", v2.Message);
            }

            {
                Exception v1 = new Exception("my msg2");
                Exception v2 = (Exception)CloneObject(v1);
                Assert.AreEqual("my msg2", v2.Message);
            }
        }
        /// <summary>
        /// Connects this bot to Slack using the slack API key provided. Set yours up at https://yourteam.slack.com/apps/manage.
        /// </summary>
        /// <param name="slackKey">The API key the bot will use to identify itself to the Slack API.</param>
        public async Task Connect(string slackKey)
        {
            SlackKey = slackKey;

            // disconnect in case we're already connected like a crazy person
            Disconnect();

            // kill the regex for our bot's name - we'll rebuild it upon request with some of the info we get here
            BotNameRegex = string.Empty;

            // start session and get response
            var httpClient = new HttpClient();
            var json       = await httpClient.GetStringAsync($"https://slack.com/api/rtm.start?token={SlackKey}");

            var jData = JObject.Parse(json);

            // Handle exceptions.

            if (!jData["ok"].Value <bool>())
            {
                var errorMessage = jData["ok"].Value <string>();
                switch (errorMessage)
                {
                case "not_authed":
                case "account_inactive":
                case "invalid_auth":
                    InvalidCredentialException exIC = new InvalidCredentialException(errorMessage);
                    exIC.HelpLink = SlackRtmStartHelp;
                    throw exIC;

                case "invalid_arg_name":
                case "invalid_array_arg":
                case "invalid_charset":
                case "invalid_form_data":
                case "invalid_post_type":
                case "missing_post_type":
                    ArgumentException exAE = new ArgumentException(errorMessage);
                    exAE.HelpLink = SlackRtmStartHelp;
                    throw exAE;

                case "request_timeout":
                    TimeoutException exTE = new TimeoutException(errorMessage);
                    exTE.HelpLink = SlackRtmStartHelp;
                    throw exTE;

                default:
                    throw new Exception(errorMessage);
                }
            }

            // read various bot properties out of the response
            TeamID   = jData["team"]["id"].Value <string>();
            TeamName = jData["team"]["name"].Value <string>();
            UserID   = jData["self"]["id"].Value <string>();
            UserName = jData["self"]["name"].Value <string>();
            var webSocketUrl = jData["url"].Value <string>();

            // rebuild the username cache
            UserNameCache.Clear();
            foreach (JObject userObject in jData["users"])
            {
                UserNameCache.Add(userObject["id"].Value <string>(), userObject["name"].Value <string>());
            }

            // load the channels, groups, and DMs that margie's in
            Dictionary <string, SlackChatHub> hubs = new Dictionary <string, SlackChatHub>();

            ConnectedHubs = hubs;

            // channelz
            if (jData["channels"] != null)
            {
                foreach (JObject channelData in jData["channels"])
                {
                    if (!channelData["is_archived"].Value <bool>() && channelData["is_member"].Value <bool>())
                    {
                        var channel = new SlackChatHub()
                        {
                            ID   = channelData["id"].Value <string>(),
                            Name = "#" + channelData["name"].Value <string>(),
                            Type = SlackChatHubType.Channel
                        };
                        hubs.Add(channel.ID, channel);
                    }
                }
            }

            // groupz
            if (jData["groups"] != null)
            {
                foreach (JObject groupData in jData["groups"])
                {
                    if (!groupData["is_archived"].Value <bool>() && groupData["members"].Values <string>().Contains(UserID))
                    {
                        var group = new SlackChatHub()
                        {
                            ID   = groupData["id"].Value <string>(),
                            Name = groupData["name"].Value <string>(),
                            Type = SlackChatHubType.Group
                        };
                        hubs.Add(group.ID, group);
                    }
                }
            }

            // dmz
            if (jData["ims"] != null)
            {
                foreach (JObject dmData in jData["ims"])
                {
                    var userID = dmData["user"].Value <string>();
                    var dm     = new SlackChatHub()
                    {
                        ID   = dmData["id"].Value <string>(),
                        Name = "@" + (UserNameCache.ContainsKey(userID) ? UserNameCache[userID] : userID),
                        Type = SlackChatHubType.DM
                    };
                    hubs.Add(dm.ID, dm);
                }
            }

            // set up the websocket
            WebSocket         = new MargieBotWebSocket();
            WebSocket.OnOpen += (object sender, EventArgs e) =>
            {
                // set connection-related properties
                ConnectedSince = DateTime.Now;
            };
            WebSocket.OnMessage += async(object sender, string message) =>
            {
                await ListenTo(message);
            };
            WebSocket.OnClose += (object sender, EventArgs e) =>
            {
                // set connection-related properties
                ConnectedSince = null;
                TeamID         = null;
                TeamName       = null;
                UserID         = null;
                UserName       = null;
            };

            // connect
            await WebSocket.Connect(webSocketUrl);
        }
Exemple #14
0
        public async Task <ResponseWrapper> SendAsync(string restRelativeUri, string queryParams, RequestType requestType, string data, bool allowReconnect = true, RequestConfiguration additionalRequestConfiguration = null)
        {
            if (!IsConnected())
            {
                throw new NotConnectedException();
            }

            restRelativeUri = string.IsNullOrWhiteSpace(queryParams) ? restRelativeUri : restRelativeUri + (restRelativeUri.Contains("?") ? "&" : "?") + queryParams;
            HttpWebRequest request = CreateRequest(restRelativeUri, requestType, additionalRequestConfiguration);

            if ((requestType == RequestType.Post || requestType == RequestType.Update) && !string.IsNullOrEmpty(data))
            {
                byte[] byteData = Encoding.UTF8.GetBytes(data);
                bool   gzip     = additionalRequestConfiguration != null && additionalRequestConfiguration.GZipCompression;
                if (gzip)
                {
                    using (Stream postStream = await request.GetRequestStreamAsync().ConfigureAwait(AwaitContinueOnCapturedContext))
                    {
                        using (var zipStream = new GZipStream(postStream, CompressionMode.Compress))
                        {
                            zipStream.Write(byteData, 0, byteData.Length);
                        }
                    }
                }
                else
                {
                    request.ContentLength = byteData.Length;
                    using (Stream postStream = await request.GetRequestStreamAsync().ConfigureAwait(AwaitContinueOnCapturedContext))
                    {
                        postStream.Write(byteData, 0, byteData.Length);
                    }
                }
            }

            InvalidCredentialException originalException = null;

            try
            {
                if (requestType == RequestType.GetOctet && additionalRequestConfiguration != null)
                {
                    return(await DownloadAttachmentInternalAsync(request, additionalRequestConfiguration.AttachmentDownloadPath).ConfigureAwait(AwaitContinueOnCapturedContext));
                }
                else
                {
                    return(await DoSendAsync(request).ConfigureAwait(AwaitContinueOnCapturedContext));
                }
            }
            //catch - intended to handle the case LWSSO is expired, we will try reconnect and resend original request
            catch (InvalidCredentialException e)
            {
                // await can't exist in a catch because the CLR would lose the ambient exception.
                // We don’t need the ambient exception (i.e. we don't "throw;",
                // so we need to trick it out by putting retry logic after the catch
                originalException = e;
            }

            //RECONNECT SECTION
            try
            {
                bool reconnected = allowReconnect && await Reconnect();

                if (!reconnected)
                {
                    throw originalException;
                }
                // we reconnected,
                // but await can't exist in a catch because the CLR would lose the ambient exception.
                // We don’t need the ambient exception (i.e. we don't "throw;",
                // so we need to trick it out by putting retry logic after the catch
            }
            catch
            {
                //if reconnect throwed any exception - we rethrow original exception
                throw originalException;
            }

            //resend after reconnect
            return(await SendAsync(restRelativeUri, queryParams, requestType, data, false, additionalRequestConfiguration)
                   .ConfigureAwait(AwaitContinueOnCapturedContext));
        }