private void buttonCrear_Click(object sender, EventArgs e) { if (!string.IsNullOrWhiteSpace(textBoxNombre.Text)) { try { Models.Tenant tenant = new Models.Tenant(); tenant.BaseDeDatos = textBoxNombre.Text; tenant.UltimoNroAsientoCargando = 1; tenant.FechaCierreEjercicioContable = dateTimePickerCierre.Value.Date; tenant.FechaImpresionUltimoDiario = dateTimePickerInicio.Value.Date.AddDays(-1); tenant.FechaInicioEjercicioContable = dateTimePickerInicio.Value.Date; Models.Helpers.DatabaseOperations.MigrateDatabase(tenant); buttonCrear.Enabled = false; textBoxNombre.Enabled = false; //Helpers.CreadorMensajes.mensajeObservacion("Empresa creada con éxito."); } catch (Exception ex) { throw ex; } } }
public IActionResult RegisterDb([FromQuery] string tenant) // If we talk about db or schema strategies this method's job will be better to delegate to a separate worker or service. // And notify your tenant later that he can start work. App has to create db or schema and it can be time consumable. { if (string.IsNullOrWhiteSpace(tenant)) { return(BadRequest("Tenant name is required!")); } var reg = new Regex("[0-9a-zA-Z$_]+"); if (!reg.IsMatch(tenant)) { return(BadRequest("Tenant name must follow this pttern [0-9a-zA-Z$_]+")); } var newTenant = new Models.Tenant { ConStr = $"{_configuration.GetConnectionString("db")}_{tenant}", Key = tenant, Name = tenant }; var connectionString = _configuration.GetConnectionString("db"); var optionsBuilder = new DbContextOptionsBuilder <DbBasedContext>() .UseLazyLoadingProxies() .UseNpgsql(newTenant.ConStr); using (var db = new DbBasedContext(optionsBuilder.Options)) { db.Database.Migrate(); } Services.TenantResolver.Tenants.Add(newTenant);// add new tenant to collection of tenants return(Ok("Tenant was created")); }
public Tenant GetTenantDetails() { var allClaims = ((System.Security.Claims.ClaimsIdentity)HttpContext.Current.GetOwinContext().Request.User.Identity).Claims; Models.Tenant tenantModel = allClaims.GetTenantDetails(); return(tenantModel); }
public IActionResult RegisterSchema([FromQuery] string tenant) // If we talk about db or schema strategies this method's job will be better to delegate to a separate worker or service. // And notify your tenant later that he can start work. App has to create db or schema and it can be time consumable. { if (string.IsNullOrWhiteSpace(tenant)) { return(BadRequest("Tenant name is required!")); } var reg = new Regex("[0-9a-zA-Z$_]+"); if (!reg.IsMatch(tenant)) { return(BadRequest("Tenant name must follow this pttern [0-9a-zA-Z$_]+")); } var newTenant = new Models.Tenant { Key = tenant, Name = tenant }; var connectionString = _configuration.GetConnectionString("schema"); var optionsBuilder = new DbContextOptionsBuilder <SchemaBasedContext>() .UseNpgsql( connectionString, b => b.MigrationsAssembly("SchemaBasedStrategy") ) .ReplaceService <IModelCacheKeyFactory, ServiceModelCacheKeyFactory>(); new SchemaBasedContext(optionsBuilder.Options, newTenant.Key, true); Services.TenantResolver.Tenants.Add(newTenant);// add new tenant to collection of tenants return(Ok("Tenant was created")); }
public ResponseModel <TenantReturnModel> GetTenantById(string tenant_id) { try { //Look tenant by id Models.Tenant lookupTenant = dbcontext.tenants.FirstOrDefault(u => u.userId == tenant_id); if (lookupTenant == null) { throw new Exception("User not found"); } Models.Property dbProperty = dbcontext.properties.FirstOrDefault(u => u.propertyId == lookupTenant.propertyId); if (dbProperty == null) { throw new Exception("This user is not linked to any property...."); } return(new ResponseModel <TenantReturnModel> { data = Converter.MakeReturnTenant(lookupTenant, dbProperty), message = "success", status = true }); } catch (Exception err) { return(new ResponseModel <TenantReturnModel> { data = null, message = "An error has occured" + err.Message, status = false }); } }
public static TenantReturnModel MakeReturnTenant(Models.Tenant dbTenant, Models.Property dbProperty) { return(new TenantReturnModel { Name = dbTenant.names, UserId = dbTenant.userId, Username = dbTenant.username, propertyId = dbProperty.propertyId, leaseId = dbTenant.leaseId, Property = new MiniProperty { Address = dbProperty.address, PropertyId = dbProperty.propertyId, TotalLandLords = dbProperty.landLordProperties.Count, TotalManagers = dbProperty.managers.Count, TotalTenants = dbProperty.tenants.Count }, // TODO : Add more tenant fields gender = dbTenant.gender, idNumber = dbTenant.idNumber, cellNumber = dbTenant.cellNumber, createdAt = dbTenant.createdAt, profilePicture = dbTenant.profilePicture, deposit = dbTenant.deposit, rentAmount = dbTenant.rentAmount, Role = dbTenant.role, }); }
public static Tenant GetTenant() { var allClaims = ((ClaimsIdentity)HttpContext.Current.User.Identity).Claims; Models.Tenant tenantDetails = allClaims.GetTenantDetails(); return(tenantDetails); }
/// <summary> /// 指定コンテナを削除する /// </summary> /// <param name="tenant">対象テナント</param> /// <param name="name">コンテナ名</param> /// <param name="force">Admin権限で実行するか</param> private async Task <IActionResult> DeleteContainerAsync(Models.Tenant tenant, string name, bool force) { //入力チェック if (string.IsNullOrWhiteSpace(name)) { return(JsonBadRequest("Name is required.")); } var container = CheckContainerType(name, force); switch (container.Item1) { case ContainerType.TensorBoard: //C#は各caseがスコープ共通のため、同一変数名を使えない。止む無く変数名を分ける。 var trainingLogicForTensorBoard = commonDiLogic.DynamicDi <ITrainingLogic>(); //TensorBoardコンテナを削除する await trainingLogicForTensorBoard.DeleteTensorBoardAsync(container.Item2 as TensorBoardContainer, force); break; case ContainerType.Training: //学習コンテナを強制終了させる var trainingLogicForTraining = commonDiLogic.DynamicDi <ITrainingLogic>(); await trainingLogicForTraining.ExitAsync(container.Item2 as TrainingHistory, ContainerStatus.Killed, force); break; case ContainerType.Inferencing: //推論コンテナを強制終了させる var inferenceLogic = commonDiLogic.DynamicDi <IInferenceLogic>(); await inferenceLogic.ExitAsync(container.Item2 as InferenceHistory, ContainerStatus.Killed, force); break; case ContainerType.Preprocessing: //前処理コンテナを強制終了させる //コンテナがいる=前処理中なので、前処理済みデータは無条件で削除できると判断する var preprocessLogic = commonDiLogic.DynamicDi <IPreprocessLogic>(); await preprocessLogic.DeleteAsync(container.Item2 as PreprocessHistory, force); break; default: //正体不明コンテナを削除する var result = await clusterManagementLogic.DeleteContainerAsync(ContainerType.Unknown, name, tenant.Name, force); if (result == false) { return(JsonNotFound($"Container named {name} is not found.")); } break; } return(JsonNoContent()); }
public ActionResult Tenant(Models.Tenant tenant) { tenant.ProductId = 3; ContosoDevApiOrchestration client = new ContosoDevApiOrchestration(new Uri(ConfigurationManager.AppSettings["SaaSOrchestrationApiBaseUri"]), new AnonymousCredential()); client.Accepted(tenant); return(View("Confirmation")); }
public async Task <Models.Tenant> SaveTenantAsync(Models.Tenant tenant) { using (var context = Models.ApplicationDbContext.Create()) { context.Tenants.Add(tenant); await context.SaveChangesAsync(); return(tenant); } }
public async Task <IActionResult> GetTest() { var tenant = new Models.Tenant("Sabeco"); tenant.ExtraProperties.Add("Connection", "locahost"); await _mainDbContext.Tenants.AddAsync(tenant); await _mainDbContext.SaveChangesAsync(); return(Ok()); }
public ActionResult Index() { Models.Tenant tenantModel = ClaimsIdentityExtensions.GetTenant(); if (db.Tenants.Where(tenant => tenant.TenantID == tenantModel.TenantID).Count() > 0) { return(this.RedirectToAction("Index", "NewsItems")); } else { return(this.RedirectToAction("AdminConsent", "Permissions")); } }
protected override bool AuthorizeCore(HttpContextBase httpContext) { if (this.Roles.Contains(",")) { this.allowedroles = this.Roles.Split(','); } else { this.allowedroles = new String[] { this.Roles } }; var allClaims = ((System.Security.Claims.ClaimsIdentity)HttpContext.Current.GetOwinContext().Request.User.Identity).Claims; Models.Tenant tenant = allClaims.GetTenantDetails(); var authContext = new AuthenticationContext(ActiveDirectoryConstants.AuthString + tenant.TenantID); if (authContext.TokenCache.ReadItems().Count() > 0) { authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority); } var authResult = authContext.AcquireTokenAsync(ActiveDirectoryConstants.ResourceUrl, new ClientCredential(Startup.clientId, new Startup().appKey)); var client = new System.Net.Http.HttpClient(); var request = new HttpRequestMessage(HttpMethod.Get, "https://graph.windows.net/" + tenant.TenantID + "/users/" + HttpContext.Current.GetOwinContext().Request.User.Identity.Name + "/memberOf?api-version=1.6"); //var request = new HttpRequestMessage(HttpMethod.Get, "https://graph.windows.net/" + tenant.TenantID + "/users/" + HttpContext.Current.GetOwinContext().Request.User.Identity.Name + "/memberOf?api-version=1.6"); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.Result.AccessToken); var response = client.SendAsync(request); var content = response.Result.Content.ReadAsStringAsync(); JObject json = JObject.Parse(content.Result); var data = json.Last.Values()["displayName"]; var numerator = data.GetEnumerator(); while (numerator.MoveNext()) { if (this.allowedroles.Contains(numerator.Current.ToString())) { authorize = true; } } return(authorize); }
public static async Task CreateTenantAsync(Models.Tenant tenant) { string tenantNameFormatted = tenant.Name.Replace(" ", string.Empty).ToLower(); string environmentName = ConfigurationManager.AppSettings["SaasEnvironmentName"]; string foundationResourceGroupName = ConfigurationManager.AppSettings["SaasFoundationResourceGroupName"]; string tenantResourceGroupName = ConfigurationManager.AppSettings["SaasTenantResourceGroupName"]; string tenantPrefixName = ConfigurationManager.AppSettings["SaasProviderName"] + "-" + environmentName + "-plan3-"; string appServicePlanName = ConfigurationManager.AppSettings["SaasProviderName"] + "-" + environmentName + "-tenantsp"; string appServiceName = tenantPrefixName + tenantNameFormatted + "-web"; string databaseServer = ConfigurationManager.AppSettings["SaasProviderName"] + environmentName + "saas"; string databaseName = tenantPrefixName + tenantNameFormatted + "-sql"; AppSettings appSettings = new AppSettings(); appSettings.BlobPath = "https://wingtipsaas.blob.core.windows.net/images-sa/"; appSettings.ConnectionTimeOut = "30"; appSettings.DatabasePassword = "******"; appSettings.DatabaseServerPort = "1433"; appSettings.DatabaseUser = "******"; appSettings.ResetEventDates = "true"; appSettings.ServicePlan = "Standard"; appSettings.SqlProtocol = "tcp"; appSettings.TenantServer = databaseServer; appSettings.TenantDatabase = databaseName; appSettings.LearnHowFooterUrl = "https://aka.ms/sqldbsaastutorial"; appSettings.ASPNETCORE_ENVIRONMENT = "Production"; appSettings.WEBSITE_NODE_DEFAULT_VERSION = "4.2.3"; appSettings.DefaultRequestCulture = "en-us"; AppConfig properties = new AppConfig(); properties.Properties = appSettings; authContext = new AuthenticationContext(authority); clientCredential = new ClientCredential(clientId, appKey); await CreateDatabaseAsync(foundationResourceGroupName, tenantNameFormatted, databaseServer, databaseName); await CreateResourceGroupAsync(tenantResourceGroupName); await CreateAppServicePlanAsync(tenantResourceGroupName, appServicePlanName); await CreateAppServiceAsync(tenantResourceGroupName, appServiceName, appServicePlanName, tenantNameFormatted); await UpdateAppSettingsAsync(tenantResourceGroupName, appServiceName, properties, tenantNameFormatted); AddNewTenant(tenant.Name, tenant.ProductId); }
// GET: Tenants/Create public ActionResult Create() { DatabaseContext.Tenant tenant = new Tenant(); if (true) { Models.Tenant tenantModel = ClaimsIdentityExtensions.GetTenant(); tenant.TenantID = tenantModel.TenantID; tenant.TenantName = tenantModel.TenantName; tenant.ClientID = Startup.clientId; tenant.ClientSecret = new Startup().appKey; tenant.URL = tenantModel.TenantDomain; tenant.Modified = DateTime.Now.Date; tenant.Created = DateTime.Now.Date; tenant.CreateBy = User.Identity.Name; tenant.ModifiedBy = User.Identity.Name; db.Tenants.Add(tenant); db.SaveChanges(); return(RedirectToAction("Index")); } }
public IActionResult RegisterTable([FromQuery] string tenant) { if (string.IsNullOrWhiteSpace(tenant)) { return(BadRequest("Tenant name is required!")); } var reg = new Regex("[0-9a-zA-Z$_]+"); if (!reg.IsMatch(tenant)) { return(BadRequest("Tenant name must follow this pttern [0-9a-zA-Z$_]+")); } var newTenant = new Models.Tenant { Key = tenant, Name = tenant }; Services.TenantResolver.Tenants.Add(newTenant);// add new tenant to collection of tenants return(Ok("Tenant was created")); }
/// <summary> /// Adds a tenant w/o tag or location to DB /// </summary> /// <param name="tenantName">Name of tenant</param> /// <returns>bool TRUE if transaction succeded</returns> public static bool AddTenant(string tenantName) { //Creates a bool with value false. Only changes to true if transaction is complete var addAccepted = false; using (var db = new Database.MyDatabase()) try { //Begins transaction to DB db.Database.BeginTransaction(); //Checks if tenant name already exists in DB. To prevent same tenant to be added again by mistake, //and to avoid mixup/confusion when searching for entries by tenant in logs if (!CheckIfTenantNameExists(tenantName)) { //Creates a new object from Tenant-class, with Name value from user input var newTenant = new Models.Tenant { Name = tenantName }; //Adds new tenant to DB db.Tenants.Add(newTenant); //Saves changes to DB db.SaveChanges(); //Committs transaction to DB db.Database.CommitTransaction(); //Sets bool value to true addAccepted = true; } } catch { //Rollbacks transaction db.Database.RollbackTransaction(); } //returns bool value return(addAccepted); }
public TableBasedContext(DbContextOptions <TableBasedContext> options, Models.Tenant tenant) : base(options) { _tenant = tenant; }
public void Post([FromBody] Models.Tenant tenant) { HostingEnvironment.QueueBackgroundWorkItem(ct => Tenant.CreateTenantAsync(tenant)); //Tenant.CreateTenantAsync(tenant); }
public static void fillTenants() { using (var addData = new ApartmentDB()) { //Add tenants to table var tenant = new Models.Tenant { ID = 1, Name = "Liam Jönsson", IDTag = 1, IDApartment = 1 }; addData.Tenants.Add(tenant); tenant = new Models.Tenant { ID = 2, Name = "Elias Petterson", IDTag = 2, IDApartment = 2 }; addData.Tenants.Add(tenant); tenant = new Models.Tenant { ID = 3, Name = "Wilma Johansson", IDTag = 3, IDApartment = 2 }; addData.Tenants.Add(tenant); tenant = new Models.Tenant { ID = 4, Name = "Alicia Sanchez", IDTag = 4, IDApartment = 3 }; addData.Tenants.Add(tenant); tenant = new Models.Tenant { ID = 5, Name = "Aaron Sanchez", IDTag = 5, IDApartment = 3 }; addData.Tenants.Add(tenant); tenant = new Models.Tenant { ID = 6, Name = "Olivia Erlander", IDTag = 6, IDApartment = 4 }; addData.Tenants.Add(tenant); tenant = new Models.Tenant { ID = 7, Name = "William Erlander", IDTag = 7, IDApartment = 4 }; addData.Tenants.Add(tenant); tenant = new Models.Tenant { ID = 8, Name = "Alexander Erlander", IDTag = 8, IDApartment = 4 }; addData.Tenants.Add(tenant); tenant = new Models.Tenant { ID = 9, Name = "Astrid Erlander", IDTag = 9, IDApartment = 4 }; addData.Tenants.Add(tenant); tenant = new Models.Tenant { ID = 10, Name = "Lucas Adolfsson", IDTag = 10, IDApartment = 5 }; addData.Tenants.Add(tenant); tenant = new Models.Tenant { ID = 11, Name = "Ebba Adolfsson", IDTag = 11, IDApartment = 5 }; addData.Tenants.Add(tenant); tenant = new Models.Tenant { ID = 12, Name = "Lilly Adolfsson", IDTag = 12, IDApartment = 5 }; addData.Tenants.Add(tenant); tenant = new Models.Tenant { ID = 13, Name = "Ella Ahlström", IDTag = 13, IDApartment = 6 }; addData.Tenants.Add(tenant); tenant = new Models.Tenant { ID = 14, Name = "Alma Alfredsson", IDTag = 14, IDApartment = 6 }; addData.Tenants.Add(tenant); tenant = new Models.Tenant { ID = 15, Name = "Elsa Ahlström", IDTag = 15, IDApartment = 6 }; addData.Tenants.Add(tenant); tenant = new Models.Tenant { ID = 16, Name = "Maja Ahlström", IDTag = 16, IDApartment = 6 }; addData.Tenants.Add(tenant); tenant = new Models.Tenant { ID = 17, Name = "Noah Almgren", IDTag = 17, IDApartment = 7 }; addData.Tenants.Add(tenant); tenant = new Models.Tenant { ID = 18, Name = "Adam Andersen", IDTag = 18, IDApartment = 7 }; addData.Tenants.Add(tenant); tenant = new Models.Tenant { ID = 19, Name = "Kattis Backman", IDTag = 19, IDApartment = 7 }; addData.Tenants.Add(tenant); tenant = new Models.Tenant { ID = 20, Name = "Oscar Chen", IDTag = 20, IDApartment = 7 }; addData.Tenants.Add(tenant); tenant = new Models.Tenant { ID = 21, Name = "Janitor", IDTag = 21, IDApartment = 8 }; addData.Tenants.Add(tenant); addData.SaveChanges(); //Tenants added to table } }
public static IQueryable <T> OfTenant <T>(this DbSet <T> dbSet, Models.Tenant tenant) where T : class { return(dbSet.OfTenant(tenant.Id)); }
/// <summary> /// Add Tenant to Group /// </summary> /// <param name="organizationId">Id of the organization (required)</param> /// <param name="groupId">Id of the group (required)</param> /// <param name="tenant">Tenant details</param> public async Task <Models.Tenant> CreateAsync(string organizationId, string groupId, Models.Tenant tenant) { return(await _apiClient.CreateAsync(organizationId, groupId, tenant)); }