Example #1
0
        private async void UploadProfilePictureBtn_OnClicked(object sender, EventArgs e)
        {
            (sender as Button).IsEnabled = false;

            Stream stream = await _photoPickerService.GetImageStreamAsync();

            if (stream != null)
            {
                UserImage.Source = ImageSource.FromStream(() => stream);

                byte[] userProfilePic = stream.ReadAllBytes();


                ClientUpdateRequest request = new ClientUpdateRequest();
                request.ProfilePicture = userProfilePic;
                if (await _clientService.Update <ClientModel>(APIService.LoggedUserId, request) != null)
                {
                    await LoadClientProfilePicture();

                    await Helper.LoadUserImage(_clientService, userImg);

                    await model.Init();
                    await DisplayAlert("Success", "Profile picture successfully added!", "OK");
                }
                else
                {
                    await DisplayAlert("Error", "Unexpected error has occured. Please try again later!", "OK");
                }
            }

            (sender as Button).IsEnabled = true;
        }
Example #2
0
        private async Task SetLoginPage(BanjoPage page)
        {
            using var managementClient = await _managementApiClientFactory.CreateAsync();

            var getClientsRequest = new GetClientsRequest
            {
                IsGlobal = true, Fields = "client_id,name", IncludeFields = true
            };
            var globalClients = managementClient.Clients.GetAllAsync(getClientsRequest, Reporter);
            var globalClient  = await globalClients.FirstOrDefaultAsync();

            if (globalClient == null)
            {
                throw new Auth0ResourceNotFoundException("No global client found.");
            }

            var clientUpdateRequest = new ClientUpdateRequest()
            {
                CustomLoginPage = page.Html, IsCustomLoginPageOn = true
            };

            await Update(async() =>
            {
                await managementClient.Clients.UpdateAsync(globalClient.ClientId, clientUpdateRequest);
                return(page);
            },
                         page.PageType.ToString());
        }
Example #3
0
 /// <summary>
 /// Updates a client application.
 /// </summary>
 /// <param name="id">The id of the client you want to update.</param>
 /// <param name="request">The request containing the properties of the client you want to update.</param>
 /// <returns>Task&lt;Core.Client&gt;.</returns>
 public Task <Client> UpdateAsync(string id, ClientUpdateRequest request)
 {
     return(Connection.PatchAsync <Client>("clients/{id}", request, new Dictionary <string, string>
     {
         { "id", id }
     }));
 }
Example #4
0
        public async Task Test_client_crud_sequence()
        {
            // Add a new client
            var newClientRequest = new ClientCreateRequest
            {
                Name = $"Integration testing {Guid.NewGuid():N}",
                TokenEndpointAuthMethod = TokenEndpointAuthMethod.ClientSecretPost,
                IsFirstParty            = true,
                ClientMetaData          = new
                {
                    Prop1 = "1",
                    Prop2 = "2"
                }
            };
            var newClientResponse = await _apiClient.Clients.CreateAsync(newClientRequest);

            newClientResponse.Should().NotBeNull();
            newClientResponse.Name.Should().Be(newClientRequest.Name);
            newClientResponse.TokenEndpointAuthMethod.Should().Be(TokenEndpointAuthMethod.ClientSecretPost);
            newClientResponse.ApplicationType.Should().Be(ClientApplicationType.Native);
            newClientResponse.IsFirstParty.Should().BeTrue();
            string prop1 = newClientResponse.ClientMetaData.Prop1;

            prop1.Should().Be("1");
            string prop2 = newClientResponse.ClientMetaData.Prop2;

            prop2.Should().Be("2");
            newClientResponse.GrantTypes.Should().HaveCount(i => i > 0);


            // Update the client
            var updateClientRequest = new ClientUpdateRequest
            {
                Name = $"Integration testing {Guid.NewGuid():N}",
                TokenEndpointAuthMethod = TokenEndpointAuthMethod.ClientSecretPost,
                ApplicationType         = ClientApplicationType.Spa,
                GrantTypes = new string[0]
            };
            var updateClientResponse = await _apiClient.Clients.UpdateAsync(newClientResponse.ClientId, updateClientRequest);

            updateClientResponse.Should().NotBeNull();
            updateClientResponse.Name.Should().Be(updateClientRequest.Name);
            updateClientResponse.TokenEndpointAuthMethod.Should().Be(TokenEndpointAuthMethod.ClientSecretPost);
            updateClientResponse.ApplicationType.Should().Be(ClientApplicationType.Spa);
            updateClientResponse.GrantTypes.Should().HaveCount(0);

            // Get a single client
            var client = await _apiClient.Clients.GetAsync(newClientResponse.ClientId);

            client.Should().NotBeNull();
            client.Name.Should().Be(updateClientResponse.Name);

            // Delete the client, and ensure we get exception when trying to fetch client again
            await _apiClient.Clients.DeleteAsync(client.ClientId);

            Func <Task> getFunc = async() => await _apiClient.Clients.GetAsync(client.ClientId);

            getFunc.Should().Throw <ApiException>().And.ApiError.ErrorCode.Should().Be("inexistent_client");
        }
