public void GetDefaultTenantName()
        {
            string tenantName = TenantHelper.GetTenantName(RequestContext.TenantId);
            long   tenantId   = TenantHelper.GetTenantId(tenantName);

            Assert.AreEqual(tenantId, RequestContext.TenantId);
        }
示例#2
0
        /// <summary>
        ///     Exports the tenant.
        /// </summary>
        /// <remarks>
        /// This is the entry point for export requests that come via PlatformConfigure. c.f. EntityXmlExporter.GenerateXml.
        /// </remarks>
        /// <param name="tenantName">Name of the tenant.</param>
        /// <param name="entityId">Root entity to export.</param>
        /// <param name="packagePath">The package path.</param>
        /// <param name="exportSettings">Export settings.</param>
        /// <param name="context">The context.</param>
        public static void ExportEntity(string tenantName, long entityId, string packagePath, IProcessingContext context = null)
        {
            if (string.IsNullOrEmpty(tenantName))
            {
                throw new ArgumentNullException(nameof(tenantName));
            }
            if (string.IsNullOrEmpty(packagePath))
            {
                throw new ArgumentNullException(nameof(packagePath));
            }

            if (context == null)
            {
                context = new ProcessingContext( );
            }

            context.Report.StartTime = DateTime.Now;

            long tenantId = TenantHelper.GetTenantId(tenantName, true);

            /////
            // Create source to load app data from tenant
            /////
            using (IDataTarget target = FileManager.CreateDataTarget(Format.XmlVer2, packagePath))
            {
                var exporter = ( EntityXmlExporter )Factory.EntityXmlExporter;
                exporter.ExportEntity(tenantId, new[] { entityId }, target, context, false);
            }

            context.Report.EndTime = DateTime.Now;
        }
        public void TestEnable()
        {
            const string test = "foo";

            try
            {
                // Arrange
                var ts = new TenantService();

                using (new GlobalAdministratorContext())
                {
                    var id = TenantHelper.CreateTenant(test);
                    id.Should().BeGreaterThan(0);

                    var tenant = Entity.Get <Tenant>(id).AsWritable <Tenant>();
                    tenant.IsTenantDisabled = true;
                    tenant.Save();
                }

                // Act
                ts.Enable(test);

                // Assert
                using (new GlobalAdministratorContext())
                {
                    var tid = TenantHelper.GetTenantId(test);
                    tid.Should().BeGreaterThan(0);

                    var result = Entity.Get <Tenant>(tid);
                    result.Should().NotBeNull();
                    result.IsTenantDisabled.Should().BeFalse();
                }

                Action a1 = () => ts.Enable(null);
                a1.ShouldThrow <ArgumentException>().WithMessage("The specified tenantName parameter is invalid.");

                Action a2 = () => ts.Enable(string.Empty);
                a2.ShouldThrow <ArgumentException>().WithMessage("The specified tenantName parameter is invalid.");

                var    notATenant = Guid.NewGuid().ToString();
                Action a3         = () => ts.Enable(notATenant);
                a3.ShouldThrow <Exception>().WithMessage("Tenant " + notATenant + " not found.");
            }
            finally
            {
                using (new GlobalAdministratorContext())
                {
                    var testId = TenantHelper.GetTenantId(test);
                    if (testId > 0)
                    {
                        TenantHelper.DeleteTenant(testId);
                    }
                }
            }
        }
