Ejemplo n.º 1
0
        public async Task <Response> DeleteUser(Guid userId)
        {
            ValueResponse <object> response = new ValueResponse <object>
            {
                Status = ResponseStatus.Success
            };

            try
            {
                await m_repository.Delete(userId);
            }
            catch (MongoDB.Driver.MongoDuplicateKeyException dupEx)
            {
                response.Status  = ResponseStatus.Failure;
                response.Message = dupEx.ErrorMessage;
            }
            catch (MongoDB.Driver.MongoConnectionException conEx)
            {
                response.Status  = ResponseStatus.Failure;
                response.Message = $"Connection: {conEx.ConnectionId.LocalValue} Message: {conEx.Message}";
            }
            catch (Exception ex)
            {
                response.Status  = ResponseStatus.Failure;
                response.Message = ex.Message;
            }

            return(response);
        }
Ejemplo n.º 2
0
        public void updateComboBox(int ProjectId)
        {
            try
            {
                RestClient client = new RestClient();
                client.Method = httpVerb.GET;
                if (!string.IsNullOrEmpty(ConfigurationSettings.AppSettings["ServerPatch"]))
                {
                    client.ServiceUri = ConfigurationSettings.AppSettings["ServerPatch"];
                }
                client.ServiceUri += "Boards/" + ProjectId.ToString() + "/" + Global.LoggedUser.UserId; //W serwisie musiałaby być 0- to id projektu do którego board należy
                string response = client.getRequest();

                var rsponseLst = new ValueResponse <List <BoardPoco> >(true, string.Empty, null);
                rsponseLst = JsonConvert.DeserializeObject <ValueResponse <List <BoardPoco> > >(response);

                foreach (BoardPoco board in rsponseLst.Value)
                {
                    selectBoardBox.Items.Add(board.Name + "/" + board.BoardId.ToString());
                    BoardList.Add(board);
                }

                if (selectBoardBox.Items.Count >= 1)
                {
                    selectBoardBox.SelectedIndex = 0;
                }
            }
            catch (Exception e)
            {
                MessageWindow message = new MessageWindow(e.Message);
                message.Show();
            }
        }
Ejemplo n.º 3
0
        public async Task <ValueResponse <User> > LoadUser(string email)
        {
            ValueResponse <User> valueResponse = new ValueResponse <User>
            {
                Status = ResponseStatus.Success
            };

            User user = await m_repository.GetByEmail(email);

            valueResponse.Value  = user;
            valueResponse.Status = user == null ? ResponseStatus.Error : ResponseStatus.Success;
            return(valueResponse);
        }
Ejemplo n.º 4
0
        public async Task <ValueResponse <User> > LoadUser(Guid userId)
        {
            ValueResponse <User> valueResponse = new ValueResponse <User>
            {
                Status = ResponseStatus.Success
            };

            User user = await m_repository.Get(userId);

            valueResponse.Value  = user;
            valueResponse.Status = user == null ? ResponseStatus.Error : ResponseStatus.Success;
            return(valueResponse);
        }
Ejemplo n.º 5
0
        public IActionResult Post([FromBody] int value)
        {
            var valueResponse = new ValueResponse
            {
                Id    = value,
                Value = value.ToString()
            };

            this.values.Add(valueResponse);

            return(this.HATEOASResult(valueResponse,
                                      (v) => this.CreatedAtRoute(RouteNames.Values_GetById, new { id = value }, v)));
        }
Ejemplo n.º 6
0
        //TODO: Pending to remove
        public static async Task <IValueResponse <T> > ReadHttpContentAsync <T>(this HttpResponseMessage response)
        {
            var result = new ValueResponse <T> {
                IsSuccess = response.IsSuccessStatusCode
            };

            if (result.IsSuccess)
            {
                result.Value = await response.Content.ReadAsAsync <T>();
            }
            else
            {
                var tuple = response.ConvertResponseMessage();
                result.Title   = tuple.Item1;
                result.Message = tuple.Item2;
            }
            return(result);
        }
