예제 #1
0
        private static int HandleOU(OrgUnitRegistrationExtended ou, OrgUnitService service, OrgUnitDao dao)
        {
            try
            {
                OrganisationRegistryProperties.SetCurrentMunicipality(ou.Cvr);

                if (ou.Operation.Equals(OperationType.DELETE))
                {
                    service.Delete(ou.Uuid, ou.Timestamp);
                }
                else
                {
                    service.Update(ou);
                }

                dao.OnSuccess(ou.Id);
                dao.Delete(ou.Id);

                return(0);
            }
            catch (TemporaryFailureException ex)
            {
                log.Warn("Could not handle ou '" + ou.Uuid + "' at the moment, will try later", ex);
                return(-1);
            }
            catch (Exception ex)
            {
                log.Error("Could not handle ou '" + ou.Uuid + "'", ex);
                dao.OnFailure(ou.Id, ex.Message);
                dao.Delete(ou.Id);

                return(-2);
            }
        }
예제 #2
0
        public static void Init()
        {
            // set TLS version to 1.2
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            OrganisationRegistryProperties.GetInstance();
        }
예제 #3
0
        public IActionResult Update([FromBody] OrgUnitRegistration ou, [FromHeader] string cvr, [FromHeader] string apiKey)
        {
            if ((cvr = AuthorizeAndFetchCvr(cvr, apiKey)) == null)
            {
                return(Unauthorized());
            }

            // setting it will revert to default if no value is supplied, so we can read a valid value afterwards
            OrganisationRegistryProperties.SetCurrentMunicipality(cvr);
            cvr = OrganisationRegistryProperties.GetCurrentMunicipality();

            string error;

            if ((error = ValidateOU(ou)) == null)
            {
                try
                {
                    orgUnitDao.Save(ou, OperationType.UPDATE, cvr);
                }
                catch (Exception ex)
                {
                    log.Error("Failed to save OrgUnit", ex);

                    return(BadRequest(ex.Message));
                }
            }
            else
            {
                return(BadRequest(error));
            }

            return(Ok(ou));
        }
예제 #4
0
        protected string AuthorizeAndFetchCvr(string cvr, string apiKey)
        {
            if (!ApiKeyFilter.ValidApiKey(apiKey))
            {
                return(null);
            }

            string defaultCvr = OrganisationRegistryProperties.GetInstance().DefaultMunicipality;

            if (!string.IsNullOrEmpty(defaultCvr))
            {
                if (!string.IsNullOrEmpty(cvr) && !cvr.Equals(defaultCvr))
                {
                    log.Warn("CVR supplied through HTTP HEADER (" + cvr + ") was overwritten by configured default (" + defaultCvr + ")");
                }

                cvr = defaultCvr;
            }

            // if no CVR is supplied or configured, stop execution
            if (string.IsNullOrEmpty(cvr))
            {
                log.Warn("No CVR supplied or configured!");
                throw new System.Exception("No CVR supplied or configured!");
            }

            OrganisationRegistryProperties.SetCurrentMunicipality(cvr);

            return(OrganisationRegistryProperties.GetCurrentMunicipality());
        }
예제 #5
0
        public static int HandleUser(UserRegistrationExtended user, UserService service, UserDao dao)
        {
            try
            {
                OrganisationRegistryProperties.SetCurrentMunicipality(user.Cvr);

                if (user.Operation.Equals(OperationType.DELETE))
                {
                    service.Delete(user.Uuid, user.Timestamp);
                }
                else
                {
                    service.Update(user);
                }

                dao.OnSuccess(user.Id);
                dao.Delete(user.Id);

                return(0);
            }
            catch (TemporaryFailureException ex)
            {
                log.Warn("Could not handle user '" + user.Uuid + "' at the moment, will try later", ex);

                return(-1);
            }
            catch (Exception ex)
            {
                log.Error("Could not handle user '" + user.Uuid + "'", ex);
                dao.OnFailure(user.Id, ex.Message);
                dao.Delete(user.Id);

                return(-2);
            }
        }