Example #5
0
        public async Task Test_client_crud_sequence()
        {
            var scopes = new
            {
                clients = new
                {
                    actions = new string[] { "read", "create", "delete", "update" }
                },
                client_keys = new
                {
                    actions = new string[] { "read", "update" }
                }
            };
            string token = GenerateToken(scopes);

            var apiClient = new ManagementApiClient(token, new Uri(GetVariable("AUTH0_MANAGEMENT_API_URL")));

            // Get all clients
            var clientsBefore = await apiClient.Clients.GetAllAsync();

            // Add a new client
            var newClientRequest = new ClientCreateRequest
            {
                Name = $"Integration testing {Guid.NewGuid().ToString("N")}"
            };
            var newClientResponse = await apiClient.Clients.CreateAsync(newClientRequest);

            newClientResponse.Should().NotBeNull();
            newClientResponse.Name.Should().Be(newClientRequest.Name);

            // Get all clients again, and ensure we have one client more
            var clientsAfter = await apiClient.Clients.GetAllAsync();

            clientsAfter.Count.Should().Be(clientsBefore.Count + 1);

            // Update the client
            var updateClientRequest = new ClientUpdateRequest
            {
                Name = $"Integration testing {Guid.NewGuid().ToString("N")}"
            };
            var updateClientResponse = await apiClient.Clients.UpdateAsync(newClientResponse.ClientId, updateClientRequest);

            updateClientResponse.Should().NotBeNull();
            updateClientResponse.Name.Should().Be(updateClientRequest.Name);

            // Get a single client
            var client = await apiClient.Clients.GetAsync(newClientResponse.ClientId);

            client.Should().NotBeNull();
            client.Name.Should().Be(updateClientResponse.Name);

            // Delete the client, and ensure we get exception when trying to fetch client again
            await apiClient.Clients.DeleteAsync(client.ClientId);

            Func <Task> getFunc = async() => await apiClient.Clients.GetAsync(client.ClientId);

            getFunc.ShouldThrow <ApiException>().And.ApiError.ErrorCode.Should().Be("inexistent_client");
        }
Example #6
0
        public void Update(ClientUpdateRequest model)
        {
            using var db = new salesSystemContext();
            var client = db.Clients.Find(model.Id);

            // product.UpdatedAt = DateTime.Now;
            client.ClientName      = model.Name;
            client.UpdatedAt       = DateTime.Now;
            db.Entry(client).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
            db.SaveChanges();
        }
Example #7
0
        public async Task Test_client_crud_sequence()
        {
            var scopes = new
            {
                clients = new
                {
                    actions = new string[] { "read", "create", "delete", "update" }
                },
                client_keys = new
                {
                    actions = new string[] { "read", "update" }
                }
            };
            string token = GenerateToken(scopes);

            var apiClient = new ManagementApiClient(token, new Uri(GetVariable("AUTH0_MANAGEMENT_API_URL")));

            // Get all clients
            var clientsBefore = await apiClient.Clients.GetAllAsync();

            // Add a new client
            var newClientRequest = new ClientCreateRequest
            {
                Name = $"Integration testing {Guid.NewGuid().ToString("N")}"
            };
            var newClientResponse = await apiClient.Clients.CreateAsync(newClientRequest);
            newClientResponse.Should().NotBeNull();
            newClientResponse.Name.Should().Be(newClientRequest.Name);

            // Get all clients again, and ensure we have one client more
            var clientsAfter = await apiClient.Clients.GetAllAsync();
            clientsAfter.Count.Should().Be(clientsBefore.Count + 1);

            // Update the client
            var updateClientRequest = new ClientUpdateRequest
            {
                Name = $"Integration testing {Guid.NewGuid().ToString("N")}"
            };
            var updateClientResponse = await apiClient.Clients.UpdateAsync(newClientResponse.ClientId, updateClientRequest);
            updateClientResponse.Should().NotBeNull();
            updateClientResponse.Name.Should().Be(updateClientRequest.Name);

            // Get a single client
            var client = await apiClient.Clients.GetAsync(newClientResponse.ClientId);
            client.Should().NotBeNull();
            client.Name.Should().Be(updateClientResponse.Name);

            // Delete the client, and ensure we get exception when trying to fetch client again
            await apiClient.Clients.DeleteAsync(client.ClientId);
            Func<Task> getFunc = async () => await apiClient.Clients.GetAsync(client.ClientId);
            getFunc.ShouldThrow<ApiException>().And.ApiError.ErrorCode.Should().Be("inexistent_client");
        }
Example #8
0
    public async Task <IActionResult> PutClient(int id, ClientUpdateRequest request)
    {
        var client = await _context.Client.FindAsync(id);

        if (client == null)
        {
            return(NotFound());
        }

        client.Phone = request.Phone;
        client.Email = request.Email;
        client.Name  = request.Name;

        _context.Entry(client).State = EntityState.Modified;
        await _context.SaveChangesAsync();

        return(Ok());
    }
Example #9
0
        public async Task <IActionResult> ClientSave(ClientVM model)
        {
            if (model.ID != 0)
            {
                var request = new ClientUpdateRequest()
                {
                    FirstName        = model.FirstName,
                    LastName         = model.LastName,
                    Username         = model.Username,
                    Email            = model.Email,
                    Address          = model.LastName,
                    CreditCardNumber = model.CreditCardNumber
                };

                await _eventiApi.UpdateClientAsync(model.ID, request);
            }

            return(Redirect("/Administrator/Home/Index"));
        }
Example #10
0
        private async void btnSubmit_Click(object sender, EventArgs e)
        {
            if (ValidateChildren())
            {
                var cId = cmbCountry.SelectedValue;
                int.TryParse(cId.ToString(), out int countryId);

                var request = new ClientUpdateRequest
                {
                    CountryId     = countryId,
                    CleasPassword = txtPassword.Text,
                    Active        = true,
                    Address       = txtAddress.Text,
                    City          = txtCity.Text,
                    DateOfBirth   = dtpDateOfBirth.Value,
                    Email         = txtEmail.Text,
                    FirstName     = txtFirstName.Text,
                    LastName      = txtLastName.Text,
                    PhoneNumber   = txtPhone.Text,
                    Username      = txtUsername.Text
                };

                ClientModel clientModel = null;

                if (_clientId.HasValue && _countryId.HasValue && _personId.HasValue && _loginDataId.HasValue)
                {
                    clientModel = await _clientService.Update <ClientModel>(_clientId.Value, request);
                }


                if (clientModel != null)
                {
                    MessageBox.Show("Success!");
                    if (Form.ActiveForm != null)
                    {
                        Form.ActiveForm.Close();
                    }
                }
            }
        }