示例#4
0
        /// <summary>
        ///     Exports the tenant.
        /// </summary>
        /// <param name="tenantName">Name of the tenant.</param>
        /// <param name="packagePath">The package path.</param>
        /// <param name="metadataOnly">If true, exclude user data.</param>
        /// <param name="context">The context.</param>
        /// <exception cref="System.ArgumentNullException">
        ///     tenantName
        ///     or
        ///     tenantStorePath
        /// </exception>
        public static void ExportTenant(string tenantName, string packagePath, bool metadataOnly, IProcessingContext context = null)
        {
            if (string.IsNullOrEmpty(tenantName))
            {
                throw new ArgumentNullException("tenantName");
            }

            if (string.IsNullOrEmpty(packagePath))
            {
                throw new ArgumentNullException("packagePath");
            }

            if (context == null)
            {
                context = new ProcessingContext( );
            }

            context.Report.StartTime = DateTime.Now;

            long tenantId = TenantHelper.GetTenantId(tenantName, true);

            IDataSource source = metadataOnly
                ? (IDataSource) new TenantMetadataSource {
                TenantId = tenantId, TenantName = tenantName
            }
                : (IDataSource) new TenantSource {
                TenantId = tenantId, TenantName = tenantName
            };

            /////
            // Create source to load app data from tenant
            /////
            using ( source )
            {
                Format packageFormat = FileManager.GetExportFileFormat(packagePath);

                /////
                // Create target to write to SQLite database
                /////
                using (var target = FileManager.CreateDataTarget(packageFormat, packagePath))
                {
                    /////
                    // Copy the data
                    /////
                    var processor = new CopyProcessor(source, target, context);
                    processor.MigrateData( );
                }
            }

            context.Report.EndTime = DateTime.Now;
        }
        /// <summary>
        /// Grant or deny a tenant permission to operate with an application.
        /// </summary>
        /// <param name="tenantName">The tenant name or guid.</param>
        /// <param name="app">The application name or guid.</param>
        /// <param name="permission">The type of permission (e.g. Install, Publish).</param>
        /// <param name="grant">True to grant permission; false to remove permission.</param>
        public static void ChangeAppAccess(string tenantName, string app, AppPermission permission, bool grant)
        {
            // Log activity
            var context = new ProcessingContext
            {
                Report =
                {
                    Action = AppLibraryAction.ChangeAccess
                }
            };

            context.Report.Arguments.Add(new KeyValuePair <string, string>("Tenant", tenantName));
            context.Report.Arguments.Add(new KeyValuePair <string, string>("Application", app));
            context.Report.Arguments.Add(new KeyValuePair <string, string>("Permission", permission.ToString()));
            context.Report.Arguments.Add(new KeyValuePair <string, string>("Access", grant ? "Grant" : "Deny"));

            // Run
            using (new SecurityBypassContext( ))
            {
                long tenantId;
                long appId;

                using (new GlobalAdministratorContext( ))
                {
                    // Process arguments
                    tenantId = TenantHelper.GetTenantId(tenantName);
                    appId    = SystemHelper.GetGlobalApplicationIdByNameOrGuid(app);

                    if (appId <= 0 || tenantId <= 0)
                    {
                        return;
                    }

                    // Update database
                    switch (permission)
                    {
                    case AppPermission.Install:
                        UpdateTenantPermissionRelationship(tenantId, appId, "canInstallApplication", grant);
                        break;

                    case AppPermission.Publish:
                        UpdateTenantPermissionRelationship(tenantId, appId, "canPublishApplication", grant);
                        break;
                    }
                }
            }
        }
示例#6
0
        private void InvalidateTenant(string tenant)
        {
            long tid;

            using (new GlobalAdministratorContext())
            {
                tid = TenantHelper.GetTenantId(tenant);
            }

            if (tid > 0)
            {
                using (new TenantAdministratorContext(tid))
                {
                    TenantHelper.Invalidate(tid);
                }
            }
        }
示例#7
0
        /// <summary>
        ///     Deletes the tenant.
        /// </summary>
        /// <param name="tenantName">Name of the tenant.</param>
        /// <remarks></remarks>
        public static void DeleteTenant(string tenantName)
        {
            using (new GlobalAdministratorContext( ))
            {
                long tenantId = TenantHelper.GetTenantId(tenantName);

                if (tenantId == -1)
                {
                    /////
                    // Fail, the tenant does not exist.
                    /////
                    Console.WriteLine(@"The tenant {0} does not exist.", tenantName);
                    return;
                }

                TenantHelper.DeleteTenant(tenantId);
            }
        }
示例#8
0
        /// <summary>
        ///     Creates the tenant.
        /// </summary>
        /// <param name="tenantName">Name of the tenant.</param>
        /// <remarks></remarks>
        public static void CreateTenant(string tenantName)
        {
            using (new GlobalAdministratorContext( ))
            {
                /////
                // Check for existing tenant
                /////
                long tenantId = TenantHelper.GetTenantId(tenantName);

                if (tenantId != -1)
                {
                    // Fail, the tenant already exists.
                    Console.WriteLine(@"The tenant {0} already exists.", tenantName);
                    return;
                }

                TenantHelper.CreateTenant(tenantName);
            }
        }