예제 #6
0
        public OrgUnitDao()
        {
            connectionString = OrganisationRegistryProperties.GetInstance().DBConnectionString;
            if (connectionString.Equals("SQLITE"))
            {
                useSqlLite       = true;
                connectionString = "Data Source=./STSOrgSync.sqlite;Version=3;Pooling=True;MaxPoolSize=10;foreign keys=true;";
            }

            CreateTableIfNotExists();
        }
예제 #7
0
        /// <summary>
        /// This method will check whether the OrgUnit already exists inside Organisation, read it if it does, and perform
        /// the correct update (registering the delta-changes between the local object and the org-object). If the object
        /// does not already exist, it will pass the registration to the Create method.
        /// </summary>
        public void Update(OrgUnitRegistration registration)
        {
            log.Debug("Performing Update on OrgUnit '" + registration.Uuid + "'");

            ValidateAndEnforceCasing(registration);

            try
            {
                var result = organisationEnhedStub.GetLatestRegistration(registration.Uuid);
                if (result == null)
                {
                    log.Debug("Update on OrgUnit '" + registration.Uuid + "' changed to a Create because it does not exists as an active object within Organisation");
                    Create(registration);
                }
                else
                {
                    var addressRefs = UpdateAddresses(registration, result);

                    // this must happen after addresses have been imported, as it might result in UUID's being created
                    OrgUnitData orgUnitData = MapRegistrationToOrgUnitDTO(registration, addressRefs);

                    #region Update payout units
                    // if this unit handles payouts on behalf of a payout unit, create a reference to that payout unit
                    if (!string.IsNullOrEmpty(registration.PayoutUnitUuid))
                    {
                        string payoutUnitFunctionUuid = ServiceHelper.EnsurePayoutUnitFunctionExists(registration.PayoutUnitUuid, registration.Timestamp);

                        orgUnitData.OrgFunctionUuids.Add(payoutUnitFunctionUuid);
                    }
                    #endregion

                    ServiceHelper.UpdateManager(registration);

                    organisationEnhedStub.Ret(orgUnitData);

                    // ensure "henvendelsessted" tasks are updated
                    if (!OrganisationRegistryProperties.GetInstance().DisableHenvendelsessteder)
                    {
                        ServiceHelper.UpdateContactForTasks(registration.Uuid, registration.ContactForTasks, registration.Timestamp);
                    }

                    UpdateOrganisationObject(orgUnitData);

                    log.Debug("Update successful on OrgUnit '" + registration.Uuid + "'");
                }
            }
            catch (Exception ex) when(ex is STSNotFoundException || ex is ServiceNotFoundException)
            {
                log.Warn("Update on OrgUnitService failed for '" + registration.Uuid + "' due to unavailable KOMBIT services", ex);
                throw new TemporaryFailureException(ex.Message);
            }
        }
        public IActionResult Create([FromBody] ImportInputType input, [FromHeader] string cvr, [FromHeader] string apiKey)
        {
            if ((cvr = AuthorizeAndFetchCvr(cvr, apiKey)) == null)
            {
                return(Unauthorized());
            }

            // setting it will revert to default if no value is supplied, so we can read a valid value afterwards
            OrganisationRegistryProperties.SetCurrentMunicipality(cvr);
            cvr = OrganisationRegistryProperties.GetCurrentMunicipality();

            importerResponse result = rawOrganisationEnhedStub.Create(input);

            return(Ok(result));
        }
예제 #9
0
        public static DbCommand GetCommand(string statement, DbConnection connection)
        {
            DatabaseType database = OrganisationRegistryProperties.GetInstance().Database;

            switch (database)
            {
            case DatabaseType.MSSQL:
                return(new SqlCommand(statement, (SqlConnection)connection));

            case DatabaseType.MYSQL:
                return(new MySqlCommand(statement, (MySqlConnection)connection));

            default:
                throw new System.Exception("Unknown database type: " + database);
            }
        }