Example #11
0
        public IActionResult Edit(ClientUpdateRequest client, long id)
        {
            Response response = new Response();

            try
            {
                if (id != client.Id)
                {
                    throw new Exception("El id del cliente no es el mismo");
                }

                _updateService.Update(client);
                response.Success = true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

            return(Ok(response));
        }
Example #12
0
 /// <summary>
 /// Updates a client application.
 /// </summary>
 /// <param name="id">The id of the client you want to update.</param>
 /// <param name="request">The request containing the properties of the client you want to update.</param>
 /// <returns>Task&lt;Core.Client&gt;.</returns>
 public Task<Core.Client> UpdateAsync(string id, ClientUpdateRequest request)
 {
     return Connection.PatchAsync<Core.Client>("clients/{id}", request, new Dictionary<string, string>
     {
         {"id", id}
     });
 }
Example #13
0
        public async Task Test_client_crud_sequence()
        {
            // Add a new client
            var newClientRequest = new ClientCreateRequest
            {
                Name = $"Integration testing {MakeRandomName()}",
                TokenEndpointAuthMethod = TokenEndpointAuthMethod.ClientSecretPost,
                IsFirstParty            = true,
                ClientMetaData          = new
                {
                    Prop1 = "1",
                    Prop2 = "2"
                },
                InitiateLoginUri = "https://create.com/login",
                RefreshToken     = new RefreshToken
                {
                    ExpirationType = RefreshTokenExpirationType.NonExpiring,
                    RotationType   = RefreshTokenRotationType.NonRotating
                },
                OidcConformant              = true,
                GrantTypes                  = new[] { "refresh_token" },
                OrganizationUsage           = OrganizationUsage.Require,
                OrganizationRequireBehavior = OrganizationRequireBehavior.PreLoginPrompt
            };
            var newClientResponse = await _apiClient.Clients.CreateAsync(newClientRequest);

            newClientResponse.Should().NotBeNull();
            newClientResponse.Name.Should().Be(newClientRequest.Name);
            newClientResponse.TokenEndpointAuthMethod.Should().Be(TokenEndpointAuthMethod.ClientSecretPost);
            newClientResponse.ApplicationType.Should().Be(ClientApplicationType.Native);
            newClientResponse.IsFirstParty.Should().BeTrue();
            newClientResponse.RefreshToken.Should().NotBeNull();
            newClientResponse.RefreshToken.ExpirationType.Should().Be(newClientRequest.RefreshToken.ExpirationType);
            newClientResponse.RefreshToken.RotationType.Should().Be(newClientRequest.RefreshToken.RotationType);
            newClientResponse.OrganizationUsage.Should().Be(OrganizationUsage.Require);
            newClientResponse.OrganizationRequireBehavior.Should().Be(OrganizationRequireBehavior.PreLoginPrompt);

            string prop1 = newClientResponse.ClientMetaData.Prop1;

            prop1.Should().Be("1");
            string prop2 = newClientResponse.ClientMetaData.Prop2;

            prop2.Should().Be("2");
            newClientResponse.GrantTypes.Should().HaveCount(1);
            newClientResponse.InitiateLoginUri.Should().Be("https://create.com/login");

            // Update the client
            var updateClientRequest = new ClientUpdateRequest
            {
                Name = $"Integration testing {Guid.NewGuid():N}",
                TokenEndpointAuthMethod = TokenEndpointAuthMethod.ClientSecretPost,
                ApplicationType         = ClientApplicationType.Spa,
                GrantTypes       = new[] { "refresh_token", "authorization_code" },
                InitiateLoginUri = "https://update.com/login",
                RefreshToken     = new RefreshToken
                {
                    ExpirationType = RefreshTokenExpirationType.Expiring,
                    RotationType   = RefreshTokenRotationType.Rotating,
                    TokenLifetime  = 3600,
                    Leeway         = 1800
                },
                OrganizationRequireBehavior = OrganizationRequireBehavior.NoPrompt
            };
            var updateClientResponse = await _apiClient.Clients.UpdateAsync(newClientResponse.ClientId, updateClientRequest);

            updateClientResponse.Should().NotBeNull();
            updateClientResponse.Name.Should().Be(updateClientRequest.Name);
            updateClientResponse.TokenEndpointAuthMethod.Should().Be(TokenEndpointAuthMethod.ClientSecretPost);
            updateClientResponse.ApplicationType.Should().Be(ClientApplicationType.Spa);
            updateClientResponse.GrantTypes.Should().HaveCount(2);
            updateClientResponse.InitiateLoginUri.Should().Be("https://update.com/login");
            updateClientResponse.RefreshToken.Should().NotBeNull();
            updateClientResponse.RefreshToken.RotationType.Should().Be(updateClientRequest.RefreshToken.RotationType);
            updateClientResponse.RefreshToken.ExpirationType.Should().Be(updateClientRequest.RefreshToken.ExpirationType);
            updateClientResponse.RefreshToken.TokenLifetime.Should().Be(updateClientRequest.RefreshToken.TokenLifetime);
            updateClientResponse.RefreshToken.Leeway.Should().Be(updateClientRequest.RefreshToken.Leeway);
            updateClientResponse.OrganizationRequireBehavior.Should().Be(OrganizationRequireBehavior.NoPrompt);

            // Get a single client
            var client = await _apiClient.Clients.GetAsync(newClientResponse.ClientId);

            client.Should().NotBeNull();
            client.Name.Should().Be(updateClientResponse.Name);

            // Delete the client, and ensure we get exception when trying to fetch client again
            await _apiClient.Clients.DeleteAsync(client.ClientId);

            Func <Task> getFunc = async() => await _apiClient.Clients.GetAsync(client.ClientId);

            getFunc.Should().Throw <ErrorApiException>().And.ApiError.ErrorCode.Should().Be("inexistent_client");
        }
Example #14
0
 public Task <Core.Client> Update(string id, ClientUpdateRequest request)
 {
     return(UpdateAsync(id, request));
 }
Example #15
0
 public Task<Core.Client> Update(string id, ClientUpdateRequest request)
 {
     return UpdateAsync(id, request);
 }
        /// <summary>
        /// Update client details
        /// </summary>
        /// <param name="headerInfo"> </param>
        /// <param name="eventClient"> </param>
        public ClientUpdateResponse ClientUpdateFull(ClientUpdateRequest clientUpdateRequest)
        {
            var clientUpdateResponse = new ClientUpdateResponse();

            bool contractorSizeFirstTime = false;

            // Check if contractor size has been set before
            //
            var clientRead = RepClient.Read(clientUpdateRequest.eventClient.UID);

            if (clientRead.client.FKDocumentSetUID == 0)
            {
                contractorSizeFirstTime = true;
            }

            clientUpdateResponse.response = new ResponseStatus();

            // --------------------------------------------------------------
            // Check if user ID is already connected to a client
            // --------------------------------------------------------------

            //var checkLinkedUser = new Client(clientUpdateRequest.headerInfo)
            //{ FKUserID = clientUpdateRequest.eventClient.FKUserID };

            var checkLinkedUser = new Model.ModelClient.Client(clientUpdateRequest.headerInfo)
            {
                FKUserID = clientUpdateRequest.eventClient.FKUserID,
                UID      = clientUpdateRequest.eventClient.UID
            };

            if (!string.IsNullOrEmpty(checkLinkedUser.FKUserID))
            {
                var responseLinked = RepClient.ReadLinkedUser(checkLinkedUser);
                // var responseLinked = checkLinkedUser.ReadLinkedUser();

                if (responseLinked.ReturnCode == 0001 && responseLinked.ReasonCode == 0001)
                {
                    clientUpdateResponse.response =
                        new ResponseStatus()
                    {
                        ReturnCode = -0010, ReasonCode = 0001, Message = "User ID is already linked to another client."
                    };
                    return(clientUpdateResponse);
                }

                if (responseLinked.ReturnCode == 0001 && responseLinked.ReasonCode == 0003)
                {
                    // All good. User ID is connected to Client Supplied.
                    //
                }
            }


            using (var connection = new MySqlConnection(ConnString.ConnectionString))
            {
                using (var tr = new TransactionScope(TransactionScopeOption.Required))
                {
                    connection.Open();
                    var newClient = RepClient.Update(clientUpdateRequest.headerInfo, clientUpdateRequest.eventClient, connection);

                    //var responseClientUpdate = clientUpdateRequest.eventClient.Update();
                    var responseClientUpdate = newClient;

                    if (!responseClientUpdate.Successful)
                    {
                        // Rollback
                        tr.Dispose();

                        clientUpdateResponse.response = new ResponseStatus(MessageType.Error);

                        clientUpdateResponse.response.Message    = responseClientUpdate.Message;
                        clientUpdateResponse.response.ReturnCode = responseClientUpdate.ReturnCode;
                        clientUpdateResponse.response.ReasonCode = responseClientUpdate.ReasonCode;

                        return(clientUpdateResponse);
                    }
                    // -------------------------------------------
                    // Call method to add client extra information
                    // -------------------------------------------

                    var ceiRead = new RepClientExtraInformation(clientUpdateRequest.headerInfo);
                    ceiRead.FKClientUID = clientUpdateRequest.eventClient.UID;

                    // var ceiResponse = ceiRead.Read();

                    var ceiResponse = RepClientExtraInformation.Read(ceiRead);

                    if (ceiResponse.ReturnCode != 1)
                    {
                        // Rollback
                        tr.Dispose();

                        clientUpdateResponse.response = new ResponseStatus(MessageType.Error);
                        return(clientUpdateResponse);
                    }

                    // Return Code = 1, Reason Code = 2 means "Record not found"
                    //
                    if (ceiResponse.ReturnCode == 1 && ceiResponse.ReasonCode == 1)
                    {
                        clientUpdateRequest.eventClient.clientExtraInformation.RecordVersion = ceiRead.RecordVersion;

                        var cei = RepClientExtraInformation.Update(clientUpdateRequest.headerInfo,
                                                                   clientUpdateRequest.eventClient.
                                                                   clientExtraInformation,
                                                                   connection);

                        // var cei = clientUpdateRequest.eventClient.clientExtraInformation.Update();

                        if (!cei.Successful)
                        {
                            clientUpdateResponse.response = new ResponseStatus();
                            clientUpdateResponse.response = cei;
                            return(clientUpdateResponse);
                        }
                    }

                    // Return Code = 1, Reason Code = 2 means "Record not found"
                    //
                    if (ceiResponse.ReturnCode == 1 && ceiResponse.ReasonCode == 2)
                    {
                        // Create new record

                        // -------------------------------------------
                        // Call method to add client extra information
                        // -------------------------------------------
                        clientUpdateRequest.eventClient.clientExtraInformation.FKClientUID = clientUpdateRequest.eventClient.UID;
                        var cei = RepClientExtraInformation.Insert(
                            HeaderInfo.Instance,
                            clientUpdateRequest.eventClient.clientExtraInformation,
                            connection);

                        if (cei.ReturnCode != 1)
                        {
                            // Rollback transaction
                            //
                            tr.Dispose();

                            clientUpdateResponse.response = new ResponseStatus();
                            clientUpdateResponse.response = cei;
                            return(clientUpdateResponse);
                        }
                    }

                    //tr.Complete();

                    // If this is the first time the users sets the contractor size, add documents.
                    //
                    if (contractorSizeFirstTime)
                    {
                        // --------------------------------------------
                        // Add first document set
                        // --------------------------------------------
                        var cds = new ClientDocumentSet();
                        cds.FKClientUID = clientUpdateRequest.eventClient.UID;

                        // cds.FolderOnly = "CLIENT" + newClientUID.ToString().Trim().PadLeft(4, '0');
                        cds.FolderOnly = "CLIENT" + clientUpdateRequest.eventClient.UID.ToString().Trim().PadLeft(4, '0');

                        // cds.Folder = FCMConstant.SYSFOLDER.CLIENTFOLDER + "\\CLIENT" + newClientUID.ToString().Trim().PadLeft(4, '0');
                        cds.Folder = FCMConstant.SYSFOLDER.CLIENTFOLDER + @"\" + cds.FolderOnly;

                        cds.SourceFolder = FCMConstant.SYSFOLDER.TEMPLATEFOLDER;
                        // cds.Add( clientUpdateRequest.headerInfo, connection );
                        cds.Add(clientUpdateRequest.headerInfo);

                        // --------------------------------------------
                        // Apply initial document set
                        // --------------------------------------------
                        BUSClientDocument.AssociateDocumentsToClient(
                            clientDocumentSet: cds,
                            documentSetUID: clientUpdateRequest.eventClient.FKDocumentSetUID,
                            headerInfo: clientUpdateRequest.headerInfo);

                        // Fix Destination Folder Location
                        //
                        BUSClientDocumentGeneration.UpdateLocation(cds.FKClientUID, cds.ClientSetID);
                    }

                    SaveEmployees(clientUpdateRequest.eventClient.UID, clientUpdateRequest.eventClient.clientEmployee, clientUpdateRequest.headerInfo.UserID);
                }
            }

            return(clientUpdateResponse);
        }
Example #17
0
 public void Update(ClientUpdateRequest model)
 {
     _clientRepository.Update(model);
 }
Example #18
0
        private async void SaveChangesBtn_OnClicked(object sender, EventArgs e)
        {
            bool errorExists = false;

            //Check if entry is null or empty
            if (string.IsNullOrWhiteSpace(FirstNameEntry.Text) || string.IsNullOrWhiteSpace(LastNameEntry.Text) ||
                string.IsNullOrWhiteSpace(PhoneNumberEntry.Text) ||
                string.IsNullOrWhiteSpace(EmailEntry.Text) || string.IsNullOrWhiteSpace(AddressEntry.Text) ||
                string.IsNullOrWhiteSpace(CityEntry.Text) || string.IsNullOrWhiteSpace(PasswordEntry.Text) ||
                CountryPicker.SelectedItem == null)
            {
                errorExists = true;
                await DisplayAlert("Warning", "Please fill in all fields!", "OK");
            }


            //Password validation
            if (!errorExists)
            {
                bool   lowerCase = false, upperCase = false, numberExists = false;
                string charArr = PasswordEntry.Text;

                for (int i = 0; i < PasswordEntry.Text.Length; i++)
                {
                    if (charArr[i] >= 'A' && charArr[i] <= 'Z')
                    {
                        upperCase = true;
                    }
                    if (charArr[i] >= 'a' && charArr[i] <= 'z')
                    {
                        lowerCase = true;
                    }
                    if (charArr[i] >= 48 && charArr[i] <= 57)
                    {
                        numberExists = true;
                    }
                }

                if (!lowerCase || !upperCase || !numberExists)
                {
                    errorExists = true;
                    await DisplayAlert("Warning",
                                       "Password must be from 5-25 characters and must include A-a and Number!", "OK");
                }

                if (!errorExists && PasswordEntry.Text.Length < 5)
                {
                    errorExists = true;
                    await DisplayAlert("Warning",
                                       "Password must be from 5-25 characters and must include A-a and Number!", "OK");
                }
            }

            //Email validation
            if (!errorExists && !EmailEntry.Text.Contains("@"))
            {
                errorExists = true;
                await DisplayAlert("Warning", "Please enter valid email address!", "OK");
            }

            //Date of birth validation (18 < DoB < 1940 year)
            if (!errorExists)
            {
                var date = DateOfBirthEntry.Date.ToString("dd.MM.yyyy");
                int day, month, year;
                var dateParts = date.Split('.');
                day   = int.Parse(dateParts[0]);
                month = int.Parse(dateParts[1]);
                year  = int.Parse(dateParts[2]);

                int daysCount = 0;
                if ((DateTime.Today.Year - year) > 18)
                {
                    daysCount = ((DateTime.Today.Year - year) * 365) + (month * 30) + day;
                }
                if ((DateTime.Today.Year - year) == 18 && DateTime.Today.Month > month)
                {
                    daysCount = (18 * 365) + (month * 30) + day;
                }
                if ((DateTime.Today.Year - year) == 18 && DateTime.Today.Month == month && DateTime.Today.Day >= day)
                {
                    daysCount = (18 * 365) + (month * 30) + day;
                }
                if ((DateTime.Today.Year - year) == 18 && DateTime.Today.Month < month)
                {
                    daysCount = (17 * 365) + (month * 30) + day;
                }
                if ((DateTime.Today.Year - year) == 18 && DateTime.Today.Month == month && DateTime.Today.Day < day)
                {
                    daysCount = (17 * 365) + (month * 30) + day;
                }


                if (daysCount <= 6570 || year < 1940)
                {
                    errorExists = true;
                    await DisplayAlert("Warning", "You have to be over 18 to register or birth year under 1940!", "OK");
                }
            }

            //If everything valid
            if (!errorExists)
            {
                CountryModel selectedCountry = (CountryModel)CountryPicker.SelectedItem;

                ClientUpdateRequest request = new ClientUpdateRequest();
                request.Username         = UsernameEntry.Text;
                request.DateOfBirth      = DateOfBirthEntry.Date;
                request.Email            = EmailEntry.Text;
                request.Active           = true;
                request.FirstName        = FirstNameEntry.Text;
                request.LastName         = LastNameEntry.Text;
                request.PhoneNumber      = PhoneNumberEntry.Text;
                request.Address          = AddressEntry.Text;
                request.City             = CityEntry.Text;
                request.CleasPassword    = PasswordEntry.Text;
                request.RegistrationDate = RegistrationDateEntry.Date;
                request.CountryId        = selectedCountry.CountryId;

                var clientUpdated = await _clientService.Update <ClientModel>(APIService.LoggedUserId, request);

                //If success
                if (clientUpdated != null)
                {
                    await DisplayAlert("Success", "Successfully updated!", "OK");

                    EnableEditMode(false);
                    await model.Init();
                }
            }
        }
        /// <summary>
        /// Update client details
        /// </summary>
        /// <param name="headerInfo"> </param>
        /// <param name="eventClient"> </param>
        public ClientUpdateResponse ClientUpdate(ClientUpdateRequest clientUpdateRequest)
        {
            var clientUpdateResponse = new ClientUpdateResponse();

            clientUpdateResponse.response = new ResponseStatus();

            // --------------------------------------------------------------
            // Check if user ID is already connected to a client
            // --------------------------------------------------------------

            //var checkLinkedUser = new Client(clientUpdateRequest.headerInfo)
            //{ FKUserID = clientUpdateRequest.eventClient.FKUserID };

            var checkLinkedUser = new Model.ModelClient.Client(clientUpdateRequest.headerInfo)
            {
                FKUserID = clientUpdateRequest.eventClient.FKUserID,
                UID      = clientUpdateRequest.eventClient.UID
            };

            if (!string.IsNullOrEmpty(checkLinkedUser.FKUserID))
            {
                var responseLinked = RepClient.ReadLinkedUser(checkLinkedUser);
                // var responseLinked = checkLinkedUser.ReadLinkedUser();

                if (responseLinked.ReturnCode == 0001 && responseLinked.ReasonCode == 0001)
                {
                    clientUpdateResponse.response =
                        new ResponseStatus()
                    {
                        ReturnCode = -0010, ReasonCode = 0001, Message = "User ID is already linked to another client."
                    };
                    return(clientUpdateResponse);
                }

                if (responseLinked.ReturnCode == 0001 && responseLinked.ReasonCode == 0003)
                {
                    // All good. User ID is connected to Client Supplied.
                    //
                }
            }


            using (var connection = new MySqlConnection(ConnString.ConnectionString))
            {
                using (var tr = new TransactionScope(TransactionScopeOption.Required))
                {
                    connection.Open();
                    var newClient = RepClient.Update(clientUpdateRequest.headerInfo, clientUpdateRequest.eventClient, connection);

                    //var responseClientUpdate = clientUpdateRequest.eventClient.Update();
                    var responseClientUpdate = newClient;

                    if (!responseClientUpdate.Successful)
                    {
                        // Rollback
                        tr.Dispose();

                        clientUpdateResponse.response = new ResponseStatus(MessageType.Error);

                        clientUpdateResponse.response.Message    = responseClientUpdate.Message;
                        clientUpdateResponse.response.ReturnCode = responseClientUpdate.ReturnCode;
                        clientUpdateResponse.response.ReasonCode = responseClientUpdate.ReasonCode;

                        return(clientUpdateResponse);
                    }
                    // -------------------------------------------
                    // Call method to add client extra information
                    // -------------------------------------------

                    var ceiRead = new RepClientExtraInformation(clientUpdateRequest.headerInfo);
                    ceiRead.FKClientUID = clientUpdateRequest.eventClient.UID;

                    // var ceiResponse = ceiRead.Read();

                    var ceiResponse = RepClientExtraInformation.Read(ceiRead);

                    if (ceiResponse.ReturnCode != 1)
                    {
                        // Rollback
                        tr.Dispose();

                        clientUpdateResponse.response = new ResponseStatus(MessageType.Error);
                        return(clientUpdateResponse);
                    }

                    // Return Code = 1, Reason Code = 2 means "Record not found"
                    //
                    if (ceiResponse.ReturnCode == 1 && ceiResponse.ReasonCode == 1)
                    {
                        clientUpdateRequest.eventClient.clientExtraInformation.RecordVersion = ceiRead.RecordVersion;

                        var cei = RepClientExtraInformation.Update(clientUpdateRequest.headerInfo,
                                                                   clientUpdateRequest.eventClient.
                                                                   clientExtraInformation,
                                                                   connection);

                        // var cei = clientUpdateRequest.eventClient.clientExtraInformation.Update();

                        if (!cei.Successful)
                        {
                            clientUpdateResponse.response = new ResponseStatus();
                            clientUpdateResponse.response = cei;
                            return(clientUpdateResponse);
                        }
                    }

                    // Return Code = 1, Reason Code = 2 means "Record not found"
                    //
                    if (ceiResponse.ReturnCode == 1 && ceiResponse.ReasonCode == 2)
                    {
                        // Create new record

                        // -------------------------------------------
                        // Call method to add client extra information
                        // -------------------------------------------
                        clientUpdateRequest.eventClient.clientExtraInformation.FKClientUID = clientUpdateRequest.eventClient.UID;
                        var cei = RepClientExtraInformation.Insert(
                            HeaderInfo.Instance,
                            clientUpdateRequest.eventClient.clientExtraInformation,
                            connection);

                        if (cei.ReturnCode != 1)
                        {
                            // Rollback transaction
                            //
                            tr.Dispose();

                            clientUpdateResponse.response = new ResponseStatus();
                            clientUpdateResponse.response = cei;
                            return(clientUpdateResponse);
                        }
                    }

                    tr.Complete();
                }
            }

            return(clientUpdateResponse);
        }
Example #20
0
 /// <summary>
 /// Updates a client application.
 /// </summary>
 /// <param name="id">The id of the client you want to update.</param>
 /// <param name="request">The <see cref="ClientUpdateRequest"/> containing the properties of the client you want to update.</param>
 /// <returns>The <see cref="Client"/> that was updated.</returns>
 public Task <Client> UpdateAsync(string id, ClientUpdateRequest request)
 {
     return(Connection.SendAsync <Client>(new HttpMethod("PATCH"), BuildUri($"clients/{EncodePath(id)}"), request, DefaultHeaders));
 }
Example #21
0
        public async Task Register()
        {
            IsBusy = true;
            APIService.Username = "******";
            APIService.Password = "******";

            if (string.IsNullOrWhiteSpace(Username) || string.IsNullOrWhiteSpace(Address) || string.IsNullOrWhiteSpace(City) ||
                string.IsNullOrWhiteSpace(Password) || string.IsNullOrWhiteSpace(Username) || string.IsNullOrWhiteSpace(Email) ||
                string.IsNullOrWhiteSpace(FirstName) || string.IsNullOrWhiteSpace(LastName) || string.IsNullOrWhiteSpace(PhoneNumber) ||
                SelectedCountryModel == null)
            {
                await Application.Current.MainPage.DisplayAlert("Error", "Please fill in all fields!", "OK");

                IsBusy = false;
            }
            else if (!ValidateDoB(DateOfBirth))
            {
                await Application.Current.MainPage.DisplayAlert("Error", "You have to be over 18 and birth year higher than 1940 in order to register!", "OK");

                IsBusy = false;
            }
            else if (!ValidatePassword(Password))
            {
                await Application.Current.MainPage.DisplayAlert("Error", "Password must contain upper-lower case letters and digits!", "OK");

                IsBusy = false;
            }
            else if (!Email.Contains("@"))
            {
                await Application.Current.MainPage.DisplayAlert("Error", "Please input valid e-mail address!", "OK");

                IsBusy = false;
            }
            else
            {
                try
                {
                    ClientUpdateRequest request = new ClientUpdateRequest
                    {
                        Username         = Username,
                        Active           = true,
                        Address          = Address,
                        City             = City,
                        CleasPassword    = Password,
                        CountryId        = SelectedCountryModel.CountryId,
                        DateOfBirth      = DateOfBirth,
                        Email            = Email,
                        FirstName        = FirstName,
                        LastName         = LastName,
                        PhoneNumber      = PhoneNumber,
                        RegistrationDate = DateTime.Now
                    };
                    var obj = await _clientService.Insert <dynamic>(request);

                    if (obj == null)
                    {
                        await Application.Current.MainPage.DisplayAlert("Error",
                                                                        "Username or Email already exists, try another one!", "OK");

                        IsBusy = false;
                    }
                    else
                    {
                        await Application.Current.MainPage.DisplayAlert("Success!",
                                                                        "Your account has been successfully created!", "OK");

                        Application.Current.MainPage = new LoginPage();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                    IsBusy = false;
                }
            }
        }
Example #22
0
        public async Task Test_client_crud_sequence()
        {
            string token = await GenerateManagementApiToken();

            var apiClient = new ManagementApiClient(token, new Uri(GetVariable("AUTH0_MANAGEMENT_API_URL")));

            // Get all clients
            var clientsBefore = await apiClient.Clients.GetAllAsync();

            // Add a new client
            var newClientRequest = new ClientCreateRequest
            {
                Name = $"Integration testing {Guid.NewGuid().ToString("N")}",
                TokenEndpointAuthMethod = TokenEndpointAuthMethod.ClientSecretPost,
                IsFirstParty            = true,
                ClientMetaData          = new
                {
                    Prop1 = "1",
                    Prop2 = "2"
                }
            };
            var newClientResponse = await apiClient.Clients.CreateAsync(newClientRequest);

            newClientResponse.Should().NotBeNull();
            newClientResponse.Name.Should().Be(newClientRequest.Name);
            newClientResponse.TokenEndpointAuthMethod.Should().Be(TokenEndpointAuthMethod.ClientSecretPost);
            newClientResponse.ApplicationType.Should().Be(ClientApplicationType.Native);
            newClientResponse.IsFirstParty.Should().BeTrue();
            string prop1 = newClientResponse.ClientMetaData.Prop1;

            prop1.Should().Be("1");
            string prop2 = newClientResponse.ClientMetaData.Prop2;

            prop2.Should().Be("2");

            // Get all clients again, and ensure we have one client more
            var clientsAfter = await apiClient.Clients.GetAllAsync();

            clientsAfter.Count.Should().Be(clientsBefore.Count + 1);

            // Update the client
            var updateClientRequest = new ClientUpdateRequest
            {
                Name = $"Integration testing {Guid.NewGuid().ToString("N")}",
                TokenEndpointAuthMethod = TokenEndpointAuthMethod.ClientSecretPost,
                ApplicationType         = ClientApplicationType.Spa
            };
            var updateClientResponse = await apiClient.Clients.UpdateAsync(newClientResponse.ClientId, updateClientRequest);

            updateClientResponse.Should().NotBeNull();
            updateClientResponse.Name.Should().Be(updateClientRequest.Name);
            updateClientResponse.TokenEndpointAuthMethod.Should().Be(TokenEndpointAuthMethod.ClientSecretPost);
            updateClientResponse.ApplicationType.Should().Be(ClientApplicationType.Spa);

            // Get a single client
            var client = await apiClient.Clients.GetAsync(newClientResponse.ClientId);

            client.Should().NotBeNull();
            client.Name.Should().Be(updateClientResponse.Name);

            // Delete the client, and ensure we get exception when trying to fetch client again
            await apiClient.Clients.DeleteAsync(client.ClientId);

            Func <Task> getFunc = async() => await apiClient.Clients.GetAsync(client.ClientId);

            getFunc.ShouldThrow <ApiException>().And.ApiError.ErrorCode.Should().Be("inexistent_client");
        }
Example #23
0
        /// <summary>
        /// Add/ Update client
        /// </summary>
        /// <param name="client"></param>
        public void SaveClient()
        {
            if (cbxAssociateInitialSet.Checked)
            {
                if (comboContractorSize.SelectedIndex < 0)
                {
                    MessageBox.Show("Please select contractor size.");
                    return;
                }
            }


            // Check if the client is new.
            // If the UID is empty, it is a new client.
            // If the UID is populated, it is an existing client.
            //
            if (string.IsNullOrEmpty(txtUID.Text))
            {
                _client.UID = 0;
            }
            else
            {
                _client.UID = Convert.ToInt32(txtUID.Text);
            }

            _client.ABN                   = txtABN.Text;
            _client.Name                  = txtName.Text;
            _client.LegalName             = txtLegalName.Text;
            _client.Address               = txtAddress.Text;
            _client.Phone                 = txtPhone.Text;
            _client.Fax                   = txtFax.Text;
            _client.Mobile                = txtMobile.Text;
            _client.Logo1Location         = txtLogo1Location.Text;
            _client.Logo2Location         = "";
            _client.Logo3Location         = "";
            _client.EmailAddress          = txtEmailAddress.Text;
            _client.MainContactPersonName = txtContactPerson.Text;
            _client.FKUserID              = comboUserID.Text;
            _client.DocSetUIDDisplay      = comboContractorSize.Text;
            _client.DisplayLogo           = checkDisplayLogo.Checked ? 'Y' : 'N';

            if (string.IsNullOrEmpty(_client.DocSetUIDDisplay))
            {
                _client.FKDocumentSetUID = 0;
            }
            else
            {
                string[] part = _client.DocSetUIDDisplay.Split(';');
                _client.FKDocumentSetUID = Convert.ToInt32(part[0]);
            }

            _client.DisplayLogo = checkDisplayLogo.Checked ? 'Y' : 'N';

            _client.clientExtraInformation                         = new ClientExtraInformation();
            _client.clientExtraInformation.FKClientUID             = _client.UID;
            _client.clientExtraInformation.DateToEnterOnPolicies   = dtpDateToEnterOnPolicies.Value;
            _client.clientExtraInformation.ActionPlanDate          = dtpActionPlanDate.Value;
            _client.clientExtraInformation.CertificationTargetDate = dtpCertificationTargetDate.Value;

            _client.clientExtraInformation.ScopeOfServices              = txtScopeOfServices.Text;
            _client.clientExtraInformation.TimeTrading                  = txtTimeTrading.Text;
            _client.clientExtraInformation.RegionsOfOperation           = txtRegionsOfOperation.Text;
            _client.clientExtraInformation.OperationalMeetingsFrequency = txtOperationalMeetings.Text;
            _client.clientExtraInformation.ProjectMeetingsFrequency     = txtProjectMeetings.Text;

            // Check if it is to add / update
            if (_client.UID <= 0)
            {
                string associateInitialSet = "N";
                if (cbxAssociateInitialSet.Checked)
                {
                    associateInitialSet = "Y";
                }


                var clientAddRequest = new ClientAddRequest();
                clientAddRequest.headerInfo     = HeaderInfo.Instance;
                clientAddRequest.eventClient    = _client;
                clientAddRequest.linkInitialSet = associateInitialSet;

                // var response = new BUSClient().ClientAdd(clientAddRequest);
                var response = ClientAdd(clientAddRequest);

                ControllerUtils.ShowFCMMessage(response.responseStatus, Utils.UserID);

                _client.UID = 0;

                if (response.responseStatus.Successful)
                {
                    _client.UID           = response.clientUID;
                    txtUID.Text           = _client.UID.ToString();
                    txtRecordVersion.Text = _client.RecordVersion.ToString();
                }
            }
            else
            {
                var requestClientUpdate = new ClientUpdateRequest();
                requestClientUpdate.headerInfo  = HeaderInfo.Instance;
                requestClientUpdate.eventClient = _client;

                // var response = new BUSClient().ClientUpdate(requestClientUpdate);
                var response = ClientUpdate(requestClientUpdate);

                txtRecordVersion.Text = _client.RecordVersion.ToString(CultureInfo.InvariantCulture);

                ControllerUtils.ShowFCMMessage(response.response, Utils.UserID);
            }

            // Refresh client list
            //
            Utils.ClientID = _client.UID;

            var responseClientList = new BUSClient().ClientList(HeaderInfo.Instance);

            Utils.ClientList = responseClientList.clientList;
        }
Example #24
0
        public ClientUpdateResponse ClientUpdate(ClientUpdateRequest clientUpdateRequest)
        {
            var response = new BUSClient().ClientUpdate(clientUpdateRequest);

            return(response);
        }