示例#9
0
        /// <summary>
        ///     Imports the entity
        /// </summary>
        /// <param name="tenantName">Name of the tenant.</param>
        /// <param name="packagePath">The package path.</param>
        /// <param name="ignoreMissingDeps"></param>
        /// <param name="context">The context.</param>
        public static void ImportEntity(string tenantName, string packagePath, bool ignoreMissingDeps, IProcessingContext context = null)
        {
            if (string.IsNullOrEmpty(tenantName))
            {
                throw new ArgumentNullException(nameof(tenantName));
            }
            if (string.IsNullOrEmpty(packagePath))
            {
                throw new ArgumentNullException(nameof(packagePath));
            }

            if (context == null)
            {
                context = new ProcessingContext();
            }

            context.Report.StartTime = DateTime.Now;

            long tenantId = TenantHelper.GetTenantId(tenantName, true);

            /////
            // Create source to load app data from tenant
            /////
            using (IDataSource importSource = FileManager.CreateDataSource(packagePath))
            {
                EntityXmlImportSettings settings = new EntityXmlImportSettings
                {
                    IgnoreMissingDependencies = ignoreMissingDeps
                };
                EntityXmlImporter importer = ( EntityXmlImporter )Factory.EntityXmlImporter;
                try
                {
                    importer.ImportEntity(tenantId, importSource, settings, context);
                }
                catch (EntityXmlImporter.ImportDependencyException)
                {
                    context.WriteError("Import failed due to missing dependencies. Use -ignoreMissingDeps True to ignore.");
                }
            }

            context.Report.EndTime = DateTime.Now;
        }
示例#10
0
        public void TestDelete()
        {
            const string test = "foo";

            try
            {
                // Arrange
                var ts = new TenantService();

                using (new GlobalAdministratorContext())
                {
                    var id = TenantHelper.CreateTenant(test);
                    id.Should().BeGreaterThan(0);
                }

                // Act
                ts.Delete(test);

                // Assert
                using (new GlobalAdministratorContext())
                {
                    TenantHelper.GetTenantId(test).Should().BeLessThan(0);
                }

                Action a1 = () => ts.Delete(null);
                a1.ShouldThrow <ArgumentNullException>().WithMessage("Value cannot be null.\r\nParameter name: tenantName");

                Action a2 = () => ts.Delete(string.Empty);
                a2.ShouldThrow <ArgumentNullException>().WithMessage("Value cannot be null.\r\nParameter name: tenantName");
            }
            finally
            {
                using (new GlobalAdministratorContext())
                {
                    var testId = TenantHelper.GetTenantId(test);
                    if (testId > 0)
                    {
                        TenantHelper.DeleteTenant(testId);
                    }
                }
            }
        }
示例#11
0
        /// <summary>
        /// Changes the tenant application can modify field.
        /// </summary>
        /// <param name="tenantName"></param>
        /// <param name="app"></param>
        /// <param name="grant"></param>
        public static void ChangeTenantApplicationCanModify(string tenantName, string app, bool grant)
        {
            // Log activity
            var context = new ProcessingContext
            {
                Report =
                {
                    Action = AppLibraryAction.ChangeAccess
                }
            };

            context.Report.Arguments.Add(new KeyValuePair <string, string>("Tenant", tenantName));
            context.Report.Arguments.Add(new KeyValuePair <string, string>("Application", app));
            context.Report.Arguments.Add(new KeyValuePair <string, string>("Permission", "CanModifyApplication"));
            context.Report.Arguments.Add(new KeyValuePair <string, string>("Access", grant ? "Grant" : "Deny"));

            // Run
            using (new SecurityBypassContext())
            {
                using (new GlobalAdministratorContext())
                {
                    // Process arguments
                    var tenantId = TenantHelper.GetTenantId(tenantName);
                    if (tenantId <= 0)
                    {
                        return;
                    }

                    var appId = SystemHelper.GetTenantApplicationIdByName(tenantId, app);

                    if (appId <= 0)
                    {
                        return;
                    }

                    UpdateCanModifyApplicationField(tenantId, appId, grant);
                }
            }
        }