예제 #10
0
        public static object GetParameter(string key, object value)
        {
            DatabaseType database = OrganisationRegistryProperties.GetInstance().Database;

            switch (database)
            {
            case DatabaseType.MSSQL:
                return(new SqlParameter(key, value));

            case DatabaseType.MYSQL:
                return(new MySqlParameter(key, value));

            default:
                throw new System.Exception("Unknown database type: " + database);
            }
        }
예제 #11
0
파일: Program.cs 프로젝트: OS2sync/OS2sync
        private static void InitEnvironment()
        {
            System.Environment.SetEnvironmentVariable("ClientCertPath", "z:/dropbox/foces/PocIntegrator.pfx");
            System.Environment.SetEnvironmentVariable("ClientCertPassword", "Test1234");
            System.Environment.SetEnvironmentVariable("Environment", "TEST");
            System.Environment.SetEnvironmentVariable("Municipality", "29189838");
            System.Environment.SetEnvironmentVariable("DisableRevocationCheck", "true");
            System.Environment.SetEnvironmentVariable("LogLevel", "INFO");
            System.Environment.SetEnvironmentVariable("LogRequestResponse", "true");

            Initializer.Init();

            // hack to ensure random org-uuid to avoid data conflicts
            OrganisationRegistryProperties.GetInstance().MunicipalityOrganisationUUID.Remove(System.Environment.GetEnvironmentVariable("Municipality"));
            OrganisationRegistryProperties.GetInstance().MunicipalityOrganisationUUID.Add(System.Environment.GetEnvironmentVariable("Municipality"), Guid.NewGuid().ToString().ToLower());
        }
예제 #12
0
        public static DbConnection GetConnection()
        {
            var          connectionString = OrganisationRegistryProperties.GetInstance().DBConnectionString;
            DatabaseType database         = OrganisationRegistryProperties.GetInstance().Database;

            switch (database)
            {
            case DatabaseType.MSSQL:
                return(new SqlConnection(connectionString));

            case DatabaseType.MYSQL:
                return(new MySqlConnection(connectionString));

            default:
                throw new System.Exception("Unknown database type: " + database);
            }
        }
예제 #13
0
        /// <summary>
        /// This method will create the object in Organisation - note that if the object already exists, this method
        /// will fail. If unsure whether the object exists, use Update() instead, as that will fallback to Create
        /// if the object does not exist.
        /// </summary>
        public void Create(OrgUnitRegistration registration)
        {
            log.Debug("Performing Create on OrgUnit '" + registration.Uuid + "'");

            ValidateAndEnforceCasing(registration);

            try
            {
                var addressRefs = ImportAddresses(registration);

                // mapping the unit must come after the addresses, as importing the address might set a UUID on the addresses if not supplied by the caller
                OrgUnitData orgUnitData = MapRegistrationToOrgUnitDTO(registration, addressRefs);

                // create manager relationship
                if (!string.IsNullOrEmpty(registration.ManagerUuid))
                {
                    ServiceHelper.UpdateManager(registration);
                }

                // if this unit is a working unit, that does payouts in behalf of a payout unit, create a reference to that payout unit
                if (!string.IsNullOrEmpty(registration.PayoutUnitUuid))
                {
                    string payoutUnitFunctionUuid = ServiceHelper.EnsurePayoutUnitFunctionExists(registration.PayoutUnitUuid, registration.Timestamp);

                    orgUnitData.OrgFunctionUuids.Add(payoutUnitFunctionUuid);
                }

                organisationEnhedStub.Importer(orgUnitData);

                UpdateOrganisationObject(orgUnitData);

                // ensure "henvendelsessted" tasks are created
                if (!OrganisationRegistryProperties.GetInstance().DisableHenvendelsessteder)
                {
                    ServiceHelper.UpdateContactForTasks(registration.Uuid, registration.ContactForTasks, registration.Timestamp);
                }

                log.Debug("Create successful on OrgUnit '" + registration.Uuid + "'");
            }
            catch (Exception ex) when(ex is STSNotFoundException || ex is ServiceNotFoundException)
            {
                log.Warn("Create on OrgUnitService failed for '" + registration.Uuid + "' due to unavailable KOMBIT services", ex);
                throw new TemporaryFailureException(ex.Message);
            }
        }