Ejemplo n.º 7
0
        protected Response ValidateInput <T>(T input, string objectName) where T : class
        {
            Response response = new ValueResponse <T> {
                Status = ResponseStatus.Success
            };

            if (input == null)
            {
                response.Status  = ResponseStatus.Error;
                response.Message = String.Format("ERROR: {0} is null.", objectName);
            }
            else if (EqualityComparer <T> .Default.Equals(input, default(T)))
            {
                response.Status  = ResponseStatus.Error;
                response.Message = String.Format("ERROR: {0} ({1}) is invalid.", objectName, input);
            }

            return(response);
        }
Ejemplo n.º 8
0
        public ValueResponse UpdateValue(string workspaceId, string entity, string value, UpdateValue body)
        {
            if (string.IsNullOrEmpty(workspaceId))
            {
                throw new ArgumentNullException(nameof(workspaceId));
            }
            if (string.IsNullOrEmpty(entity))
            {
                throw new ArgumentNullException(nameof(entity));
            }
            if (string.IsNullOrEmpty(value))
            {
                throw new ArgumentNullException(nameof(value));
            }
            if (body == null)
            {
                throw new ArgumentNullException(nameof(body));
            }

            if (string.IsNullOrEmpty(VersionDate))
            {
                throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
            }

            ValueResponse result = null;

            try
            {
                result = this.Client.WithAuthentication(this.UserName, this.Password)
                         .PostAsync($"{this.Endpoint}/v1/workspaces/{workspaceId}/entities/{entity}/values/{value}")
                         .WithArgument("version", VersionDate)
                         .WithBody <UpdateValue>(body)
                         .As <ValueResponse>()
                         .Result;
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }
Ejemplo n.º 9
0
        public void refresh()
        {
            RestClient client = new RestClient();

            client.Method = httpVerb.GET;

            if (!string.IsNullOrEmpty(ConfigurationSettings.AppSettings["ServerPatch"]))
            {
                client.ServiceUri = ConfigurationSettings.AppSettings["ServerPatch"];
            }
            client.ServiceUri += "Projects/1";           ///TODO: TUTAJ USTAWIĆ ORG ID JAK JUŻ BĘDZIE GLOBALNE
            string response = client.getRequest();

            if (response != null)
            {
                var rsponseLst = new ValueResponse <List <ProjectPoco> >(true, string.Empty, null);
                rsponseLst = JsonConvert.DeserializeObject <ValueResponse <List <ProjectPoco> > >(response);
                projectDataGrid.ItemsSource = rsponseLst.Value;
            }
        }
Ejemplo n.º 10
0
        public void GetUserGET()
        {
            RestClient client = new RestClient();

            client.Method = httpVerb.GET;
            if (!string.IsNullOrEmpty(ConfigurationSettings.AppSettings["ServerPatch"]))
            {
                client.ServiceUri = ConfigurationSettings.AppSettings["ServerPatch"];
            }
            client.ServiceUri += "Users/" + this.UserId.ToString(); //W serwisie musiałaby być 0- to id projektu do którego board należy
            string response = client.getRequest();

            if (response != null)
            {
                var rsponseUsr = new ValueResponse <UsersPoco>(true, string.Empty, null);
                rsponseUsr = JsonConvert.DeserializeObject <ValueResponse <UsersPoco> >(response);

                this.Name = rsponseUsr.Value.Name;
                this.Role = rsponseUsr.Value.Role;
            }
        }
Ejemplo n.º 11
0
        public async Task <ValueResponse <int> > SaveUser(User user)
        {
            Response validationResponse = ValidateInput(user, "User");

            ValueResponse <int> valueResponse = new ValueResponse <int>();

            valueResponse.Status  = validationResponse.Status;
            valueResponse.Message = validationResponse.Message;
            if (validationResponse.Status == ResponseStatus.Success)
            {
                try
                {
                    if (user.Id == Guid.Empty)
                    {
                        await m_repository.Create(user);
                    }
                    else
                    {
                        await m_repository.Update(user);
                    }
                }
                catch (MongoDB.Driver.MongoDuplicateKeyException dupEx)
                {
                    valueResponse.Status  = ResponseStatus.Failure;
                    valueResponse.Message = dupEx.ErrorMessage;
                }
                catch (MongoDB.Driver.MongoConnectionException conEx)
                {
                    valueResponse.Status  = ResponseStatus.Failure;
                    valueResponse.Message = $"Connection: {conEx.ConnectionId.LocalValue} Message: {conEx.Message}";
                }
                catch (Exception ex)
                {
                    valueResponse.Status  = ResponseStatus.Failure;
                    valueResponse.Message = ex.Message;
                }
            }
            return(valueResponse);
        }
Ejemplo n.º 12
0
        public async Task <IActionResult> Create([FromBody] AccountModel model,
                                                 [FromServices] IValidatorFactory validatorFactory,
                                                 [FromServices] ICreateAccountCommand createAccountCommand)
        {
            try
            {
                //Validate request
                if (model == null)
                {
                    return(BadRequest());
                }

                //Create account
                IValidator validator = validatorFactory.Create();
                string     accountId = await createAccountCommand.Execute(model, validator);

                //Return result
                if (validator.HasErrors)
                {
                    return(BadRequest(ValueResponse <string> .ValidationError(validator.Errors)));
                }
                else
                {
                    return(Created("", ValueResponse <string> .Success(accountId)));
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("AccountController.Create", "Exception occurred", new
                {
                    Exception    = ex,
                    AccountModel = model
                });
                return(BadRequest(ValueResponse <string> .GeneralError("Something went wrong")));
            }
        }
Ejemplo n.º 13
0
        public void loadTasks()
        {
            try
            {
                tasksGrid.Children.Clear();
                tasksGrid.RowDefinitions.Clear();
                tasksGrid.ColumnDefinitions.Clear();

                if (selectBoardBox.SelectedItem != null)
                {
                    string[] list = selectBoardBox.SelectedItem.ToString().Split('/');

                    if (list.Length >= 2)
                    {
                        BoardId = Convert.ToInt32(list[1]);
                    }

                    RestClient client = new RestClient();
                    client.Method = httpVerb.GET;
                    if (!string.IsNullOrEmpty(ConfigurationSettings.AppSettings["ServerPatch"]))
                    {
                        client.ServiceUri = ConfigurationSettings.AppSettings["ServerPatch"];
                    }
                    client.ServiceUri += "Tasks/" + BoardId;
                    string response = client.getRequest();

                    var taskList = new ValueResponse <List <TaskPoco> >(true, string.Empty, null);
                    taskList = JsonConvert.DeserializeObject <ValueResponse <List <TaskPoco> > >(response);

                    TaskBoardXY location = new TaskBoardXY();

                    for (int columnCount = 0; columnCount < 6; columnCount++)  //Ilość Kolumn tasków
                    {
                        ColumnDefinition colDef = new ColumnDefinition();
                        //colDef.Width = GridLength.Auto;

                        tasksGrid.ColumnDefinitions.Add(colDef);
                    }

                    foreach (TaskPoco task in taskList.Value)
                    {
                        TaskButton taskButton = new TaskButton(task);
                        taskButton.AddHandler(Button.ClickEvent, new RoutedEventHandler(openTaskWindow));

                        int dstRow = location.GetDestinationRow(task.TaskType);

                        Grid.SetColumn(taskButton, location.GetColumn(task.TaskType));
                        Grid.SetRow(taskButton, dstRow - 1);

                        tasksGrid.Children.Add(taskButton);
                    }

                    int rowsCount = location.GetMax();
                    for (int i = 0; i < rowsCount; i++)
                    {
                        RowDefinition rowDef = new RowDefinition();
                        rowDef.Height = GridLength.Auto;
                        tasksGrid.RowDefinitions.Add(rowDef);
                    }
                }
            }
            catch (Exception e)
            {
                MessageWindow message = new MessageWindow(e.Message);
                message.Show();
            }
        }
Ejemplo n.º 14
0
        public void GetAccess()
        {
            string ServiceUri = null;

            if (!string.IsNullOrEmpty(ConfigurationSettings.AppSettings["ServerPatch"]))
            {
                ServiceUri = ConfigurationSettings.AppSettings["ServerPatch"];
            }

            ServiceUri += "login";                      // TU DODAĆ ADRESS ROUTEA !!

            if (this.User != null && this.Pass != null) //Może sprawdzanie połączenia?
            {
                try
                {
                    string Json = JsonConvert.SerializeObject(this);
                    string info = string.Empty;

                    Debug.WriteLine(Json);

                    var httpWebRequest = (HttpWebRequest)WebRequest.Create(ServiceUri);
                    httpWebRequest.ContentType = "application/json";
                    httpWebRequest.Method      = "POST";



                    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                    {
                        streamWriter.Write(Json);
                    }

                    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                    {
                        var result = streamReader.ReadToEnd();
                        info = result.ToString();
                    }

                    if (info != null)  //Zapis tokena -Deserializacja
                    {
                        var response = new ValueResponse <TokenType>(true, string.Empty, null);
                        response = JsonConvert.DeserializeObject <ValueResponse <TokenType> >(info);

                        if (response.Succeeded)
                        {
                            Global.LoggedUser.AccessToken = response.Value.AccessToken;
                            Global.LoggedUser.UserId      = response.Value.UserId;
                            Global.LoggedUser.Login       = this.User;
                            Global.LoggedUser.Password    = this.Pass;
                            Global.LoggedUser.GetUserGET();
                            MessageWindow message = new MessageWindow("Zalogowano pomyślnie! \n Twoje Id: " + Global.LoggedUser.UserId.ToString());
                            message.Show();
                        }
                        else
                        {
                            MessageWindow message = new MessageWindow(response.Message);
                            message.Show();
                        }
                    }

                    httpResponse.Close();
                }
                catch (Exception e)
                {
                    MessageWindow messageWindow = new MessageWindow(e.Message);
                    messageWindow.Show();
                }
            }
        }
        public async Task <IActionResult> Renew([FromBody] RTokenRenewModel renewModel,
                                                [FromServices] IRequestClient <UserClaimsMQRequest> userClaimsReqClient,
                                                [FromServices] IGenerateRefreshTokenCommand generateRefreshTokenCommand,
                                                [FromServices] ITokenExtractor refreshTokenExtractor)
        {
            string correlationId = null;

            try
            {
                if (renewModel == null)
                {
                    return(BadRequest(ValueResponse <TokenResult> .GeneralError("Something went wrong")));
                }
                correlationId = Guid.NewGuid().ToString("N");

                //Old token verification and accountId retrieval goes here
                if (!refreshTokenExtractor.TryExractToken(renewModel.OldRToken, out List <Claim> oldClaims))
                {
                    return(BadRequest(ValueResponse <TokenResult> .GeneralError("Something went wrong")));
                }

                string accountId = oldClaims.Single(x => x.Type == "Account").Value;
                //Problem with dates
                DateTime expiredOld = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Unspecified).AddSeconds((long.Parse(oldClaims.Single(x => x.Type == "exp").Value)));

                //Get user and generate user claims
                Response <UserClaimsMQResponse> claimsResp = await userClaimsReqClient.GetResponse <UserClaimsMQResponse>(new UserClaimsMQRequest()
                {
                    CorrelationId   = correlationId,
                    AccountId       = accountId,
                    ClaimsConsumers = renewModel.ClaimsConsumers
                });

                if (claimsResp.Message.OpSuccess != true)
                {
                    throw new Exception("Error with userClaimsReqClient request");
                }

                //Generate refresh token
                var newClaims = claimsResp.Message.GetClaims();

                var req = ControllerContext.HttpContext.Request;
                TokenAdditionalData additionalData = new TokenAdditionalData()
                {
                    DeviceInfo    = "Device info",
                    RequesterIPv4 = "ipv4",
                    RequesterIPv6 = "ipv6"
                };

                TokenResult rTokenResult = await generateRefreshTokenCommand.Execute(accountId, newClaims, additionalData, expiredOld);

                return(Created("", rTokenResult));
            }
            catch (Exception ex)
            {
                //Log error
                _logger.LogError("RefreshTokenController.Renew", "Exception was thrown", new
                {
                    CorrelationId   = correlationId,
                    TokenRenewModel = renewModel,
                    Exception       = ex
                });

                return(BadRequest(ValueResponse <TokenResult> .GeneralError("Something went wrong")));
            }
        }