Esempio n. 1
0
        public async Task <TenantDto> PutTenant(int id, TenantDto model)
        {
            var url    = CRMApiUri + "/Tenant/" + id;
            var result = await PutRequestToApi(url, model);

            return(result);
        }
Esempio n. 2
0
        public async Task <TenantDto> PostTenant(TenantDto model)
        {
            var url    = CRMApiUri + "/Tenant";
            var result = await PostRequestToApi(url, model);

            return(result);
        }
        public async Task <int> Create(TenantDto tenantDto)
        {
            int tenantId = await _tenantManager.Create(_mapper.Map <Tenant>(tenantDto));

            _userSession.TenantId = tenantId;

            try
            {
                IdentityResult userCreationResult = await _userManager.CreateAsync(new User
                {
                    UserName       = "******" + "-" + _userSession.TenantId.ToString(),
                    Email          = tenantDto.Email,
                    EmailConfirmed = true,
                }, "123@Qwe");

                if (!userCreationResult.Succeeded)
                {
                    throw new Exception("Error creating Tenant admin user. " + userCreationResult.Errors);
                }

                return(tenantId);
            }
            catch (Exception ex)
            {
                throw new Exception("Error creating Tenant admin user. " + ex.Message);
            }
        }
Esempio n. 4
0
        public async Task <TenantDto> GetById(int id)
        {
            try
            {
                if (id > 0)
                {
                    var tenantObj = await _dbContext.TenantPersonnels.Where(s => s.Id == id).Include(s => s.GenderFk).FirstOrDefaultAsync();

                    var tenant = new TenantDto
                    {
                        FirstName  = tenantObj.FirstName,
                        LastName   = tenantObj.LastName,
                        MiddleName = tenantObj.MiddleName,
                        Active     = tenantObj.Active,
                        DOB        = tenantObj.DOB,
                        GenderFk   = tenantObj.GenderFk,
                        PrefixId   = tenantObj.PrefixId,
                        NickName   = tenantObj.NickName,
                        TenantId   = tenantObj.TenantId
                    };
                    return(tenant);
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public async Task <IActionResult> Put(Guid id, [FromBody] TenantDto tenantDto)
        {
            if (tenantDto == null)
            {
                return(InvalidRequestBodyJson(nameof(TenantDto)));
            }
            if (id.ToString() != tenantDto.Id)
            {
                return(BadRequest("Conflicting or missing tenant id in model data versus the URL"));
            }
            if (tenantDto.PrimaryContact == null)
            {
                AddErrors(new[] { "Model must have contact information defined" });
                return(BadRequest());
            }
            if (tenantDto.ServiceDetails == null)
            {
                AddErrors(new[] { "Model must have service information defined" });
                return(BadRequest(ModelState));
            }
            var tenant = await _tenantService.GetAsync(id);

            Mapper.Map(tenantDto, tenant, typeof(TenantDto), typeof(Tenant));

            await _tenantService.UpdateAsync(tenant);

            return(NoContent());
        }
Esempio n. 6
0
        //public void OnAuthorization(AuthorizationFilterContext context)
        //{
        //    var sub = context.HttpContext.User.Claims.FirstOrDefault(c => "sub".Equals(c.Type));
        //    var request = context.ActionDescriptor.Parameters;
        //    if (sub is null)
        //    {
        //        context.Result = new ForbidResult();
        //    }
        //}

        public void OnActionExecuting(ActionExecutingContext context)
        {
            // do something before the action executes
            var sub   = context.HttpContext.User.Claims.FirstOrDefault(c => "sub".Equals(c.Type));
            var email = context.HttpContext.User.Claims.FirstOrDefault(c => "email".Equals(c.Type)).Value;

            context.ActionArguments.TryGetValue("tenantId", out object tenantId);
            context.ActionArguments.TryGetValue("officeId", out object officeId);
            context.HttpContext.Request.Headers.TryGetValue("User-Agent", out StringValues browser);
            var request = context.HttpContext.Request.Path;

            if (sub == null)
            {
                context.Result = new ForbidResult();
            }
            if (email == null)
            {
                context.Result = new ForbidResult();
            }
            UserDto   currentUser   = null;
            TenantDto currentTenant = null;
            OfficeDto currentOffice = null;
            RoleDto   currentRole   = null;
            var       user          = _userService.GetUserByEmail(email).Result;

            if (user == null)
            {
                currentUser = _userService.CreateInitialUser(new UserDto {
                    Email = email, Name = email, LastSeenOn = DateTime.Now, LastBrowser = browser, LastIp = context.HttpContext.Connection.RemoteIpAddress.ToString()
                }).Result;
            }
            else
            {
                user.LastBrowser = browser;
                user.LastIp      = context.HttpContext.Connection.RemoteIpAddress.ToString();
                user.LastSeenOn  = DateTime.Now;
                currentUser      = _userService.UpdateContextUser(user).Result;
            }
            if (tenantId != null)
            {
                currentTenant = _userService.GetTenant(tenantId.ToString()).Result;
            }
            if (officeId != null)
            {
                currentOffice = currentUser.Offices.FirstOrDefault(o => o.Id == Guid.Parse(officeId.ToString()));
            }
            if (currentTenant == null && currentOffice != null)
            {
                currentTenant = _userService.GetTenant(currentOffice.TenantId.ToString()).Result;
            }
            if (currentOffice != null)
            {
                currentRole = currentUser.Roles.FirstOrDefault(r => r.OfficeId == currentOffice.Id);
            }

            _authContext.CurrentUser   = currentUser;
            _authContext.CurrentTenant = currentTenant;
            _authContext.CurrentOffice = currentOffice;
            _authContext.CurrentRole   = currentRole;
        }
Esempio n. 7
0
 /// <summary>
 /// Creates a tenant.
 /// </summary>
 /// <remarks>
 /// Client Credentials Flow required permissions: Administration or
 /// Administration.Write.
 ///
 /// Host only. Requires authentication.
 /// </remarks>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='body'>
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <TenantDto> PostAsync(this ITenants operations, TenantDto body = default(TenantDto), CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.PostWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Esempio n. 8
0
        public static void MappTenantDto(this Tenant tenant, TenantDto tenantDto)
        {
            //tenant.Id = tenantDto.Id;
            tenant.TenantCode       = tenantDto.TenantCode;
            tenant.TenantName       = tenantDto.TenantName;
            tenant.RegistrationDate = tenantDto.RegistrationDate;
            tenant.CurrencyCode     = tenantDto.CurrencyCode;
            tenant.AddressLine1     = tenantDto.AddressLine1;
            tenant.AddressLine2     = tenantDto.AddressLine2;
            tenant.Street           = tenantDto.Street;
            tenant.State            = tenantDto.State;
            tenant.City             = tenantDto.City;
            tenant.ZipCode          = tenantDto.ZipCode;
            tenant.Country          = tenantDto.Country;
            tenant.Phone            = tenantDto.Phone;
            tenant.Fax   = tenantDto.Fax;
            tenant.Email = tenantDto.Email;
            tenant.Url   = tenantDto.Url;
            tenant.Logo  = tenantDto.Logo;
            tenant.RegistrationNumber = tenantDto.RegistrationNumber;

            tenant.CreatedByUserId = tenantDto.CreatedByUserId;
            tenant.CreatedOn       = tenantDto.CreatedOn;
            tenant.UpdatedByUserId = tenantDto.UpdatedByUserId;
            tenant.UpdatedOn       = tenantDto.UpdatedOn;
        }
Esempio n. 9
0
        public async Task <TenantDto> UpdateTenant(TenantDto tenantDto) // in use
        {
            //https://github.com/aspnet/EntityFrameworkCore/issues/10954
            //https://github.com/AutoMapper/AutoMapper/issues/1792
            //https://github.com/AutoMapper/AutoMapper/issues/1695

            var tenant = await _tenantRepository.List().Include(t => t.Offices).FirstOrDefaultAsync(t => t.Id == tenantDto.Id);

            var officeDtos = (tenantDto.Offices == null || !tenantDto.Offices.Any()) ? new List <OfficeDto>() : tenantDto.Offices;

            // var offices = tenant.Offices;
            // tenantDto.Offices = null; // unable to set the automapper to ignore this list; so it ends up added twice during the save.

            // a tenant should has at least one office
            if (!officeDtos.Any() && !tenant.Offices.Any())
            {
                officeDtos.Add(new OfficeDto
                {
                    TenantId   = tenantDto.Id,
                    OfficeCode = tenantDto.TenantCode,
                    OfficeName = tenantDto.TenantName,
                    NickName   = tenantDto.TenantName
                });
            }
            //_mapper.Map<TenantDto,Tenant>(tenantDto, tenant);
            tenant.MappTenantDto(tenantDto);
            _tenantRepository.Update(tenant);
            foreach (var officeDto in officeDtos)
            {
                officeDto.TenantId = tenant.Id;
                // ef addorupdate causes some kind of troubles
                var office = tenant.Offices.FirstOrDefault(o => o.Id == officeDto.Id); // _mapper.Map<Office>(officeDto);
                if (office == null)
                {
                    office = _mapper.Map <Office>(officeDto);
                    office = _officeRepository.Add(office);
                    // the current user would be added to the office; so that the office at least has one user
                    _officeUserRepository.Add(new OfficeUser {
                        UserId = _authContext.CurrentUser.Id, OfficeId = office.Id
                    });
                    var adminRole = new Role {
                        RoleName = $"Admin of {officeDto.OfficeName}", IsAdministrator = true, OfficeId = office.Id
                    };
                    adminRole = _roleRepository.Add(adminRole);
                    // this user would be the admin of the office
                    _roleUserRepository.Add(new RoleUser {
                        UserId = _authContext.CurrentUser.Id, RoleId = adminRole.Id
                    });
                }
                else
                {
                    //_mapper.Map<OfficeDto,Office>(officeDto,office);
                    office.MappOfficeDto(officeDto);
                    _officeRepository.Update(office);
                }
            }
            await _tenantRepository.SaveAsync();

            return(await GetTenant(tenant.Id.ToString()));
        }
Esempio n. 10
0
        public async Task <ApiResponse> UpdateTenantAsync(TenantDto tenantDto)
        {
            var tenant = await _tenantStoreDbContext.TenantInfo.SingleOrDefaultAsync(i => i.Id == tenantDto.Id);

            if (tenant == null)
            {
                return(new ApiResponse(Status400BadRequest, L["The tenant {0} doesn't exist", tenantDto.Name]));
            }

            var response = new ApiResponse(Status200OK, L["Tenant {0} updated", tenantDto.Name], tenantDto);

            if (tenantDto.Identifier != tenant.Identifier && (tenantDto.Identifier == Constants.Settings.DefaultTenantId || tenant.Identifier == Constants.Settings.DefaultTenantId))
            {
                response = new ApiResponse(Status403Forbidden, L["Default Tenant identifier cannot be changed and must be unique"]);
            }
            else
            {
                tenant = _autoMapper.Map(tenantDto, tenant);

                _tenantStoreDbContext.TenantInfo.Update(tenant);
                await _tenantStoreDbContext.SaveChangesAsync();
            }

            return(response);
        }
Esempio n. 11
0
        public async Task UpdateTenant(TenantDto tenant)
        {
            var existingTenant = await this._tenantRep.GetAsync(tenant.Id);

            existingTenant.ChangeName(tenant.Name)
            .ChangeOrAddDesc(tenant.Description);
        }
Esempio n. 12
0
 public async Task <ActionResult <IEnumerable <TenantDto> > > Get()
 {
     return(await _context.Tenants
            .OrderBy(i => i.LastName)
            .Select(i => TenantDto.FromEntity(i))
            .ToListAsync());
 }
Esempio n. 13
0
 private void btnOK_Click(object sender, EventArgs e)
 {
     _tenantDto = new TenantDto {
         Name = txtTenantName.Text
     };
     Close();
 }
        public void Update_ShouldFail_GivenTenantDoesntExist()
        {
            // Given
            // a random TenantDto
            var tenantDto = new TenantDto()
            {
                Id             = Guid.NewGuid().ToString(),
                Name           = "123 Name",
                Slug           = "zbcdef_123",
                ServiceDetails = new ServiceDetailsDto
                {
                    ServiceExpireDate          = DateTime.Now + TimeSpan.FromDays(1000),
                    ServiceMaxStorageMegabytes = 10000,
                    ServiceMaxUsers            = 1000
                },
                PrimaryContact = new ContactInfoDto
                {
                    FullName          = "John Doe",
                    Email             = "*****@*****.**",
                    MobilePhoneNumber = "+79991234567"
                }
            };

            // When
            var updateTenantResponse = _httpClient.PutAsJsonAsync(_url + tenantDto.Id, tenantDto).Result;

            // Then
            Assert.That(updateTenantResponse.StatusCode == HttpStatusCode.NotFound);
        }
Esempio n. 15
0
        public TenantDto Update(TenantDto tenant)
        {
            Tenant tenantToUpdate = Get(tenant.Id);

            _dbContext.Entry(tenantToUpdate).CurrentValues.SetValues(_mapper.Map <Tenant>(tenant));
            _dbContext.SaveChanges();
            return(_mapper.Map <TenantDto>(tenantToUpdate));
        }
Esempio n. 16
0
 public async Task <Tenant> Create(TenantDto tenantDto)
 {
     throw new System.NotImplementedException();
     //var tenant = _autoMapper.Map<TenantDto, Tenant>(tenantDto);
     //await _db.Tenants.AddAsync(tenant);
     //await _db.SaveChangesAsync(CancellationToken.None);
     //return tenant;
 }
Esempio n. 17
0
        public async Task <IActionResult> Post([FromBody] TenantDto tenantDto)
        {
            if (tenantDto.Id != 0)
            {
                return(StatusCode(StatusCodes.Status400BadRequest, "Identity insert is not permitted."));
            }

            return(await SaveAndReturnEntityAsync(async() => await _tenantService.SaveAndReturnEntityAsync(tenantDto)));
        }
Esempio n. 18
0
        private void AddTenantNode(AuthTokenDto tokenDto, TenantDto tenant)
        {
            var node = new TenantNode(_serverDto, tenant.Name)
            {
                DisplayName = tenant.Name, Tag = tenant.Guid
            };

            AddTenantNode(node);
        }
Esempio n. 19
0
        public TenantDto UpdateTenant(TenantDto tenantDto)
        {
            var tenant = this._tenantRepository.GetByKey(tenantDto.ID);

            tenant.UpdateTenant(tenantDto.DisplayName, tenantDto.Description, tenantDto.UpdatedBy);
            this._tenantRepository.Update(tenant);

            return(tenant.MapAs <TenantDto>());
        }
Esempio n. 20
0
        public TenantDto CreateTenant(TenantDto tenantDto)
        {
            var tenant = new Tenant(tenantDto.TenantName, tenantDto.DisplayName, tenantDto.Description,
                                    tenantDto.CreatedBy);

            this._tenantRepository.Add(tenant);

            return(tenant.MapAs <TenantDto>());
        }
Esempio n. 21
0
        public async Task <IActionResult> Put(int id, [FromBody] TenantDto tenantDto)
        {
            if (id == 0 || tenantDto.Id == 0)
            {
                return(StatusCode(StatusCodes.Status400BadRequest, "Id needs to be greater than 0."));
            }

            return(await SaveAndReturnEntityAsync(async() => await _tenantService.SaveAndReturnEntityAsync(tenantDto)));
        }
Esempio n. 22
0
 public ActionResult Edit(TenantDto model)
 {
     using (var service = ServiceLocator.Instance.Resolve <ITenantService>())
     {
         model.UpdatedBy = this.LoginUser.Identity.Name;
         var tenant = service.UpdateTenant(model);
         return(Json(true, tenant));
     }
 }
Esempio n. 23
0
        public TenantDto Add(TenantDto item)
        {
            Tenant tenant = _mapper.Map <Tenant>(item);

            _dbContext.Tenant.Add(tenant);
            _dbContext.SaveChanges();

            return(GetDto(tenant.Id));
        }
Esempio n. 24
0
        public IActionResult Create(int personId)
        {
            var person      = _customerFacadeApiClient.GetPerson(personId).Result;
            var personAlert = new TenantDto {
                PersonId = personId, Person = person
            };

            return(PartialView("Edit", personAlert));
        }
Esempio n. 25
0
        public IActionResult Save(TenantDto model)
        {
            bool success;

            model = model.Id == 0 ? _customerFacadeApiClient.PostTenant(model).Result
                : _customerFacadeApiClient.PutTenant(model.Id, model).Result;
            success = string.IsNullOrWhiteSpace(model.ErrorMessage);
            return(Json(new { success, message = success ? model.SuccessMessage : model.ErrorMessage }));
        }
Esempio n. 26
0
        public async Task <ApiResponse> CreateTenantAsync(TenantDto tenantDto)
        {
            var tenant = _autoMapper.Map <TenantDto, TenantInfo>(tenantDto);
            await _tenantStoreDbContext.TenantInfo.AddAsync(tenant);

            await _tenantStoreDbContext.SaveChangesAsync();

            return(new ApiResponse(Status200OK, L["Tenant {0} created", tenantDto.Name], tenantDto));
        }
Esempio n. 27
0
 public TenantContainer(TenantDto tenant)
 {
     AdminName      = NormalizeName(tenant.Name) + "Admin";
     AdminPassword  = "******";
     TenantId       = Guid.NewGuid();
     Tenant         = tenant;
     Department_1_1 = new TestDepartmentHolder();
     Department_1_2 = new TestDepartmentHolder();
 }
        private TenantDto CreateTenantDto(OspTenant ospTenant)
        {
            var tenantDto = new TenantDto
            {
                TenantId = ospTenant.TenantId,
                Database = ospTenant.DatabaseName
            };

            return(tenantDto);
        }
        public async Task <IActionResult> Get(int id)
        {
            TenantDto tenant = await _tenantAppService.GetById(id);

            if (tenant == null)
            {
                return(NotFound("Tenant not found."));
            }

            return(Ok(tenant));
        }
Esempio n. 30
0
        private TenantDto AddTenant(TenantDto tenantDto)
        {
            var succcess = false;

            ActionHelper.Execute(delegate() {
                var auth  = SnapInContext.Instance.AuthTokenManager.GetAuthToken(DisplayName);
                tenantDto = SnapInContext.Instance.ServiceGateway.Tenant.Create(auth.ServerDto, tenantDto, auth.Token);
                succcess  = true;
            });
            return(succcess ? tenantDto: null);
        }