예제 #14
0
        public static IDisposable Init()
        {
            if (!initialized)
            {
                initialized = true;

                if (OrganisationRegistryProperties.GetInstance().UseSSL)
                {
                    // If this fails with an error code 5 (Access Denied), then run powershell as admin, start netsh and run this command
                    // http add urlacl url=https://+:9010/ user=Everyone
                    return(WebApp.Start <Startup>(url: "https://+:9010/"));
                }

                // If this fails with an error code 5 (Access Denied), then run powershell as admin, start netsh and run this command
                // http add urlacl url=http://+:9010/ user=Everyone
                return(WebApp.Start <Startup>(url: "http://+:9010/"));
            }

            return(null);
        }
예제 #15
0
        public Controller(string cvr, string orgUuid, RichTextBox log)
        {
            this.log = log;

            // overwrite settings from registry - this must happen before calling Init() as that will start fetching tokens
            OrganisationRegistryProperties properties = OrganisationRegistryProperties.GetInstance();

            OrganisationRegistryProperties.Municipality = cvr;
            properties.MunicipalityOrganisationUUID[OrganisationRegistryProperties.GetMunicipality()] = orgUuid;

            Initializer.Init();

            this.inspectorService = new InspectorService();

            var config = new TemplateServiceConfiguration();

            config.CachingProvider = new DefaultCachingProvider(t => { });
            var service = RazorEngineService.Create(config);

            Engine.Razor = service;
        }