示例#12
0
        /// <summary>
        /// Sets the account status.
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        /// <param name="tenantName">Name of the tenant.</param>
        /// <param name="status">The status.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">
        /// userName
        /// or
        /// tenantName
        /// </exception>
        private static bool SetAccountStatus(string userName, string tenantName, UserAccountStatusEnum_Enumeration status)
        {
            if (string.IsNullOrEmpty(userName))
            {
                throw new ArgumentNullException("userName");
            }

            if (string.IsNullOrEmpty(tenantName))
            {
                throw new ArgumentNullException("tenantName");
            }

            long tenantId = TenantHelper.GetTenantId(tenantName);

            if (tenantId == -1)
            {
                return(false);
            }

            using (new TenantAdministratorContext(tenantId))
            {
                /////
                // Fetch the user account.
                /////
                UserAccount userAccount = Entity.GetByField <UserAccount>(userName, true, new EntityRef("core", "name")).FirstOrDefault( );

                if (userAccount == null)
                {
                    return(false);
                }

                userAccount.AccountStatus_Enum = status;

                userAccount.Save( );
            }

            return(true);
        }
示例#13
0
        public void TestRename()
        {
            const string test = "foo";
            const string name = "new";

            try
            {
                // Arrange
                var ts = new TenantService();

                long id;
                using (new GlobalAdministratorContext())
                {
                    id = TenantHelper.CreateTenant(test);
                }

                id.Should().BeGreaterThan(0);

                // Act
                ts.Rename(id, name);

                // Assert
                long nid;
                using (new GlobalAdministratorContext())
                {
                    var tid = TenantHelper.GetTenantId(test);
                    tid.Should().BeLessThan(0);

                    nid = TenantHelper.GetTenantId(name);
                    nid.Should().BeGreaterThan(0);
                }

                Action a1 = () => ts.Rename(-1, null);
                a1.ShouldThrow <ArgumentException>().WithMessage("New tenant name may not be null or empty.\r\nParameter name: name");

                Action a2 = () => ts.Rename(-1, string.Empty);
                a2.ShouldThrow <ArgumentException>().WithMessage("New tenant name may not be null or empty.\r\nParameter name: name");

                Action a3 = () => ts.Rename(-1, name);
                a3.ShouldThrow <Exception>().WithMessage("Tenant not found.");

                Action a4 = () => ts.Rename(nid, name); // same
                a4.ShouldNotThrow();
            }
            finally
            {
                using (new GlobalAdministratorContext())
                {
                    var testId = TenantHelper.GetTenantId(test);
                    if (testId > 0)
                    {
                        TenantHelper.DeleteTenant(testId);
                    }

                    var newId = TenantHelper.GetTenantId(name);
                    if (newId > 0)
                    {
                        TenantHelper.DeleteTenant(newId);
                    }
                }
            }
        }
示例#14
0
        public void Runs( )
        {
            var edcTenantId = TenantHelper.GetTenantId("EDC", true);

            //static string result = "";
            _result = "";

            using (CountdownEvent evt = new CountdownEvent(1))
            {
                Action <DummyParam> act = (p) =>
                {
                    _result += p.S;
                    // ReSharper disable once AccessToDisposedClosure
                    evt.Signal( );
                };


                var handler = new DummyHandler {
                    Action = act
                };
                var qFactory = new RedisTenantQueueFactory("BackgroundTaskManagerTests " + Guid.NewGuid( ));
                var manager  = new BackgroundTaskManager(qFactory, handlers: handler.ToEnumerable( ))
                {
                    IsActive = true
                };

                try
                {
                    manager.EnqueueTask(edcTenantId, BackgroundTask.Create("DummyHandler", new DummyParam {
                        S = "a"
                    }));
                    Assert.That(_result, Is.Empty);

                    manager.Start( );

                    evt.Wait(DefaultTimeout);
                    evt.Reset( );

                    Assert.That(_result, Is.EqualTo("a"));

                    manager.EnqueueTask(edcTenantId, BackgroundTask.Create("DummyHandler", new DummyParam {
                        S = "b"
                    }));

                    evt.Wait(DefaultTimeout);
                    evt.Reset( );

                    Assert.That(_result, Is.EqualTo("ab"));

                    manager.Stop(5000);

                    manager.EnqueueTask(edcTenantId, BackgroundTask.Create("DummyHandler", new DummyParam {
                        S = "c"
                    }));

                    Assert.That(_result, Is.EqualTo("ab"));                              // c not processed
                }
                finally
                {
                    manager.Stop( );
                    var items = manager.EmptyQueue(edcTenantId);
                    Assert.That(items.Count( ), Is.EqualTo(1));
                }
            }
        }