예제 #16
0
파일: InitDB.cs 프로젝트: OS2sync/OS2sync
        public static void InitializeDatabase()
        {
            if (!string.IsNullOrEmpty(OrganisationRegistryProperties.GetInstance().DBConnectionString))
            {
                using (DbConnection connection = DaoUtil.GetConnection())
                {
                    try
                    {
                        string location = OrganisationRegistryProperties.GetInstance().MigrationScriptsPath;

                        if (OrganisationRegistryProperties.GetInstance().Database.Equals(DatabaseType.MSSQL))
                        {
                            var evolve = new Evolve.Evolve(connection, msg => log.Info(msg))
                            {
                                Locations       = new[] { location },
                                Schemas         = new[] { "dbo" }, // default schema can be NULL in SQL Server, which makes Evolve unhappy
                                IsEraseDisabled = true
                            };

                            evolve.Migrate();
                        }
                        else
                        {
                            var evolve = new Evolve.Evolve(connection, msg => log.Info(msg))
                            {
                                Locations       = new[] { location },
                                IsEraseDisabled = true
                            };

                            evolve.Migrate();
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
        }
예제 #17
0
        public static async void InitAsync()
        {
            if (string.IsNullOrEmpty(OrganisationRegistryProperties.GetInstance().DBConnectionString))
            {
                log.Warn("Not starting scheduler - no connection string configured!");
                return;
            }

            if (!initialized)
            {
                InitDB.InitializeDatabase();

                log.Info("Starting SchedulingLayer");

                // get a scheduler
                IScheduler sched = await new StdSchedulerFactory().GetScheduler();
                await sched.StartDelayed(System.TimeSpan.FromSeconds(30));

                // define the job and tie it to our HelloJob class
                IJobDetail job = JobBuilder.Create <SyncJob>()
                                 .WithIdentity("syncJob", "syncGroup")
                                 .Build();

                // execute updater every minute
                ITrigger trigger = TriggerBuilder.Create()
                                   .WithIdentity("syncTrigger", "syncGroup")
                                   .StartNow()
                                   .WithSimpleSchedule(x => x
                                                       .WithIntervalInMinutes(1)
                                                       .RepeatForever())
                                   .Build();

                await sched.ScheduleJob(job, trigger);

                initialized = true;
            }
        }
예제 #18
0
        private void ValidateAndEnforceCasing(OrgUnitRegistration registration)
        {
            List <string> errors = new List <string>();

            if (string.IsNullOrEmpty(registration.Name))
            {
                errors.Add("name");
            }

            if (string.IsNullOrEmpty(registration.Uuid))
            {
                errors.Add("uuid");
            }

            if (registration.Timestamp == null)
            {
                errors.Add("timestamp");
            }

            if (errors.Count > 0)
            {
                throw new InvalidFieldsException("Invalid registration object - the following fields are invalid: " + string.Join(",", errors));
            }

            if (OrganisationRegistryProperties.GetInstance().DisableHenvendelsessteder)
            {
                registration.ContactForTasks = new List <string>();
            }

            if (OrganisationRegistryProperties.GetInstance().DisableUdbetalingsenheder)
            {
                registration.PayoutUnitUuid = null;
            }

            registration.Uuid = registration.Uuid.ToLower();
        }
예제 #19
0
        public IActionResult Read([FromHeader] string cvr, [FromHeader] string apiKey)
        {
            if (!ApiKeyFilter.ValidApiKey(apiKey))
            {
                return(Unauthorized());
            }

            List <UserDTO> result = new List <UserDTO>();

            try {
                // set cvr on thread if supplied as header (will revert to default if null)
                OrganisationRegistryProperties.SetCurrentMunicipality(cvr);

                log.Info("Fetching users in OrgUnits with a DTR-ID for " + OrganisationRegistryProperties.GetCurrentMunicipality());

                // read OUs
                List <global::IntegrationLayer.OrganisationFunktion.FiltreretOejebliksbilledeType> allUnitRoles;
                List <OU> ous = service.ReadOUHierarchy(cvr, out allUnitRoles, null, ReadTasks.NO, ReadManager.YES, ReadAddresses.YES, ReadPayoutUnit.NO, ReadPositions.NO, ReadContactForTasks.NO);

                log.Info("Found " + ous.Count() + " orgUnits in total");

                // filter OUs so we only get those with a DTRID registered on them
                ous = ous.Where(ou => ou.Addresses.Where(a => a is DtrId).Count() > 0).ToList();

                log.Info("Filtered to " + ous.Count() + " orgUnits with a DTR ID assigned");

                // TODO: could optimize this with some parallel lookup
                // read positions from OrgUnits
                service.LoadPositions(ous, allUnitRoles);

                // read users
                var userUuids = service.FindAllUsers(ous).Distinct().ToList();

                log.Info("Identified " + userUuids.Count + " users - reading details");

                var users = service.ReadUsers(cvr, userUuids, allUnitRoles, null, ReadAddresses.YES, ReadParentDetails.NO);
                log.Info("Found " + users.Count + " users");

                foreach (var ou in ous)
                {
                    var dtrIdAddress = ou.Addresses.Where(a => a is DtrId).FirstOrDefault();
                    if (dtrIdAddress == null)
                    {
                        continue;
                    }

                    string dtrId = dtrIdAddress.Value;

                    // load manager if available
                    if (!string.IsNullOrEmpty(ou.Manager?.Uuid))
                    {
                        log.Info("Reading manager for " + ou.Name);

                        try
                        {
                            var manager = service.ReadUserObject(ou.Manager.Uuid, ReadAddresses.YES, ReadParentDetails.NO);

                            var emailAddress = manager.Addresses.Where(a => a is Email).FirstOrDefault();
                            var phoneAddress = manager.Addresses.Where(a => a is Phone).FirstOrDefault();

                            var email = (emailAddress != null) ? emailAddress.Value : null;
                            var phone = (phoneAddress != null) ? phoneAddress.Value : null;

                            UserDTO userDTO = new UserDTO();
                            userDTO.dtrId   = dtrId;
                            userDTO.email   = email;
                            userDTO.phone   = phone;
                            userDTO.ssn     = manager.Person?.Cpr;
                            userDTO.userId  = manager.UserId;
                            userDTO.uuid    = manager.Uuid.ToLower();
                            userDTO.manager = true;
                            result.Add(userDTO);
                        }
                        catch (Exception ex)
                        {
                            log.Warn("Manager did not exist: " + ou.Manager.Uuid + " - " + ex.Message);
                        }
                    }

                    foreach (var user in users)
                    {
                        if (user.Positions.Where(p => string.Compare(p.OU?.Uuid, ou.Uuid) == 0).Count() > 0)
                        {
                            var emailAddress = user.Addresses.Where(a => a is Email).FirstOrDefault();
                            var phoneAddress = user.Addresses.Where(a => a is Phone).FirstOrDefault();

                            var email = (emailAddress != null) ? emailAddress.Value : null;
                            var phone = (phoneAddress != null) ? phoneAddress.Value : null;

                            UserDTO userDTO = new UserDTO();
                            userDTO.dtrId   = dtrId;
                            userDTO.email   = email;
                            userDTO.phone   = phone;
                            userDTO.ssn     = user.Person?.Cpr;
                            userDTO.userId  = user.UserId;
                            userDTO.uuid    = user.Uuid.ToLower();
                            userDTO.manager = false;
                            result.Add(userDTO);
                        }
                    }
                }

                return(Ok(result));
            }
            catch (Exception ex)
            {
                log.Error("Failed to build Hierarchy for " + OrganisationRegistryProperties.GetCurrentMunicipality(), ex);
                return(BadRequest("Error - se logs for details"));
            }
        }
예제 #20
0
 public UserDao()
 {
     connectionString = OrganisationRegistryProperties.GetInstance().DBConnectionString;
 }
예제 #21
0
        public IActionResult Read([FromHeader] string cvr, [FromHeader] string apiKey)
        {
            if (!ApiKeyFilter.ValidApiKey(apiKey))
            {
                return(Unauthorized());
            }

            string uuid = Guid.NewGuid().ToString().ToLower();

            new Thread(() => {
                try {
                    // set cvr on thread if supplied as header (will revert to default if null)
                    OrganisationRegistryProperties.SetCurrentMunicipality(cvr);

                    log.Info("Fetching hierarchy for " + OrganisationRegistryProperties.GetCurrentMunicipality());

                    // read OUs
                    List <global::IntegrationLayer.OrganisationFunktion.FiltreretOejebliksbilledeType> allUnitRoles;
                    var ous = service.ReadOUHierarchy(cvr, out allUnitRoles, null, ReadTasks.NO, ReadManager.NO, ReadAddresses.NO, ReadPayoutUnit.NO, ReadPositions.YES, ReadContactForTasks.NO);

                    // read users
                    var userUuids = service.FindAllUsers(ous).Distinct().ToList();
                    var users     = service.ReadUsers(cvr, userUuids, allUnitRoles, null, ReadAddresses.YES, ReadParentDetails.NO);
                    log.Info("Found " + users.Count + " users");

                    // construct result
                    var res = new Hierarchy();

                    // ous can be mapped in a simple manner
                    res.OUs = ous.Select(ou => new BasicOU()
                    {
                        Name     = ou.Name,
                        ParentOU = ou.ParentOU?.Uuid,
                        Uuid     = ou.Uuid
                    }).ToList();

                    // users has a slightly more complex structure
                    foreach (var user in users)
                    {
                        if (string.IsNullOrEmpty(user.Person?.Name))
                        {
                            log.Warn("User with uuid " + user.Uuid + " does not have a Person.Name for CVR: " + cvr);
                            continue;
                        }

                        BasicUser basicUser = new BasicUser();
                        basicUser.Name      = user.Person.Name;
                        basicUser.UserId    = user.UserId;
                        basicUser.Uuid      = user.Uuid;

                        if (user.Addresses != null)
                        {
                            foreach (var address in user.Addresses)
                            {
                                if (address is Email)
                                {
                                    basicUser.Email = address.Value;
                                }
                                else if (address is Phone)
                                {
                                    basicUser.Telephone = address.Value;
                                }
                            }
                        }

                        if (user.Positions != null)
                        {
                            foreach (var position in user.Positions)
                            {
                                basicUser.Positions.Add(new BasicPosition()
                                {
                                    Name = position.Name,
                                    Uuid = position.OU.Uuid
                                });
                            }
                        }

                        res.Users.Add(basicUser);
                    }

                    log.Info("Hierarchy build for " + OrganisationRegistryProperties.GetCurrentMunicipality() + ". Adding to cache with uuid: " + uuid);

                    cache.Add(uuid, new HierarchyWrapper()
                    {
                        Created = DateTime.Now,
                        Result  = res,
                        Status  = Status.SUCCESS
                    });
                }
                catch (Exception ex)
                {
                    log.Error("Failed to build Hierarchy for " + OrganisationRegistryProperties.GetCurrentMunicipality(), ex);

                    cache.Add(uuid, new HierarchyWrapper()
                    {
                        Created = DateTime.Now,
                        Result  = null,
                        Status  = Status.FAILURE
                    });
                }
            }).Start();

            return(Ok(uuid));
        }
예제 #22
0
파일: Program.cs 프로젝트: OS2sync/OS2sync
        private static void TestListAndReadOUs()
        {
            // small hack to ensure this test passes (the search parameters will find all ous in the organisation, and we need to test that it hits the required amount)
            OrganisationRegistryProperties properties = OrganisationRegistryProperties.GetInstance();
            string oldUuid = properties.MunicipalityOrganisationUUID[OrganisationRegistryProperties.GetCurrentMunicipality()];

            properties.MunicipalityOrganisationUUID[OrganisationRegistryProperties.GetCurrentMunicipality()] = Uuid();

            OrgUnitRegistration registration1 = OUReg();

            registration1.Name              = "magic";
            registration1.Email             = "*****@*****.**";
            registration1.ParentOrgUnitUuid = Uuid();
            orgUnitService.Update(registration1);

            orgUnitService.Read(registration1.Uuid);

            OrgUnitRegistration registration2 = OUReg();

            registration2.Name              = "magic";
            registration2.Email             = "*****@*****.**";
            registration2.ParentOrgUnitUuid = Uuid();
            orgUnitService.Update(registration2);

            registration2.Name = "different name";
            orgUnitService.Update(registration2);

            // TODO: a KMD bug prevents this test from working...
            OrgUnitRegistration registration3 = OUReg();

            registration3.Name              = "ou3";
            registration3.Email             = "*****@*****.**";
            registration3.ParentOrgUnitUuid = Uuid();
            orgUnitService.Update(registration3);
            orgUnitService.Delete(registration3.Uuid, DateTime.Now);

            List <string> ous = orgUnitService.List();

            if (ous.Count != 2)
            {
                throw new Exception("List() returned " + ous.Count + " ous, but 2 was expected");
            }

            foreach (var uuid in ous)
            {
                OrgUnitRegistration registration = orgUnitService.Read(uuid);

                if (uuid.Equals(registration1.Uuid))
                {
                    if (!registration1.Name.Equals(registration.Name))
                    {
                        throw new Exception("Name does not match");
                    }

                    if (!registration1.ParentOrgUnitUuid.Equals(registration.ParentOrgUnitUuid))
                    {
                        throw new Exception("ParentOU UUID does not match");
                    }

                    if (!registration1.Email.Equals(registration.Email))
                    {
                        throw new Exception("Email does not match");
                    }
                }
                else if (uuid.Equals(registration2.Uuid))
                {
                    if (!registration2.Name.Equals(registration.Name))
                    {
                        throw new Exception("Name does not match");
                    }

                    if (!registration2.ParentOrgUnitUuid.Equals(registration.ParentOrgUnitUuid))
                    {
                        throw new Exception("ParentOU UUID does not match");
                    }

                    if (!registration2.Email.Equals(registration.Email))
                    {
                        throw new Exception("Email does not match");
                    }
                }
                else
                {
                    throw new Exception("List returned the uuid of an unexpected ou");
                }
            }

            properties.MunicipalityOrganisationUUID[OrganisationRegistryProperties.GetCurrentMunicipality()] = oldUuid;
        }
예제 #23
0
파일: Program.cs 프로젝트: OS2sync/OS2sync
        private static void TestListAndReadUsers()
        {
            // small hack to ensure this test passes (the search parameters will find all users in the organisation, and we need to test that it hits the required amount)
            OrganisationRegistryProperties properties = OrganisationRegistryProperties.GetInstance();
            string oldUuid = properties.MunicipalityOrganisationUUID[OrganisationRegistryProperties.GetCurrentMunicipality()];

            properties.MunicipalityOrganisationUUID[OrganisationRegistryProperties.GetCurrentMunicipality()] = Uuid();

            UserRegistration registration1 = UserReg();

            registration1.UserId      = "userId1";
            registration1.Email       = "*****@*****.**";
            registration1.Person.Name = "Name of Person 1";
            registration1.Positions.Add(new Position()
            {
                Name        = "Position 1",
                OrgUnitUuid = Uuid()
            });
            registration1.Positions.Add(new Position()
            {
                Name        = "Position 2",
                OrgUnitUuid = Uuid()
            });
            userService.Update(registration1);

            UserRegistration registration2 = UserReg();

            registration2.UserId      = "userId2";
            registration2.Email       = "*****@*****.**";
            registration2.Person.Name = "Name of Person 2";
            registration2.Positions.Add(new Position()
            {
                Name        = "Position 3",
                OrgUnitUuid = Uuid()
            });
            registration2.Positions.Add(new Position()
            {
                Name        = "Position 4",
                OrgUnitUuid = Uuid()
            });
            userService.Update(registration2);

            UserRegistration registration3 = UserReg();

            registration3.UserId      = "userId3";
            registration3.Email       = "*****@*****.**";
            registration3.Person.Name = "Name of Person 3";
            registration3.Positions.Add(new Position()
            {
                Name        = "Position 5",
                OrgUnitUuid = Uuid()
            });
            userService.Update(registration3);
            userService.Delete(registration3.Uuid, DateTime.Now);

            List <string> users = userService.List();

            if (users.Count != 2)
            {
                throw new Exception("List() returned " + users.Count + " users, but 2 was expected");
            }

            foreach (var uuid in users)
            {
                UserRegistration registration = userService.Read(uuid);

                if (uuid.Equals(registration1.Uuid))
                {
                    if (!registration1.UserId.Equals(registration.UserId))
                    {
                        throw new Exception("userId does not match");
                    }

                    if (!registration1.Person.Name.Equals(registration.Person.Name))
                    {
                        throw new Exception("Name does not match");
                    }

                    if (!registration1.Email.Equals(registration.Email))
                    {
                        throw new Exception("Email does not match");
                    }

                    if (registration1.Positions.Count != registration.Positions.Count)
                    {
                        throw new Exception("Amount of positions does not match");
                    }

                    foreach (var position in registration1.Positions)
                    {
                        bool found = false;

                        foreach (var readPosition in registration.Positions)
                        {
                            if (readPosition.Name.Equals(position.Name) && readPosition.OrgUnitUuid.Equals(position.OrgUnitUuid))
                            {
                                found = true;
                            }
                        }

                        if (!found)
                        {
                            throw new Exception("Missing position");
                        }
                    }
                }
                else if (uuid.Equals(registration2.Uuid))
                {
                    if (!registration2.UserId.Equals(registration.UserId))
                    {
                        throw new Exception("userId does not match");
                    }

                    if (!registration2.Person.Name.Equals(registration.Person.Name))
                    {
                        throw new Exception("Name does not match");
                    }

                    if (!registration2.Email.Equals(registration.Email))
                    {
                        throw new Exception("Email does not match");
                    }

                    if (registration2.Positions.Count != registration.Positions.Count)
                    {
                        throw new Exception("Amount of positions does not match");
                    }

                    foreach (var position in registration2.Positions)
                    {
                        bool found = false;

                        foreach (var readPosition in registration.Positions)
                        {
                            if (readPosition.Name.Equals(position.Name) && readPosition.OrgUnitUuid.Equals(position.OrgUnitUuid))
                            {
                                found = true;
                            }
                        }

                        if (!found)
                        {
                            throw new Exception("Missing position");
                        }
                    }
                }
                else
                {
                    throw new Exception("List returned the uuid of an unexpected user");
                }
            }

            properties.MunicipalityOrganisationUUID[OrganisationRegistryProperties.GetCurrentMunicipality()] = oldUuid;
        }