internal AdresseFlerRelationType CreateAddressReference(string uuid, int indeks, string roleUuid, VirkningType virkning)
        {
            UnikIdType type = new UnikIdType();

            type.Item            = UUIDConstants.ADDRESS_TYPE_ORGUNIT;
            type.ItemElementName = ItemChoiceType.UUIDIdentifikator;

            UnikIdType role = new UnikIdType();

            role.ItemElementName = ItemChoiceType.UUIDIdentifikator;
            role.Item            = roleUuid;

            AdresseFlerRelationType address = new AdresseFlerRelationType();

            address.ReferenceID = StubUtil.GetReference <UnikIdType>(uuid, ItemChoiceType.UUIDIdentifikator);
            address.Virkning    = virkning;
            address.Indeks      = "" + indeks;
            address.Rolle       = role;
            address.Type        = type;

            return(address);
        }
Esempio n. 2
0
        public retResponse Update(RetInputType1 input)
        {
            // construct request
            retRequest request = new retRequest();

            request.RetRequest1                  = new RetRequestType();
            request.RetRequest1.RetInput         = input;
            request.RetRequest1.AuthorityContext = new AuthorityContextType();
            request.RetRequest1.AuthorityContext.MunicipalityCVR = OrganisationRegistryProperties.GetCurrentMunicipality();

            // send Ret request
            BrugerPortType channel = StubUtil.CreateChannel <BrugerPortType>(BrugerStubHelper.SERVICE, "Ret", helper.CreatePort());

            try
            {
                return(channel.ret(request));
            }
            catch (Exception ex) when(ex is CommunicationException || ex is IOException || ex is TimeoutException || ex is WebException)
            {
                throw new ServiceNotFoundException("Failed to establish connection to the Ret service on Person", ex);
            }
        }
        internal void AddTilknyttedeFunktioner(List <string> tilknytteFunktioner, VirkningType virkning, RegistreringType1 registration)
        {
            if (tilknytteFunktioner == null || tilknytteFunktioner.Count == 0)
            {
                return;
            }

            OrganisationFunktionFlerRelationType[] orgFunktionFlerRelationTypes = new OrganisationFunktionFlerRelationType[tilknytteFunktioner.Count];

            for (int i = 0; i < tilknytteFunktioner.Count; i++)
            {
                UnikIdType tilknytteFunktionId = StubUtil.GetReference <UnikIdType>(tilknytteFunktioner[i], ItemChoiceType.UUIDIdentifikator);

                OrganisationFunktionFlerRelationType orgFunktionFlerRelationType = new OrganisationFunktionFlerRelationType();
                orgFunktionFlerRelationType.ReferenceID = tilknytteFunktionId;
                orgFunktionFlerRelationType.Virkning    = virkning;

                orgFunktionFlerRelationTypes[i] = orgFunktionFlerRelationType;
            }

            registration.RelationListe.TilknyttedeFunktioner = orgFunktionFlerRelationTypes;
        }
        internal void AddOpgaver(List <string> opgaver, VirkningType virkning, RegistreringType1 registration)
        {
            if (opgaver == null || opgaver.Count == 0)
            {
                return;
            }

            KlasseFlerRelationType[] opgaverTypes = new KlasseFlerRelationType[opgaver.Count];

            for (int i = 0; i < opgaver.Count; i++)
            {
                UnikIdType tilknytteFunktionId = StubUtil.GetReference <UnikIdType>(opgaver[i], ItemChoiceType.UUIDIdentifikator);

                KlasseFlerRelationType opgaveType = new KlasseFlerRelationType();
                opgaveType.ReferenceID = tilknytteFunktionId;
                opgaveType.Virkning    = virkning;

                opgaverTypes[i] = opgaveType;
            }

            registration.RelationListe.Opgaver = opgaverTypes;
        }
Esempio n. 5
0
        public importerResponse Create(ImportInputType inportInput)
        {
            // construct request
            importerRequest request = new importerRequest();

            request.ImporterRequest1                  = new ImporterRequestType();
            request.ImporterRequest1.ImportInput      = inportInput;
            request.ImporterRequest1.AuthorityContext = new AuthorityContextType();
            request.ImporterRequest1.AuthorityContext.MunicipalityCVR = OrganisationRegistryProperties.GetCurrentMunicipality();

            // send request
            AdressePortType channel = StubUtil.CreateChannel <AdressePortType>(AdresseStubHelper.SERVICE, "Importer", helper.CreatePort());

            try
            {
                return(channel.importer(request));
            }
            catch (Exception ex) when(ex is CommunicationException || ex is IOException || ex is TimeoutException || ex is WebException)
            {
                throw new ServiceNotFoundException("Failed to establish connection to the Importer service on Adresse", ex);
            }
        }
        public soegResponse Search(SoegInputType1 soegInput)
        {
            // construct request
            soegRequest request = new soegRequest();

            request.SoegRequest1                  = new SoegRequestType();
            request.SoegRequest1.SoegInput        = soegInput;
            request.SoegRequest1.AuthorityContext = new AuthorityContextType();
            request.SoegRequest1.AuthorityContext.MunicipalityCVR = OrganisationRegistryProperties.GetCurrentMunicipality();


            // send request
            OrganisationFunktionPortType channel = StubUtil.CreateChannel <OrganisationFunktionPortType>(OrganisationFunktionStubHelper.SERVICE, "Soeg", helper.CreatePort());

            try
            {
                return(channel.soeg(request));
            }
            catch (Exception ex) when(ex is CommunicationException || ex is IOException || ex is TimeoutException || ex is WebException)
            {
                throw new ServiceNotFoundException("Failed to establish connection to the Soeg service on OrganisationFunktion", ex);
            }
        }
Esempio n. 7
0
        public static bool TerminateObjectsInOrgNoLongerPresentLocally(dynamic orgArray, dynamic localArray, DateTime timestamp, bool uuidSubReference)
        {
            bool changes = false;

            if (orgArray != null)
            {
                foreach (var objectInOrg in orgArray)
                {
                    bool found = false;

                    if (localArray != null)
                    {
                        foreach (var objectInLocal in localArray)
                        {
                            // we need the UuidSubReference check on both sides of the || to ensure that the second part of the && clause is not evaluated unless needed
                            if ((uuidSubReference && objectInLocal.Uuid.Equals(objectInOrg.ReferenceID.Item)) || (!uuidSubReference && objectInLocal.Equals(objectInOrg.ReferenceID.Item)))
                            {
                                found = true;
                            }
                        }
                    }

                    if (!found)
                    {
                        // as this is a FlerRelation, we also get all the old references, so only mark the object as
                        // changed if we actually terminate a valid Virkning
                        if (StubUtil.TerminateVirkning(objectInOrg.Virkning, timestamp))
                        {
                            changes = true;
                        }
                    }
                }
            }

            return(changes);
        }
Esempio n. 8
0
        public laesResponse Read(string uuid)
        {
            LaesInputType laesInput = new LaesInputType();

            laesInput.UUIDIdentifikator = uuid;

            laesRequest request = new laesRequest();

            request.LaesRequest1                  = new LaesRequestType();
            request.LaesRequest1.LaesInput        = laesInput;
            request.LaesRequest1.AuthorityContext = new AuthorityContextType();
            request.LaesRequest1.AuthorityContext.MunicipalityCVR = OrganisationRegistryProperties.GetCurrentMunicipality();

            OrganisationPortType channel = StubUtil.CreateChannel <OrganisationPortType>(OrganisationStubHelper.SERVICE, "Laes", helper.CreatePort());

            try
            {
                return(channel.laes(request));
            }
            catch (Exception ex) when(ex is CommunicationException || ex is IOException || ex is TimeoutException || ex is WebException)
            {
                throw new ServiceNotFoundException("Failed to establish connection to the Laes service on Organisation", ex);
            }
        }
Esempio n. 9
0
        internal BrugerPortTypeClient CreatePort()
        {
            BasicHttpBinding binding = new BasicHttpBinding();

            binding.Security.Mode = BasicHttpSecurityMode.Transport;
            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
            binding.MaxReceivedMessageSize = Int32.MaxValue;
            binding.OpenTimeout            = new TimeSpan(0, 3, 0);
            binding.CloseTimeout           = new TimeSpan(0, 3, 0);
            binding.ReceiveTimeout         = new TimeSpan(0, 3, 0);
            binding.SendTimeout            = new TimeSpan(0, 3, 0);

            BrugerPortTypeClient port = new BrugerPortTypeClient(binding, StubUtil.GetEndPointAddress("Bruger/5"));

            port.ClientCredentials.ClientCertificate.Certificate = CertificateLoader.LoadCertificateAndPrivateKeyFromFile();

            // Disable revocation checking
            if (registryProperties.DisableRevocationCheck)
            {
                port.ClientCredentials.ServiceCertificate.Authentication.RevocationMode = X509RevocationMode.NoCheck;
            }

            return(port);
        }
Esempio n. 10
0
        public void Importer(OrgUnitData unit)
        {
            log.Debug("Attempting Importer on OrganisationEnhed with uuid " + unit.Uuid);

            // create ShortKey if not supplied
            EnsureKeys(unit);

            // create timestamp object to be used on all registrations, properties and relations
            VirkningType virkning = helper.GetVirkning(unit.Timestamp);

            // setup registration
            RegistreringType1 registration = helper.CreateRegistration(unit, LivscyklusKodeType.Importeret);

            // add properties
            helper.AddProperties(unit.ShortKey, unit.Name, virkning, registration);

            // add relationships
            helper.SetType(unit.OrgUnitType, virkning, registration);
            helper.AddAddressReferences(unit.Addresses, virkning, registration);
            helper.AddOrganisationRelation(StubUtil.GetMunicipalityOrganisationUUID(), virkning, registration);
            helper.AddOverordnetEnhed(unit.ParentOrgUnitUuid, virkning, registration);

            // TODO: if we ever have other functions for OrgUnits than payout units, this solution will not work
            if (!registry.DisableUdbetalingsenheder)
            {
                helper.AddTilknyttedeFunktioner(unit.OrgFunctionUuids, virkning, registration);
            }

            helper.AddOpgaver(unit.Tasks, virkning, registration);

            // set Tilstand to Active
            helper.SetTilstandToActive(virkning, registration, unit.Timestamp);

            // wire everything together
            OrganisationEnhedType organisationEnhedType = helper.GetOrganisationEnhedType(unit.Uuid, registration);
            ImportInputType       importInput           = new ImportInputType();

            importInput.OrganisationEnhed = organisationEnhedType;

            // construct request
            importerRequest request = new importerRequest();

            request.ImporterRequest1                  = new ImporterRequestType();
            request.ImporterRequest1.ImportInput      = importInput;
            request.ImporterRequest1.AuthorityContext = new AuthorityContextType();
            request.ImporterRequest1.AuthorityContext.MunicipalityCVR = OrganisationRegistryProperties.GetCurrentMunicipality();

            // send request
            OrganisationEnhedPortType channel = StubUtil.CreateChannel <OrganisationEnhedPortType>(OrganisationEnhedStubHelper.SERVICE, "Importer", helper.CreatePort());

            try
            {
                importerResponse result = channel.importer(request);
                int statusCode          = Int32.Parse(result.ImporterResponse1.ImportOutput.StandardRetur.StatusKode);
                if (statusCode != 20)
                {
                    string message = StubUtil.ConstructSoapErrorMessage(statusCode, "Import", OrganisationEnhedStubHelper.SERVICE, result.ImporterResponse1.ImportOutput.StandardRetur.FejlbeskedTekst);
                    log.Error(message);
                    throw new SoapServiceException(message);
                }

                log.Debug("Importer successful on OrganisationEnhed with uuid " + unit.Uuid);
            }
            catch (Exception ex) when(ex is CommunicationException || ex is IOException || ex is TimeoutException || ex is WebException)
            {
                throw new ServiceNotFoundException("Failed to establish connection to the Importer service on OrganisationEnhed", ex);
            }
        }
Esempio n. 11
0
        // this method only performs a call to Ret on Organisation if there are actual changes
        public void Ret(string uuid, string newName, string newCpr, DateTime timestamp)
        {
            log.Debug("Attempting Ret on Person with uuid " + uuid);

            // this should never fail - we always import the Person before the User, and we have a User with a reference to this object
            RegistreringType1 registration = GetLatestRegistration(uuid);

            if (registration == null)
            {
                log.Debug("Cannot call Ret on Person with uuid " + uuid + " because it does not exist in Organisation");
                return;
            }

            PersonPortType channel = StubUtil.CreateChannel <PersonPortType>(PersonStubHelper.SERVICE, "Ret", helper.CreatePort());

            try
            {
                RetInputType1 input = new RetInputType1();
                input.UUIDIdentifikator = uuid;
                input.AttributListe     = registration.AttributListe;
                input.TilstandListe     = registration.TilstandListe;
                input.RelationListe     = registration.RelationListe;

                // compare latest property to the local object
                EgenskabType latestProperty = StubUtil.GetLatestProperty(input.AttributListe);
                if (latestProperty == null || string.Compare(latestProperty.NavnTekst, newName) != 0 || string.Compare(latestProperty.CPRNummerTekst, newCpr) != 0)
                {
                    // create a new property
                    EgenskabType newProperty = new EgenskabType();
                    newProperty.Virkning = helper.GetVirkning(timestamp);
                    newProperty.BrugervendtNoegleTekst = ((latestProperty != null) ? latestProperty.BrugervendtNoegleTekst : IdUtil.GenerateShortKey());
                    newProperty.NavnTekst      = newName;
                    newProperty.CPRNummerTekst = newCpr;

                    // overwrite existing property set
                    input.AttributListe    = new EgenskabType[1];
                    input.AttributListe[0] = newProperty;
                }
                else
                {
                    log.Debug("No changes on Person, so returning without calling Organisation");

                    // if there are no changes to the attributes, we do not call the Organisation service
                    return;
                }

                // send Ret request
                retRequest request = new retRequest();
                request.RetRequest1                  = new RetRequestType();
                request.RetRequest1.RetInput         = input;
                request.RetRequest1.AuthorityContext = new AuthorityContextType();
                request.RetRequest1.AuthorityContext.MunicipalityCVR = OrganisationRegistryProperties.GetCurrentMunicipality();

                retResponse response = channel.ret(request);

                int statusCode = Int32.Parse(response.RetResponse1.RetOutput.StandardRetur.StatusKode);
                if (statusCode != 20)
                {
                    if (statusCode == 49)
                    {
                        log.Warn("Ret failed on Person " + uuid + " as Organisation returned status 49. The most likely cause is that the object has been Passiveret");
                        return;
                    }

                    string message = StubUtil.ConstructSoapErrorMessage(statusCode, "Ret", PersonStubHelper.SERVICE, response.RetResponse1.RetOutput.StandardRetur.FejlbeskedTekst);
                    log.Error(message);
                    throw new SoapServiceException(message);
                }

                log.Debug("Ret successful on Person with uuid " + uuid);
            }
            catch (Exception ex) when(ex is CommunicationException || ex is IOException || ex is TimeoutException || ex is WebException)
            {
                throw new ServiceNotFoundException("Failed to establish connection to the Ret service on Person", ex);
            }
        }
Esempio n. 12
0
        public Dictionary <string, RegistreringType1> GetLatestRegistrations(List <string> uuids)
        {
            var result = new Dictionary <string, RegistreringType1>();

            ListInputType listInput = new ListInputType();

            listInput.UUIDIdentifikator = uuids.ToArray();

            listRequest request = new listRequest();

            request.ListRequest1                  = new ListRequestType();
            request.ListRequest1.ListInput        = listInput;
            request.ListRequest1.AuthorityContext = new AuthorityContextType();
            request.ListRequest1.AuthorityContext.MunicipalityCVR = OrganisationRegistryProperties.GetMunicipality();

            AdressePortType channel = StubUtil.CreateChannel <AdressePortType>(AdresseStubHelper.SERVICE, "List", helper.CreatePort());

            try
            {
                listResponse response = channel.list(request);

                int statusCode = Int32.Parse(response.ListResponse1.ListOutput.StandardRetur.StatusKode);
                if (statusCode != 20)
                {
                    // note that statusCode 44 means that the object does not exists, so that is a valid response
                    log.Debug("List on Adresse failed with statuscode " + statusCode);
                    return(result);
                }

                if (response.ListResponse1.ListOutput.FiltreretOejebliksbillede == null || response.ListResponse1.ListOutput.FiltreretOejebliksbillede.Length == 0)
                {
                    log.Debug("List on Adresse has 0 hits");
                    return(result);
                }

                foreach (var adresse in response.ListResponse1.ListOutput.FiltreretOejebliksbillede)
                {
                    RegistreringType1[] resultSet = adresse.Registrering;
                    if (resultSet.Length == 0)
                    {
                        log.Warn("Adresse with uuid '" + adresse.ObjektType.UUIDIdentifikator + "' exists, but has no registration");
                        continue;
                    }

                    RegistreringType1 reg = null;
                    if (resultSet.Length > 1)
                    {
                        log.Warn("Adresse with uuid " + adresse.ObjektType.UUIDIdentifikator + " has more than one registration when reading latest registration, this should never happen");

                        DateTime winner = DateTime.MinValue;
                        foreach (RegistreringType1 res in resultSet)
                        {
                            // first time through will always result in a True evaluation here
                            if (DateTime.Compare(winner, res.Tidspunkt) < 0)
                            {
                                reg    = res;
                                winner = res.Tidspunkt;
                            }
                        }
                    }
                    else
                    {
                        reg = resultSet[0];
                    }

                    // we cannot perform any kind of updates on Slettet/Passiveret, så it makes sense to filter them out on lookup,
                    // so the rest of the code will default to Import op top of this
                    if (reg.LivscyklusKode.Equals(LivscyklusKodeType.Slettet) || reg.LivscyklusKode.Equals(LivscyklusKodeType.Passiveret))
                    {
                        continue;
                    }

                    result.Add(adresse.ObjektType.UUIDIdentifikator, reg);
                }

                return(result);
            }
            catch (Exception ex) when(ex is CommunicationException || ex is IOException || ex is TimeoutException || ex is WebException)
            {
                throw new ServiceNotFoundException("Failed to establish connection to the List service on Adresse", ex);
            }
        }
        internal OrganisationSystemPortTypeClient CreatePort()
        {
            BasicHttpBinding binding = new BasicHttpBinding();

            binding.Security.Mode = BasicHttpSecurityMode.Transport;
            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
            binding.MaxReceivedMessageSize = Int32.MaxValue;
            binding.OpenTimeout            = new TimeSpan(0, 3, 0);
            binding.CloseTimeout           = new TimeSpan(0, 3, 0);
            binding.ReceiveTimeout         = new TimeSpan(0, 3, 0);
            binding.ReceiveTimeout         = new TimeSpan(0, 3, 0);
            binding.SendTimeout            = new TimeSpan(0, 3, 0);

            OrganisationSystemPortTypeClient port = new OrganisationSystemPortTypeClient(binding, StubUtil.GetEndPointAddress("OrganisationSystem/4"));

            port.ClientCredentials.ClientCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindByThumbprint, registryProperties.ClientCertThumbprint);

            // Disable revocation checking
            if (registryProperties.DisableRevocationCheck)
            {
                port.ClientCredentials.ServiceCertificate.Authentication.RevocationMode = X509RevocationMode.NoCheck;
            }

            return(port);
        }
Esempio n. 14
0
 private UnikIdType GetOrganisationReference()
 {
     return(StubUtil.GetReference <UnikIdType>(StubUtil.GetMunicipalityOrganisationUUID(), ItemChoiceType.UUIDIdentifikator));
 }
        internal bool UpdateOpgaver(List <string> opgaver, VirkningType virkning, RegistreringType1 registration, DateTime timestamp)
        {
            if (registryProperties.DisableKleOpgaver)
            {
                return(false);
            }

            bool changes = false;

            // make sure we have a list to work with below, and that there are no duplicates
            opgaver = (opgaver != null) ? opgaver : new List <string>();
            opgaver = opgaver.Distinct().ToList();

            // find those we need to add (at the end of this method)
            var toAdd = new List <string>();

            foreach (var opgave in opgaver)
            {
                bool add = true;

                if (registration.RelationListe?.Opgaver != null)
                {
                    foreach (var opgaveRelation in registration.RelationListe.Opgaver)
                    {
                        string uuid = opgaveRelation.ReferenceID?.Item;

                        if (opgave.Equals(uuid))
                        {
                            add = false;
                            break;
                        }
                    }
                }

                if (add)
                {
                    changes = true;
                    toAdd.Add(opgave);
                }
            }

            if (registration.RelationListe?.Opgaver != null)
            {
                IEqualityComparer <KlasseFlerRelationType> comparer = new KlasseFlerRelationTypeComparer();

                // remove duplicates from registration.RelationListe.Opgaver (because sometimes we get duplicates back from KMD)
                registration.RelationListe.Opgaver = registration.RelationListe.Opgaver.Distinct(comparer).ToArray();

                // terminate virkning on elements no longer in local
                foreach (var opgaveRelation in registration.RelationListe.Opgaver)
                {
                    string uuid = opgaveRelation.ReferenceID?.Item;

                    if (uuid != null && !opgaver.Contains(uuid))
                    {
                        changes = true;
                        StubUtil.TerminateVirkning(opgaveRelation.Virkning, timestamp);
                    }
                }
            }

            // actually add the new ones to this registration
            if (toAdd.Count > 0)
            {
                if (registration.RelationListe.Opgaver == null || registration.RelationListe.Opgaver.Length == 0)
                {
                    AddOpgaver(toAdd, virkning, registration);
                }
                else
                {
                    KlasseFlerRelationType[] opgaverTypes = new KlasseFlerRelationType[toAdd.Count + registration.RelationListe.Opgaver.Length];

                    // add new
                    for (int i = 0; i < toAdd.Count; i++)
                    {
                        UnikIdType tilknytteFunktionId = StubUtil.GetReference <UnikIdType>(toAdd[i], ItemChoiceType.UUIDIdentifikator);

                        KlasseFlerRelationType opgaveType = new KlasseFlerRelationType();
                        opgaveType.ReferenceID = tilknytteFunktionId;
                        opgaveType.Virkning    = virkning;

                        opgaverTypes[i] = opgaveType;
                    }

                    // copy existing
                    for (int j = 0, i = toAdd.Count; i < opgaverTypes.Length && j < registration.RelationListe.Opgaver.Length; i++, j++)
                    {
                        opgaverTypes[i] = registration.RelationListe.Opgaver[j];
                    }

                    registration.RelationListe.Opgaver = opgaverTypes;
                }
            }

            return(changes);
        }
Esempio n. 16
0
        // this method only performs a call to Ret on Address if there are actual changes
        public void Ret(string uuid, string newValue, DateTime timestamp, RegistreringType1 registration)
        {
            log.Debug("Attempting Ret on Address with uuid " + uuid);

            AdressePortType channel = StubUtil.CreateChannel <AdressePortType>(AdresseStubHelper.SERVICE, "Ret", helper.CreatePort());

            try
            {
                RetInputType1 input = new RetInputType1();
                input.UUIDIdentifikator = uuid;
                input.AttributListe     = registration.AttributListe;
                input.TilstandListe     = registration.TilstandListe;
                input.RelationListe     = registration.RelationListe;

                // compare latest property to the local object
                EgenskabType latestProperty = StubUtil.GetLatestProperty(input.AttributListe);
                if (latestProperty == null || !latestProperty.AdresseTekst.Equals(newValue))
                {
                    // create a new property
                    EgenskabType newProperty = new EgenskabType();
                    newProperty.Virkning = helper.GetVirkning(timestamp);
                    newProperty.BrugervendtNoegleTekst = latestProperty.BrugervendtNoegleTekst;
                    newProperty.AdresseTekst           = newValue;

                    // create a new set of properties
                    input.AttributListe    = new EgenskabType[1];
                    input.AttributListe[0] = newProperty;
                }
                else
                {
                    log.Debug("No changes on Address, so returning without calling Organisation");

                    // if there are no changes to the attributes, we do not call the Organisation service
                    return;
                }

                // send Ret request
                retRequest request = new retRequest();
                request.RetRequest1                  = new RetRequestType();
                request.RetRequest1.RetInput         = input;
                request.RetRequest1.AuthorityContext = new AuthorityContextType();
                request.RetRequest1.AuthorityContext.MunicipalityCVR = OrganisationRegistryProperties.GetCurrentMunicipality();

                retResponse response = channel.ret(request);

                int statusCode = Int32.Parse(response.RetResponse1.RetOutput.StandardRetur.StatusKode);
                if (statusCode != 20)
                {
                    if (statusCode == 49)
                    {
                        log.Warn("Ret failed on Address " + uuid + " as Organisation returned status 49. The most likely cause is that the object has been Passiveret");
                        return;
                    }

                    string message = StubUtil.ConstructSoapErrorMessage(statusCode, "Ret", AdresseStubHelper.SERVICE, response.RetResponse1.RetOutput.StandardRetur.FejlbeskedTekst);
                    log.Error(message);
                    throw new SoapServiceException(message);
                }

                log.Debug("Ret successful on Address with uuid " + uuid);
            }
            catch (Exception ex) when(ex is CommunicationException || ex is IOException || ex is TimeoutException || ex is WebException)
            {
                throw new ServiceNotFoundException("Failed to establish connection to the Ret service on Adresse", ex);
            }
        }
        public List <OrgUnitRegWrapper> Read(string antal, string offset)
        {
            FremsoegObjekthierarkiInputType input = new FremsoegObjekthierarkiInputType();

            input.MaksimalAntalKvantitet   = antal;
            input.FoersteResultatReference = offset;

            fremsoegobjekthierarkiRequest request = new fremsoegobjekthierarkiRequest();

            request.FremsoegobjekthierarkiRequest1 = new FremsoegobjekthierarkiRequestType();
            request.FremsoegobjekthierarkiRequest1.FremsoegObjekthierarkiInput      = input;
            request.FremsoegobjekthierarkiRequest1.AuthorityContext                 = new AuthorityContextType();
            request.FremsoegobjekthierarkiRequest1.AuthorityContext.MunicipalityCVR = OrganisationRegistryProperties.GetMunicipality();

            // send request
            OrganisationSystemPortType channel = StubUtil.CreateChannel <OrganisationSystemPortType>(OrganisationSystemStubHelper.SERVICE, "FremsoegObjektHierarki", helper.CreatePort());

            try
            {
                var result = channel.fremsoegobjekthierarki(request);

                int statusCode = Int32.Parse(result.FremsoegobjekthierarkiResponse1.FremsoegObjekthierarkiOutput.StandardRetur.StatusKode);
                if (statusCode != 20)
                {
                    string message = StubUtil.ConstructSoapErrorMessage(statusCode, "FremsoegObjektHierarki", OrganisationFunktionStubHelper.SERVICE, result.FremsoegobjekthierarkiResponse1.FremsoegObjekthierarkiOutput.StandardRetur.FejlbeskedTekst);
                    log.Error(message);
                    throw new SoapServiceException(message);
                }


                List <OrgUnitRegWrapper> registrations = new List <OrgUnitRegWrapper>();

                var ous = result.FremsoegobjekthierarkiResponse1.FremsoegObjekthierarkiOutput.OrganisationEnheder;
                foreach (var ou in ous)
                {
                    string uuid = ou.ObjektType?.UUIDIdentifikator;

                    if (uuid == null)
                    {
                        log.Warn("OU in hierarchy does not have a uuid");
                    }
                    else if (ou.Registrering == null)
                    {
                        log.Warn("OU in hierarchy does not have a registration: " + uuid);
                    }
                    else
                    {
                        if (ou.Registrering.Length != 1)
                        {
                            log.Warn("OU in hierarchy does has more than one registration: " + uuid);
                        }

                        registrations.Add(new OrgUnitRegWrapper()
                        {
                            Uuid         = uuid,
                            Registration = ou.Registrering[0]
                        });
                    }
                }

                return(registrations);
            }
            catch (Exception ex) when(ex is CommunicationException || ex is IOException || ex is TimeoutException || ex is WebException)
            {
                throw new ServiceNotFoundException("Failed to establish connection to the Importer service on OrganisationFunktion", ex);
            }
        }
Esempio n. 18
0
        public List <string> Soeg(string antal = null, string offset = null)
        {
            OrganisationEnhedPortType channel = StubUtil.CreateChannel <OrganisationEnhedPortType>(OrganisationEnhedStubHelper.SERVICE, "Soeg", helper.CreatePort());

            SoegInputType1 soegInput = new SoegInputType1();

            soegInput.AttributListe = new AttributListeType();
            soegInput.RelationListe = new RelationListeType();
            soegInput.TilstandListe = new TilstandListeType();

            if (antal != null)
            {
                soegInput.MaksimalAntalKvantitet = antal;
            }
            if (offset != null)
            {
                soegInput.FoersteResultatReference = offset;
            }

            // only search for Active units
            soegInput.TilstandListe.Gyldighed    = new GyldighedType[1];
            soegInput.TilstandListe.Gyldighed[0] = new GyldighedType();
            soegInput.TilstandListe.Gyldighed[0].GyldighedStatusKode = GyldighedStatusKodeType.Aktiv;

            // TODO: these three lines should be removeable once KMD fixes their end
            soegInput.TilstandListe.Gyldighed[0].Virkning = new VirkningType();
            soegInput.TilstandListe.Gyldighed[0].Virkning.FraTidspunkt      = new TidspunktType();
            soegInput.TilstandListe.Gyldighed[0].Virkning.FraTidspunkt.Item = DateTime.Now;

            // only return objects that have a Tilhører relationship top-level Organisation
            UnikIdType orgReference = StubUtil.GetReference <UnikIdType>(registry.MunicipalityOrganisationUUID[OrganisationRegistryProperties.GetCurrentMunicipality()], ItemChoiceType.UUIDIdentifikator);
            OrganisationRelationType organisationRelationType = new OrganisationRelationType();

            organisationRelationType.ReferenceID = orgReference;
            soegInput.RelationListe.Tilhoerer    = organisationRelationType;

            // search
            soegRequest request = new soegRequest();

            request.SoegRequest1                  = new SoegRequestType();
            request.SoegRequest1.SoegInput        = soegInput;
            request.SoegRequest1.AuthorityContext = new AuthorityContextType();
            request.SoegRequest1.AuthorityContext.MunicipalityCVR = OrganisationRegistryProperties.GetCurrentMunicipality();

            try
            {
                soegResponse response   = channel.soeg(request);
                int          statusCode = Int32.Parse(response.SoegResponse1.SoegOutput.StandardRetur.StatusKode);
                if (statusCode != 20 && statusCode != 44) // 44 is empty search result
                {
                    string message = StubUtil.ConstructSoapErrorMessage(statusCode, "Soeg", OrganisationEnhedStubHelper.SERVICE, response.SoegResponse1.SoegOutput.StandardRetur.FejlbeskedTekst);
                    log.Error(message);
                    throw new SoapServiceException(message);
                }

                List <string> functions = new List <string>();
                if (statusCode == 20)
                {
                    foreach (string id in response.SoegResponse1.SoegOutput.IdListe)
                    {
                        functions.Add(id);
                    }
                }

                return(functions);
            }
            catch (Exception ex) when(ex is CommunicationException || ex is IOException || ex is TimeoutException || ex is WebException)
            {
                throw new ServiceNotFoundException("Failed to establish connection to the Soeg service on OrganisationEnhed", ex);
            }
        }
Esempio n. 19
0
        public List <OrgUnitRegWrapper> Read(string antal, string offset, out Boolean moreData)
        {
            moreData = false; // initialize to no-more-data

            FremsoegObjekthierarkiInputType input = new FremsoegObjekthierarkiInputType();

            input.MaksimalAntalKvantitet   = antal;
            input.FoersteResultatReference = offset;

            fremsoegobjekthierarkiRequest request = new fremsoegobjekthierarkiRequest();

            request.FremsoegobjekthierarkiRequest1 = new FremsoegobjekthierarkiRequestType();
            request.FremsoegobjekthierarkiRequest1.FremsoegObjekthierarkiInput      = input;
            request.FremsoegobjekthierarkiRequest1.AuthorityContext                 = new AuthorityContextType();
            request.FremsoegobjekthierarkiRequest1.AuthorityContext.MunicipalityCVR = OrganisationRegistryProperties.GetCurrentMunicipality();

            // send request
            OrganisationSystemPortType channel = StubUtil.CreateChannel <OrganisationSystemPortType>(OrganisationSystemStubHelper.SERVICE, "FremsoegObjektHierarki", helper.CreatePort());

            try
            {
                var result = channel.fremsoegobjekthierarki(request);

                int statusCode = Int32.Parse(result.FremsoegobjekthierarkiResponse1.FremsoegObjekthierarkiOutput.StandardRetur.StatusKode);
                if (statusCode != 20)
                {
                    string message = StubUtil.ConstructSoapErrorMessage(statusCode, "FremsoegObjektHierarki", OrganisationSystemStubHelper.SERVICE, result.FremsoegobjekthierarkiResponse1.FremsoegObjekthierarkiOutput.StandardRetur.FejlbeskedTekst);
                    log.Error(message);
                    throw new SoapServiceException(message);
                }

                var output = result.FremsoegobjekthierarkiResponse1.FremsoegObjekthierarkiOutput;
                if (log.IsDebugEnabled)
                {
                    log.Debug("Found: " + output.OrganisationEnheder.Length + " Enheder, " +
                              output.Interessefaellesskaber.Length + " Interessefaellesskaber, " +
                              output.ItSystemer.Length + " ItSystemer, " +
                              output.Organisationer.Length + " Organisationer, " +
                              output.OrganisationFunktioner.Length + " OrganisationFunktioner");
                }

                if (output.OrganisationEnheder.Length > 0)
                {
                    moreData = true;
                }

                List <OrgUnitRegWrapper> registrations = new List <OrgUnitRegWrapper>();

                var ous = result.FremsoegobjekthierarkiResponse1.FremsoegObjekthierarkiOutput.OrganisationEnheder;
                foreach (var ou in ous)
                {
                    string uuid = ou.ObjektType?.UUIDIdentifikator;

                    if (uuid == null)
                    {
                        log.Warn("OU in hierarchy does not have a uuid");
                    }
                    else if (ou.Registrering == null)
                    {
                        log.Warn("OU in hierarchy does not have a registration: " + uuid);
                    }
                    else
                    {
                        if (ou.Registrering.Length != 1)
                        {
                            log.Warn("OU in hierarchy does has more than one registration: " + uuid);
                        }

                        var reg = ou.Registrering[0];

                        if (StubUtil.GetMunicipalityOrganisationUUID().Equals(reg.RelationListe?.Tilhoerer?.ReferenceID?.Item))
                        {
                            registrations.Add(new OrgUnitRegWrapper()
                            {
                                Uuid         = uuid,
                                Registration = reg
                            });
                        }
                        else
                        {
                            log.Warn("Skipping OrgUnit with Tilhoerer relation unknown Organisation: " + reg.RelationListe?.Tilhoerer?.ReferenceID?.Item);
                        }
                    }
                }

                return(registrations);
            }
            catch (Exception ex) when(ex is CommunicationException || ex is IOException || ex is TimeoutException || ex is WebException)
            {
                throw new ServiceNotFoundException("Failed to establish connection to the Importer service on OrganisationSystem", ex);
            }
        }
Esempio n. 20
0
        public RegistreringType1 GetLatestRegistration(string uuid)
        {
            LaesInputType laesInput = new LaesInputType();

            laesInput.UUIDIdentifikator = uuid;

            laesRequest request = new laesRequest();

            request.LaesRequest1                  = new LaesRequestType();
            request.LaesRequest1.LaesInput        = laesInput;
            request.LaesRequest1.AuthorityContext = new AuthorityContextType();
            request.LaesRequest1.AuthorityContext.MunicipalityCVR = OrganisationRegistryProperties.GetCurrentMunicipality();

            OrganisationEnhedPortType channel = StubUtil.CreateChannel <OrganisationEnhedPortType>(OrganisationEnhedStubHelper.SERVICE, "Laes", helper.CreatePort());

            try
            {
                laesResponse response = channel.laes(request);

                int statusCode = Int32.Parse(response.LaesResponse1.LaesOutput.StandardRetur.StatusKode);
                if (statusCode != 20)
                {
                    // note that statusCode 44 means that the object does not exists, so that is a valid response
                    log.Debug("Lookup on OrgUnit with uuid '" + uuid + "' failed with statuscode " + statusCode);
                    return(null);
                }

                RegistreringType1[] resultSet = response.LaesResponse1.LaesOutput.FiltreretOejebliksbillede.Registrering;
                if (resultSet.Length == 0)
                {
                    log.Warn("OrgUnit with uuid '" + uuid + "' exists, but has no registration");
                    return(null);
                }

                RegistreringType1 result = null;
                if (resultSet.Length > 1)
                {
                    log.Warn("OrgUnit with uuid " + uuid + " has more than one registration when reading latest registration, this should never happen");

                    DateTime winner = DateTime.MinValue;
                    foreach (RegistreringType1 res in resultSet)
                    {
                        // first time through will always result in a True evaluation here
                        if (DateTime.Compare(winner, res.Tidspunkt) < 0)
                        {
                            result = res;
                            winner = res.Tidspunkt;
                        }
                    }
                }
                else
                {
                    result = resultSet[0];
                }

                // we cannot perform any kind of updates on Slettet/Passiveret, så it makes sense to filter them out on lookup,
                // so the rest of the code will default to Import op top of this
                if (result.LivscyklusKode.Equals(LivscyklusKodeType.Slettet) || result.LivscyklusKode.Equals(LivscyklusKodeType.Passiveret))
                {
                    return(null);
                }

                return(result);
            }
            catch (Exception ex) when(ex is CommunicationException || ex is IOException || ex is TimeoutException || ex is WebException)
            {
                throw new ServiceNotFoundException("Failed to establish connection to the Laes service on OrganisationEnhed", ex);
            }
        }
        public void Ret(OrgFunctionData orgFunction, UpdateIndicator userIndicator, UpdateIndicator unitIndicator, UpdateIndicator taskIndicator)
        {
            log.Debug("Attempting Ret on OrganisationFunction with uuid " + orgFunction.Uuid);

            RegistreringType1 registration = GetLatestRegistration(orgFunction.Uuid);

            if (registration == null)
            {
                log.Debug("Cannot call Ret on OrganisationFunktion with uuid " + orgFunction.Uuid + " because it does not exist in Organisation");
                return;
            }

            VirkningType virkning = helper.GetVirkning(orgFunction.Timestamp);

            OrganisationFunktionPortType channel = StubUtil.CreateChannel <OrganisationFunktionPortType>(OrganisationFunktionStubHelper.SERVICE, "Ret", helper.CreatePort());

            try
            {
                bool changes = false;

                RetInputType1 input = new RetInputType1();
                input.UUIDIdentifikator = orgFunction.Uuid;
                input.AttributListe     = registration.AttributListe;
                input.TilstandListe     = registration.TilstandListe;
                input.RelationListe     = registration.RelationListe;

                changes = helper.SetTilstandToActive(virkning, registration, orgFunction.Timestamp) | changes;

                #region Update attributes if needed
                EgenskabType latestProperty = StubUtil.GetLatestProperty(input.AttributListe.Egenskab);
                if (latestProperty == null || latestProperty.FunktionNavn == null ||
                    (orgFunction.Name != null && !latestProperty.FunktionNavn.Equals(orgFunction.Name)) ||
                    (orgFunction.ShortKey != null && !latestProperty.BrugervendtNoegleTekst.Equals(orgFunction.ShortKey)))
                {
                    if (latestProperty == null)
                    {
                        orgFunction.ShortKey = (orgFunction.ShortKey != null) ? orgFunction.ShortKey : IdUtil.GenerateShortKey();

                        // special case where editing a function that has been orphaned, without supplying a name - should never really happen, but the API allows it
                        orgFunction.Name = (orgFunction.Name != null) ? orgFunction.Name : "Unknown Function";
                    }

                    // create a new property
                    EgenskabType newProperty = new EgenskabType();
                    newProperty.Virkning = helper.GetVirkning(orgFunction.Timestamp);
                    newProperty.BrugervendtNoegleTekst = (orgFunction.ShortKey != null) ? orgFunction.ShortKey : latestProperty.BrugervendtNoegleTekst;
                    newProperty.FunktionNavn           = (orgFunction.Name != null) ? orgFunction.Name : latestProperty.FunktionNavn;

                    // create a new set of properties
                    input.AttributListe.Egenskab    = new EgenskabType[1];
                    input.AttributListe.Egenskab[0] = newProperty;

                    changes = true;
                }
                #endregion

                #region update tasks if needed
                if (taskIndicator.Equals(UpdateIndicator.COMPARE))
                {
                    // terminate the Virkning on all address relationships that no longer exists locally
                    changes = StubUtil.TerminateObjectsInOrgNoLongerPresentLocally(input.RelationListe.Opgaver, orgFunction.Tasks, orgFunction.Timestamp, true) || changes;

                    // add references to address objects that are new
                    List <string> taskUuidsToAdd = StubUtil.FindAllObjectsInLocalNotInOrg(input.RelationListe.Opgaver, orgFunction.Tasks, true);

                    if (taskUuidsToAdd.Count > 0)
                    {
                        int size = taskUuidsToAdd.Count + ((input.RelationListe.Opgaver != null) ? input.RelationListe.Opgaver.Length : 0);
                        KlasseFlerRelationType[] newTasks = new KlasseFlerRelationType[size];

                        int i = 0;
                        if (input.RelationListe.Opgaver != null)
                        {
                            foreach (var taskInOrg in input.RelationListe.Opgaver)
                            {
                                newTasks[i++] = taskInOrg;
                            }
                        }

                        foreach (string uuidToAdd in taskUuidsToAdd)
                        {
                            foreach (var taskInLocal in orgFunction.Tasks)
                            {
                                if (taskInLocal.Equals(uuidToAdd))
                                {
                                    KlasseFlerRelationType newTask = helper.CreateOpgaveRelation(uuidToAdd, virkning);
                                    newTasks[i++] = newTask;
                                }
                            }
                        }

                        input.RelationListe.Opgaver = newTasks;
                        changes = true;
                    }
                }
                #endregion

                #region Update TilknyttedeBrugere relationships
                // terminate references
                if (userIndicator.Equals(UpdateIndicator.COMPARE))
                {
                    // terminate the references in Org that no longer exist locally
                    changes = StubUtil.TerminateObjectsInOrgNoLongerPresentLocally(input.RelationListe.TilknyttedeBrugere, orgFunction.Users, orgFunction.Timestamp, false) || changes;
                }
                else if (userIndicator.Equals(UpdateIndicator.REMOVE))
                {
                    changes = TerminateObjectsInOrgThatAreInLocal(input.RelationListe.TilknyttedeBrugere, orgFunction.Users, orgFunction.Timestamp) || changes;
                }

                if (userIndicator.Equals(UpdateIndicator.COMPARE) || userIndicator.Equals(UpdateIndicator.ADD))
                {
                    // get the set of new local objects only
                    List <string> uuidsToAdd = StubUtil.FindAllObjectsInLocalNotInOrg(input.RelationListe.TilknyttedeBrugere, orgFunction.Users, false);

                    // add all the new references
                    if (uuidsToAdd.Count > 0)
                    {
                        int size = uuidsToAdd.Count + ((input.RelationListe.TilknyttedeBrugere != null) ? input.RelationListe.TilknyttedeBrugere.Length : 0);
                        BrugerFlerRelationType[] newUsers = new BrugerFlerRelationType[size];

                        int i = 0;
                        if (input.RelationListe.TilknyttedeBrugere != null)
                        {
                            foreach (var usersInOrg in input.RelationListe.TilknyttedeBrugere)
                            {
                                newUsers[i++] = usersInOrg;
                            }
                        }

                        foreach (string uuidToAdd in uuidsToAdd)
                        {
                            newUsers[i++] = helper.CreateBrugerRelation(uuidToAdd, virkning);
                        }

                        input.RelationListe.TilknyttedeBrugere = newUsers;
                        changes = true;
                    }
                }
                #endregion

                #region Update TilknyttedeEnheder relationships
                // terminate references
                if (unitIndicator.Equals(UpdateIndicator.COMPARE))
                {
                    // terminate the references in Org that no longer exist locally
                    changes = StubUtil.TerminateObjectsInOrgNoLongerPresentLocally(input.RelationListe.TilknyttedeEnheder, orgFunction.OrgUnits, orgFunction.Timestamp, false) || changes;
                }
                else if (unitIndicator.Equals(UpdateIndicator.REMOVE))
                {
                    changes = TerminateObjectsInOrgThatAreInLocal(input.RelationListe.TilknyttedeEnheder, orgFunction.OrgUnits, orgFunction.Timestamp) || changes;
                }

                if (unitIndicator.Equals(UpdateIndicator.COMPARE) || unitIndicator.Equals(UpdateIndicator.ADD))
                {
                    // get the set of new local objects
                    List <string> uuidsToAdd = StubUtil.FindAllObjectsInLocalNotInOrg(input.RelationListe.TilknyttedeEnheder, orgFunction.OrgUnits, false);

                    // add all the new references
                    if (uuidsToAdd.Count > 0)
                    {
                        int size = uuidsToAdd.Count + ((input.RelationListe.TilknyttedeEnheder != null) ? input.RelationListe.TilknyttedeEnheder.Length : 0);
                        OrganisationEnhedFlerRelationType[] newUnits = new OrganisationEnhedFlerRelationType[size];

                        int i = 0;
                        if (input.RelationListe.TilknyttedeEnheder != null)
                        {
                            foreach (var unit in input.RelationListe.TilknyttedeEnheder)
                            {
                                newUnits[i++] = unit;
                            }
                        }

                        foreach (string uuidToAdd in uuidsToAdd)
                        {
                            newUnits[i++] = helper.CreateOrgEnhedRelation(uuidToAdd, virkning);
                        }

                        input.RelationListe.TilknyttedeEnheder = newUnits;
                        changes = true;
                    }
                }
                #endregion

                #region Update organisation relationship
                bool foundExistingValidOrganisationRelation = false;
                if (registration.RelationListe.TilknyttedeOrganisationer != null && registration.RelationListe.TilknyttedeOrganisationer.Length > 0)
                {
                    foreach (OrganisationFlerRelationType orgRelation in registration.RelationListe.TilknyttedeOrganisationer)
                    {
                        // make sure that the pointer is set correctly
                        if (!StubUtil.GetMunicipalityOrganisationUUID().Equals(orgRelation.ReferenceID.Item))
                        {
                            orgRelation.ReferenceID.Item = StubUtil.GetMunicipalityOrganisationUUID();
                            changes = true;
                        }

                        // update the Virkning on the TilknyttedeOrganisationer relationship if needed (undelete feature)
                        object endTime = orgRelation.Virkning.TilTidspunkt.Item;

                        // endTime is bool => ok
                        // endTime is DateTime, but Now is before endTime => ok
                        if (!(endTime is DateTime) || (DateTime.Compare(DateTime.Now, (DateTime)endTime) < 0))
                        {
                            foundExistingValidOrganisationRelation = true;
                        }
                    }
                }

                if (!foundExistingValidOrganisationRelation)
                {
                    helper.AddOrganisationRelation(StubUtil.GetMunicipalityOrganisationUUID(), virkning, registration);
                    changes = true;
                }
                #endregion

                // TODO: addresses are not currently used for functions, this is a left-over from the days of it-systems and JumpUrls
                #region Update Address relationships
                // terminate the Virkning on all address relationships that no longer exists locally
                changes = StubUtil.TerminateObjectsInOrgNoLongerPresentLocally(input.RelationListe.Adresser, orgFunction.Addresses, orgFunction.Timestamp, true) || changes;

                // add references to address objects that are new
                List <string> addressUuidsToAdd = StubUtil.FindAllObjectsInLocalNotInOrg(input.RelationListe.Adresser, orgFunction.Addresses, true);

                if (addressUuidsToAdd.Count > 0)
                {
                    int size = addressUuidsToAdd.Count + ((input.RelationListe.Adresser != null) ? input.RelationListe.Adresser.Length : 0);
                    AdresseFlerRelationType[] newAdresser = new AdresseFlerRelationType[size];

                    int i = 0;
                    if (input.RelationListe.Adresser != null)
                    {
                        foreach (var addressInOrg in input.RelationListe.Adresser)
                        {
                            newAdresser[i++] = addressInOrg;
                        }
                    }

                    foreach (string uuidToAdd in addressUuidsToAdd)
                    {
                        foreach (var addressInLocal in orgFunction.Addresses)
                        {
                            if (addressInLocal.Uuid.Equals(uuidToAdd))
                            {
                                string roleUuid = null;
                                switch (addressInLocal.Type)
                                {
                                case AddressRelationType.URL:
                                    roleUuid = UUIDConstants.ADDRESS_ROLE_ORGFUNCTION_URL;
                                    break;

                                default:
                                    log.Warn("Cannot add relationship to address of type " + addressInLocal.Type + " with uuid " + addressInLocal.Uuid + " as the type is unknown");
                                    continue;
                                }

                                AdresseFlerRelationType newAddress = helper.CreateAddressReference(uuidToAdd, (i + 1), roleUuid, virkning);
                                newAdresser[i++] = newAddress;
                            }
                        }
                    }

                    input.RelationListe.Adresser = newAdresser;
                    changes = true;
                }
                #endregion

                // if no changes are made, we do not call the service
                if (!changes)
                {
                    log.Debug("Ret on OrganisationFunktion with uuid " + orgFunction.Uuid + " cancelled because of no changes");
                    return;
                }

                // send Ret request
                retRequest request = new retRequest();
                request.RetRequest1                  = new RetRequestType();
                request.RetRequest1.RetInput         = input;
                request.RetRequest1.AuthorityContext = new AuthorityContextType();
                request.RetRequest1.AuthorityContext.MunicipalityCVR = OrganisationRegistryProperties.GetMunicipality();

                retResponse response = channel.ret(request);

                int statusCode = Int32.Parse(response.RetResponse1.RetOutput.StandardRetur.StatusKode);
                if (statusCode != 20)
                {
                    string message = StubUtil.ConstructSoapErrorMessage(statusCode, "Ret", OrganisationFunktionStubHelper.SERVICE, response.RetResponse1.RetOutput.StandardRetur.FejlbeskedTekst);
                    log.Error(message);
                    throw new SoapServiceException(message);
                }

                log.Debug("Ret succesful on OrganisationFunktion with uuid " + orgFunction.Uuid);
            }
            catch (Exception ex) when(ex is CommunicationException || ex is IOException || ex is TimeoutException || ex is WebException)
            {
                throw new ServiceNotFoundException("Failed to establish connection to the Ret service on OrganisationFunktion", ex);
            }
        }
        public void Deactivate(string uuid, DateTime timestamp)
        {
            log.Debug("Attempting Deactivate on OrganisationFunktion with uuid " + uuid);

            RegistreringType1 registration = GetLatestRegistration(uuid);

            if (registration == null)
            {
                log.Debug("Cannot call Deactivate on OrganisationFunktion with uuid " + uuid + " because it does not exist in Organisation");
                return;
            }

            OrganisationFunktionPortType channel = StubUtil.CreateChannel <OrganisationFunktionPortType>(OrganisationFunktionStubHelper.SERVICE, "Ret", helper.CreatePort());

            try
            {
                RetInputType1 input = new RetInputType1();
                input.UUIDIdentifikator = uuid;
                input.AttributListe     = registration.AttributListe;
                input.TilstandListe     = registration.TilstandListe;
                input.RelationListe     = registration.RelationListe;

                // cut relationship to all users
                if (input.RelationListe.TilknyttedeBrugere != null && input.RelationListe.TilknyttedeBrugere.Length > 0)
                {
                    foreach (var bruger in input.RelationListe.TilknyttedeBrugere)
                    {
                        StubUtil.TerminateVirkning(bruger.Virkning, timestamp);
                    }
                }

                // cut relationship to all orgUnits
                if (input.RelationListe.TilknyttedeEnheder != null && input.RelationListe.TilknyttedeEnheder.Length > 0)
                {
                    foreach (var enhed in input.RelationListe.TilknyttedeEnheder)
                    {
                        StubUtil.TerminateVirkning(enhed.Virkning, timestamp);
                    }
                }

                // cut relationship to all itSystems
                if (input.RelationListe.TilknyttedeItSystemer != null && input.RelationListe.TilknyttedeItSystemer.Length > 0)
                {
                    foreach (var itSystem in input.RelationListe.TilknyttedeItSystemer)
                    {
                        StubUtil.TerminateVirkning(itSystem.Virkning, timestamp);
                    }
                }

                // actually deactivate function
                VirkningType virkning = helper.GetVirkning(timestamp);
                helper.SetTilstandToInactive(virkning, registration, timestamp);

                retRequest request = new retRequest();
                request.RetRequest1                  = new RetRequestType();
                request.RetRequest1.RetInput         = input;
                request.RetRequest1.AuthorityContext = new AuthorityContextType();
                request.RetRequest1.AuthorityContext.MunicipalityCVR = OrganisationRegistryProperties.GetMunicipality();

                retResponse response = channel.ret(request);

                int statusCode = Int32.Parse(response.RetResponse1.RetOutput.StandardRetur.StatusKode);
                if (statusCode != 20)
                {
                    string message = StubUtil.ConstructSoapErrorMessage(statusCode, "Ret", OrganisationFunktionStubHelper.SERVICE, response.RetResponse1.RetOutput.StandardRetur.FejlbeskedTekst);
                    log.Error(message);
                    throw new SoapServiceException(message);
                }

                log.Debug("Deactivate on OrganisationFunktion with uuid " + uuid + " succeded");
            }
            catch (Exception ex) when(ex is CommunicationException || ex is IOException || ex is TimeoutException || ex is WebException)
            {
                throw new ServiceNotFoundException("Failed to establish connection to the Ret service on OrganisationFunktion", ex);
            }
        }
        private List <string> Soeg(string functionsTypeUuid, string userUuid, string unitUuid, string itSystemUuid)
        {
            OrganisationFunktionPortType channel = StubUtil.CreateChannel <OrganisationFunktionPortType>(OrganisationFunktionStubHelper.SERVICE, "Soeg", helper.CreatePort());

            SoegInputType1 soegInput = new SoegInputType1();

            soegInput.AttributListe = new AttributListeType();
            soegInput.RelationListe = new RelationListeType();
            soegInput.TilstandListe = new TilstandListeType();

            // only return objects that have a Tilhører relationship top-level Organisation
            UnikIdType orgReference = StubUtil.GetReference <UnikIdType>(registry.MunicipalityOrganisationUUID[OrganisationRegistryProperties.GetMunicipality()], ItemChoiceType.UUIDIdentifikator);

            soegInput.RelationListe.TilknyttedeOrganisationer                = new OrganisationFlerRelationType[1];
            soegInput.RelationListe.TilknyttedeOrganisationer[0]             = new OrganisationFlerRelationType();
            soegInput.RelationListe.TilknyttedeOrganisationer[0].ReferenceID = orgReference;

            if (!String.IsNullOrEmpty(functionsTypeUuid))
            {
                UnikIdType reference = new UnikIdType();
                reference.Item            = functionsTypeUuid;
                reference.ItemElementName = ItemChoiceType.UUIDIdentifikator;

                KlasseRelationType funktionsType = new KlasseRelationType();
                funktionsType.ReferenceID             = reference;
                soegInput.RelationListe.Funktionstype = funktionsType;
            }

            if (!String.IsNullOrEmpty(userUuid))
            {
                UnikIdType reference = new UnikIdType();
                reference.Item            = userUuid;
                reference.ItemElementName = ItemChoiceType.UUIDIdentifikator;

                soegInput.RelationListe.TilknyttedeBrugere                = new BrugerFlerRelationType[1];
                soegInput.RelationListe.TilknyttedeBrugere[0]             = new BrugerFlerRelationType();
                soegInput.RelationListe.TilknyttedeBrugere[0].ReferenceID = reference;
            }

            if (!String.IsNullOrEmpty(unitUuid))
            {
                UnikIdType reference = new UnikIdType();
                reference.Item            = unitUuid;
                reference.ItemElementName = ItemChoiceType.UUIDIdentifikator;

                soegInput.RelationListe.TilknyttedeEnheder                = new OrganisationEnhedFlerRelationType[1];
                soegInput.RelationListe.TilknyttedeEnheder[0]             = new OrganisationEnhedFlerRelationType();
                soegInput.RelationListe.TilknyttedeEnheder[0].ReferenceID = reference;
            }

            if (!String.IsNullOrEmpty(itSystemUuid))
            {
                UnikIdType reference = new UnikIdType();
                reference.Item            = itSystemUuid;
                reference.ItemElementName = ItemChoiceType.UUIDIdentifikator;

                soegInput.RelationListe.TilknyttedeItSystemer                = new ItSystemFlerRelationType[1];
                soegInput.RelationListe.TilknyttedeItSystemer[0]             = new ItSystemFlerRelationType();
                soegInput.RelationListe.TilknyttedeItSystemer[0].ReferenceID = reference;
            }

            // search
            soegRequest request = new soegRequest();

            request.SoegRequest1                  = new SoegRequestType();
            request.SoegRequest1.SoegInput        = soegInput;
            request.SoegRequest1.AuthorityContext = new AuthorityContextType();
            request.SoegRequest1.AuthorityContext.MunicipalityCVR = OrganisationRegistryProperties.GetMunicipality();

            try
            {
                soegResponse response   = channel.soeg(request);
                int          statusCode = Int32.Parse(response.SoegResponse1.SoegOutput.StandardRetur.StatusKode);
                if (statusCode != 20 && statusCode != 44) // 44 is empty search result
                {
                    string message = StubUtil.ConstructSoapErrorMessage(statusCode, "Soeg", OrganisationFunktionStubHelper.SERVICE, response.SoegResponse1.SoegOutput.StandardRetur.FejlbeskedTekst);
                    log.Error(message);
                    throw new SoapServiceException(message);
                }

                List <string> functions = new List <string>();
                if (statusCode == 20)
                {
                    foreach (string id in response.SoegResponse1.SoegOutput.IdListe)
                    {
                        functions.Add(id);
                    }
                }

                return(functions);
            }
            catch (Exception ex) when(ex is CommunicationException || ex is IOException || ex is TimeoutException || ex is WebException)
            {
                throw new ServiceNotFoundException("Failed to establish connection to the Soeg service on OrganisationFunktion", ex);
            }
        }
        public void Importer(OrgFunctionData orgFunction)
        {
            // create ShortKey and Uuid if not supplied
            EnsureKeys(orgFunction);

            log.Debug("Attempting Import on OrgFunction with uuid " + orgFunction.Uuid);

            // create timestamp object to be used on all registrations, properties and relations
            VirkningType virkning = helper.GetVirkning(orgFunction.Timestamp);

            // setup registration
            RegistreringType1 registration = helper.CreateRegistration(orgFunction.Timestamp, LivscyklusKodeType.Importeret);

            // add properties
            helper.AddProperties(orgFunction.ShortKey, orgFunction.Name, virkning, registration);

            // add relationships on registration
            helper.AddTilknyttedeBrugere(orgFunction.Users, virkning, registration);
            helper.AddTilknyttedeEnheder(orgFunction.OrgUnits, virkning, registration);
            helper.AddTilknyttedeItSystemer(orgFunction.ItSystems, virkning, registration);
            helper.AddOpgaver(orgFunction.Tasks, virkning, registration);
            helper.AddOrganisationRelation(StubUtil.GetMunicipalityOrganisationUUID(), virkning, registration);
            helper.AddAddressReferences(orgFunction.Addresses, virkning, registration);
            helper.SetFunktionsType(orgFunction.FunctionTypeUuid, virkning, registration);

            // set Tilstand to Active
            helper.SetTilstandToActive(virkning, registration, orgFunction.Timestamp);

            // wire everything together
            OrganisationFunktionType organisationFunktionType = helper.GetOrganisationFunktionType(orgFunction.Uuid, registration);
            ImportInputType          importInput = new ImportInputType();

            importInput.OrganisationFunktion = organisationFunktionType;

            // construct request
            importerRequest request = new importerRequest();

            request.ImporterRequest1                  = new ImporterRequestType();
            request.ImporterRequest1.ImportInput      = importInput;
            request.ImporterRequest1.AuthorityContext = new AuthorityContextType();
            request.ImporterRequest1.AuthorityContext.MunicipalityCVR = OrganisationRegistryProperties.GetMunicipality();

            // send request
            OrganisationFunktionPortType channel = StubUtil.CreateChannel <OrganisationFunktionPortType>(OrganisationFunktionStubHelper.SERVICE, "Import", helper.CreatePort());

            try
            {
                importerResponse result = channel.importer(request);

                int statusCode = Int32.Parse(result.ImporterResponse1.ImportOutput.StandardRetur.StatusKode);
                if (statusCode != 20)
                {
                    string message = StubUtil.ConstructSoapErrorMessage(statusCode, "Import", OrganisationFunktionStubHelper.SERVICE, result.ImporterResponse1.ImportOutput.StandardRetur.FejlbeskedTekst);
                    log.Error(message);
                    throw new SoapServiceException(message);
                }

                log.Debug("Import successful on OrgFunction with uuid " + orgFunction.Uuid);
            }
            catch (Exception ex) when(ex is CommunicationException || ex is IOException || ex is TimeoutException || ex is WebException)
            {
                throw new ServiceNotFoundException("Failed to establish connection to the Importer service on OrganisationFunktion", ex);
            }
        }
Esempio n. 25
0
        public void Deactivate(string uuid, DateTime timestamp)
        {
            log.Debug("Attempting Deactivate on OrganisationEnhed with uuid " + uuid);

            RegistreringType1 registration = GetLatestRegistration(uuid);

            if (registration == null)
            {
                log.Debug("Cannot Deactivate OrganisationEnhed with uuid " + uuid + " because it does not exist in Organisation");
                return;
            }

            OrganisationEnhedPortType channel = StubUtil.CreateChannel <OrganisationEnhedPortType>(OrganisationEnhedStubHelper.SERVICE, "Ret", helper.CreatePort());

            try
            {
                RetInputType1 input = new RetInputType1();
                input.UUIDIdentifikator = uuid;
                input.AttributListe     = registration.AttributListe;
                input.TilstandListe     = registration.TilstandListe;
                input.RelationListe     = registration.RelationListe;

                // cut relationship to Parent
                if (input.RelationListe.Overordnet != null)
                {
                    StubUtil.TerminateVirkning(input.RelationListe.Overordnet.Virkning, timestamp);
                }

                // cut relationship to all functions (payout unit references and contact places)
                if (input.RelationListe.TilknyttedeFunktioner != null && input.RelationListe.TilknyttedeFunktioner.Length > 0)
                {
                    foreach (OrganisationFunktionFlerRelationType funktion in input.RelationListe.TilknyttedeFunktioner)
                    {
                        StubUtil.TerminateVirkning(funktion.Virkning, timestamp);
                    }
                }

                // cut relationship to all Opgaver
                if (input.RelationListe.Opgaver != null && input.RelationListe.Opgaver.Length > 0)
                {
                    foreach (var opgave in input.RelationListe.Opgaver)
                    {
                        StubUtil.TerminateVirkning(opgave.Virkning, timestamp);
                    }
                }

                VirkningType virkning = helper.GetVirkning(timestamp);
                helper.SetTilstandToInactive(virkning, registration, timestamp);

                retRequest request = new retRequest();
                request.RetRequest1                  = new RetRequestType();
                request.RetRequest1.RetInput         = input;
                request.RetRequest1.AuthorityContext = new AuthorityContextType();
                request.RetRequest1.AuthorityContext.MunicipalityCVR = OrganisationRegistryProperties.GetCurrentMunicipality();

                retResponse response = channel.ret(request);

                int statusCode = Int32.Parse(response.RetResponse1.RetOutput.StandardRetur.StatusKode);
                if (statusCode != 20)
                {
                    if (statusCode == 49)
                    {
                        log.Warn("Deactive failed on OrgUnit " + uuid + " as Organisation returned status 49. The most likely cause is that the object has been Passiveret");
                        return;
                    }

                    string message = StubUtil.ConstructSoapErrorMessage(statusCode, "Ret", OrganisationEnhedStubHelper.SERVICE, response.RetResponse1.RetOutput.StandardRetur.FejlbeskedTekst);
                    log.Error(message);
                    throw new SoapServiceException(message);
                }

                log.Debug("Deactivate successful on OrganisationEnhed with uuid " + uuid);
            }
            catch (Exception ex) when(ex is CommunicationException || ex is IOException || ex is TimeoutException || ex is WebException)
            {
                throw new ServiceNotFoundException("Failed to establish connection to the Ret service on OrganisationEnhed", ex);
            }
        }
Esempio n. 26
0
        public void Ret(UserData user)
        {
            log.Debug("Attempting Ret on Bruger with uuid " + user.Uuid);

            RegistreringType1 registration = GetLatestRegistration(user.Uuid);

            if (registration == null)
            {
                log.Debug("Cannot call Ret on Bruger with uuid " + user.Uuid + " because it does not exist in Organisation");
                return;
            }

            VirkningType virkning = helper.GetVirkning(user.Timestamp);

            BrugerPortType channel = StubUtil.CreateChannel <BrugerPortType>(BrugerStubHelper.SERVICE, "Ret", helper.CreatePort());

            try
            {
                bool changes = false;

                RetInputType1 input = new RetInputType1();
                input.UUIDIdentifikator = user.Uuid;
                input.AttributListe     = registration.AttributListe;
                input.TilstandListe     = registration.TilstandListe;
                input.RelationListe     = registration.RelationListe;

                // set Tilstand to Active (idempotent change - but it ensures that a previously deactived object is re-activated)
                changes = helper.SetTilstandToActive(virkning, registration, user.Timestamp) | changes;

                #region Update attributes

                // compare latest property to the local object
                EgenskabType latestProperty = StubUtil.GetLatestProperty(input.AttributListe.Egenskab);
                if (latestProperty == null || !latestProperty.BrugerNavn.Equals(user.UserId) || (user.ShortKey != null && !latestProperty.BrugervendtNoegleTekst.Equals(user.ShortKey)))
                {
                    // end the validity of open-ended property
                    if (latestProperty == null)
                    {
                        // create ShortKey if not supplied
                        EnsureKeys(user);
                    }

                    // create a new property
                    EgenskabType newProperty = new EgenskabType();
                    newProperty.Virkning = helper.GetVirkning(user.Timestamp);
                    newProperty.BrugervendtNoegleTekst = ((user.ShortKey != null) ? user.ShortKey : latestProperty.BrugervendtNoegleTekst);
                    newProperty.BrugerNavn             = user.UserId;

                    // create a new set of properties
                    input.AttributListe.Egenskab    = new EgenskabType[1];
                    input.AttributListe.Egenskab[0] = newProperty;

                    changes = true;
                }
                #endregion

                #region Update address relationships
                // terminate the Virkning on all address relationships that no longer exists locally
                changes = StubUtil.TerminateObjectsInOrgNoLongerPresentLocally(input.RelationListe.Adresser, user.Addresses, user.Timestamp, true) || changes;

                // add references to address objects that are new
                List <string> uuidsToAdd = StubUtil.FindAllObjectsInLocalNotInOrg(input.RelationListe.Adresser, user.Addresses, true);

                if (uuidsToAdd.Count > 0)
                {
                    int size = uuidsToAdd.Count + ((input.RelationListe.Adresser != null) ? input.RelationListe.Adresser.Length : 0);
                    AdresseFlerRelationType[] newAdresser = new AdresseFlerRelationType[size];

                    int i = 0;
                    if (input.RelationListe.Adresser != null)
                    {
                        foreach (var addressInOrg in input.RelationListe.Adresser)
                        {
                            newAdresser[i++] = addressInOrg;
                        }
                    }

                    foreach (string uuidToAdd in uuidsToAdd)
                    {
                        foreach (var addressInLocal in user.Addresses)
                        {
                            if (addressInLocal.Uuid.Equals(uuidToAdd))
                            {
                                string roleUuid = null;
                                switch (addressInLocal.Type)
                                {
                                case AddressRelationType.EMAIL:
                                    roleUuid = UUIDConstants.ADDRESS_ROLE_USER_EMAIL;
                                    break;

                                case AddressRelationType.PHONE:
                                    roleUuid = UUIDConstants.ADDRESS_ROLE_USER_PHONE;
                                    break;

                                case AddressRelationType.LOCATION:
                                    roleUuid = UUIDConstants.ADDRESS_ROLE_USER_LOCATION;
                                    break;

                                default:
                                    log.Warn("Cannot add relationship to address of type " + addressInLocal.Type + " with uuid " + addressInLocal.Uuid + " as the type is unknown");
                                    continue;
                                }

                                AdresseFlerRelationType newAddress = helper.CreateAddressReference(uuidToAdd, (i + 1), roleUuid, virkning);
                                newAdresser[i++] = newAddress;
                            }
                        }
                    }
                    input.RelationListe.Adresser = newAdresser;
                    changes = true;
                }
                #endregion

                #region Update organisation relationship
                if (registration.RelationListe.Tilhoerer != null)
                {
                    // make sure that the pointer is set correctly
                    if (!StubUtil.GetMunicipalityOrganisationUUID().Equals(registration.RelationListe.Tilhoerer.ReferenceID.Item))
                    {
                        registration.RelationListe.Tilhoerer.ReferenceID.Item = StubUtil.GetMunicipalityOrganisationUUID();
                        changes = true;
                    }

                    // update the Virkning on the Tilhører relationship if needed (undelete feature)
                    object endTime = registration.RelationListe.Tilhoerer.Virkning.TilTidspunkt.Item;

                    if (endTime is DateTime && (DateTime.Compare(DateTime.Now, (DateTime)endTime) >= 0))
                    {
                        log.Debug("Re-establishing relationship with Organisation for Bruger " + user.Uuid);
                        registration.RelationListe.Tilhoerer.Virkning = virkning;
                        changes = true;
                    }
                }
                else
                {
                    // no existing relationship (should actually never happen, but let us just take care of it)
                    helper.AddOrganisationRelation(StubUtil.GetMunicipalityOrganisationUUID(), virkning, registration);
                    changes = true;
                }
                #endregion

                #region Update person relationship
                PersonFlerRelationType existingPerson = BrugerStubHelper.GetLatestPersonFlerRelationType(registration.RelationListe.TilknyttedePersoner);
                if (existingPerson != null)
                {
                    // It really shouldn't happen that often that the Person reference changes on a User, but we support it nonetheless
                    if (!existingPerson.ReferenceID.Item.Equals(user.PersonUuid))
                    {
                        // terminiate existing relationship, and add a new one
                        StubUtil.TerminateVirkning(existingPerson.Virkning, user.Timestamp);

                        // create a new person relation
                        PersonFlerRelationType newPerson = new PersonFlerRelationType();
                        newPerson.Virkning    = helper.GetVirkning(user.Timestamp);
                        newPerson.ReferenceID = StubUtil.GetReference <UnikIdType>(user.PersonUuid, ItemChoiceType.UUIDIdentifikator);

                        // create a new set of person references, containing the new user
                        PersonFlerRelationType[] oldPersons = registration.RelationListe.TilknyttedePersoner;
                        input.RelationListe.TilknyttedePersoner = new PersonFlerRelationType[oldPersons.Length + 1];
                        for (int i = 0; i < oldPersons.Length; i++)
                        {
                            input.RelationListe.TilknyttedePersoner[i] = oldPersons[i];
                        }
                        input.RelationListe.TilknyttedePersoner[oldPersons.Length] = newPerson;

                        changes = true;
                    }
                }
                else
                {
                    // This really shouldn't have happened, as it means we have an existing User without a Person attached - but
                    // we will just fix it, and create the reference on this user

                    log.Warn("Ret on Bruge with uuid " + user.Uuid + " encountered a registration with NO relationship to a Person - fixing it!");
                    helper.AddPersonRelationship(user.PersonUuid, virkning, registration);
                    changes = true;
                }
                #endregion

                // if no changes are made, we do not call the service
                if (!changes)
                {
                    log.Debug("Ret on Bruger with uuid " + user.Uuid + " cancelled because of no changes");
                    return;
                }

                // send Ret request
                retRequest request = new retRequest();
                request.RetRequest1                  = new RetRequestType();
                request.RetRequest1.RetInput         = input;
                request.RetRequest1.AuthorityContext = new AuthorityContextType();
                request.RetRequest1.AuthorityContext.MunicipalityCVR = OrganisationRegistryProperties.GetMunicipality();

                retResponse response = channel.ret(request);

                int statusCode = Int32.Parse(response.RetResponse1.RetOutput.StandardRetur.StatusKode);
                if (statusCode != 20)
                {
                    string message = StubUtil.ConstructSoapErrorMessage(statusCode, "Ret", BrugerStubHelper.SERVICE, response.RetResponse1.RetOutput.StandardRetur.FejlbeskedTekst);
                    log.Error(message);
                    throw new SoapServiceException(message);
                }

                log.Debug("Ret succesful on Bruger with uuid " + user.Uuid);
            }
            catch (Exception ex) when(ex is CommunicationException || ex is IOException || ex is TimeoutException || ex is WebException)
            {
                throw new ServiceNotFoundException("Failed to establish connection to the Ret service on Bruger", ex);
            }
        }
Esempio n. 27
0
        public void Ret(OrgUnitData unit)
        {
            log.Debug("Attempting Ret on OrganisationEnhed with uuid " + unit.Uuid);

            RegistreringType1 registration = GetLatestRegistration(unit.Uuid);

            if (registration == null)
            {
                log.Debug("Cannot call Ret on OrganisationEnhed with uuid " + unit.Uuid + " because it does not exist in Organisation");
                return;
            }

            VirkningType virkning = helper.GetVirkning(unit.Timestamp);

            OrganisationEnhedPortType channel = StubUtil.CreateChannel <OrganisationEnhedPortType>(OrganisationEnhedStubHelper.SERVICE, "Ret", helper.CreatePort());

            try
            {
                bool changes = false;

                RetInputType1 input = new RetInputType1();
                input.UUIDIdentifikator = unit.Uuid;
                input.AttributListe     = registration.AttributListe;
                input.TilstandListe     = registration.TilstandListe;
                input.RelationListe     = registration.RelationListe;

                changes = helper.SetTilstandToActive(virkning, registration, unit.Timestamp) | changes;

                #region Update attributes

                // compare latest property to the local object
                EgenskabType latestProperty = StubUtil.GetLatestProperty(input.AttributListe.Egenskab);
                if (latestProperty == null || !latestProperty.EnhedNavn.Equals(unit.Name) || (unit.ShortKey != null && !latestProperty.BrugervendtNoegleTekst.Equals(unit.ShortKey)))
                {
                    if (latestProperty == null)
                    {
                        EnsureKeys(unit);
                    }

                    // create a new property
                    EgenskabType newProperty = new EgenskabType();
                    newProperty.Virkning = helper.GetVirkning(unit.Timestamp);
                    newProperty.BrugervendtNoegleTekst = ((unit.ShortKey != null) ? unit.ShortKey : latestProperty.BrugervendtNoegleTekst);
                    newProperty.EnhedNavn = unit.Name;

                    // create a new set of properties
                    input.AttributListe.Egenskab    = new EgenskabType[1];
                    input.AttributListe.Egenskab[0] = newProperty;

                    changes = true;
                }
                #endregion

                #region Update address relationships
                // terminate the Virkning on all address relationships that no longer exists locally
                changes = StubUtil.TerminateObjectsInOrgNoLongerPresentLocally(input.RelationListe.Adresser, unit.Addresses, unit.Timestamp, true) || changes;

                // add references to address objects that are new
                List <string> uuidsToAdd = StubUtil.FindAllObjectsInLocalNotInOrg(input.RelationListe.Adresser, unit.Addresses, true);

                if (uuidsToAdd.Count > 0)
                {
                    int size = uuidsToAdd.Count + ((input.RelationListe.Adresser != null) ? input.RelationListe.Adresser.Length : 0);
                    AdresseFlerRelationType[] newAdresser = new AdresseFlerRelationType[size];

                    int i = 0;
                    if (input.RelationListe.Adresser != null)
                    {
                        foreach (var addressInOrg in input.RelationListe.Adresser)
                        {
                            newAdresser[i++] = addressInOrg;
                        }
                    }

                    foreach (string uuidToAdd in uuidsToAdd)
                    {
                        foreach (var addressInLocal in unit.Addresses)
                        {
                            if (addressInLocal.Uuid.Equals(uuidToAdd))
                            {
                                string roleUuid = null;
                                switch (addressInLocal.Type)
                                {
                                case AddressRelationType.EMAIL:
                                    roleUuid = UUIDConstants.ADDRESS_ROLE_ORGUNIT_EMAIL;
                                    break;

                                case AddressRelationType.PHONE:
                                    roleUuid = UUIDConstants.ADDRESS_ROLE_ORGUNIT_PHONE;
                                    break;

                                case AddressRelationType.LOCATION:
                                    roleUuid = UUIDConstants.ADDRESS_ROLE_ORGUNIT_LOCATION;
                                    break;

                                case AddressRelationType.LOSSHORTNAME:
                                    roleUuid = UUIDConstants.ADDRESS_ROLE_ORGUNIT_LOSSHORTNAME;
                                    break;

                                case AddressRelationType.CONTACT_ADDRESS_OPEN_HOURS:
                                    roleUuid = UUIDConstants.ADDRESS_ROLE_ORGUNIT_CONTACT_ADDRESS_OPEN_HOURS;
                                    break;

                                case AddressRelationType.DTR_ID:
                                    roleUuid = UUIDConstants.ADDRESS_ROLE_ORGUNIT_DTR_ID;
                                    break;

                                case AddressRelationType.URL:
                                    roleUuid = UUIDConstants.ADDRESS_ROLE_ORGUNIT_URL;
                                    break;

                                case AddressRelationType.LANDLINE:
                                    roleUuid = UUIDConstants.ADDRESS_ROLE_ORGUNIT_LANDLINE;
                                    break;

                                case AddressRelationType.EAN:
                                    roleUuid = UUIDConstants.ADDRESS_ROLE_ORGUNIT_EAN;
                                    break;

                                case AddressRelationType.LOSID:
                                    roleUuid = UUIDConstants.ADDRESS_ROLE_ORGUNIT_LOSID;
                                    break;

                                case AddressRelationType.EMAIL_REMARKS:
                                    roleUuid = UUIDConstants.ADDRESS_ROLE_ORGUNIT_EMAIL_REMARKS;
                                    break;

                                case AddressRelationType.POST_RETURN:
                                    roleUuid = UUIDConstants.ADDRESS_ROLE_ORGUNIT_POST_RETURN;
                                    break;

                                case AddressRelationType.CONTACT_ADDRESS:
                                    roleUuid = UUIDConstants.ADDRESS_ROLE_ORGUNIT_CONTACT_ADDRESS;
                                    break;

                                case AddressRelationType.POST:
                                    roleUuid = UUIDConstants.ADDRESS_ROLE_ORGUNIT_POST;
                                    break;

                                case AddressRelationType.PHONE_OPEN_HOURS:
                                    roleUuid = UUIDConstants.ADDRESS_ROLE_ORGUNIT_PHONE_OPEN_HOURS;
                                    break;

                                default:
                                    log.Warn("Cannot add relationship to address of type " + addressInLocal.Type + " with uuid " + addressInLocal.Uuid + " as the type is unknown");
                                    continue;
                                }

                                AdresseFlerRelationType newAddress = helper.CreateAddressReference(uuidToAdd, (i + 1), roleUuid, virkning);
                                newAdresser[i++] = newAddress;
                            }
                        }
                    }
                    input.RelationListe.Adresser = newAdresser;
                    changes = true;
                }
                #endregion

                #region Update organisation relationship
                if (registration.RelationListe.Tilhoerer != null)
                {
                    // make sure that the pointer is set correctly
                    if (!StubUtil.GetMunicipalityOrganisationUUID().Equals(registration.RelationListe.Tilhoerer.ReferenceID.Item))
                    {
                        registration.RelationListe.Tilhoerer.ReferenceID.Item = StubUtil.GetMunicipalityOrganisationUUID();
                        changes = true;
                    }

                    // update the Virkning on the Tilhører relationship if needed (undelete feature)
                    object endTime = registration.RelationListe.Tilhoerer.Virkning.TilTidspunkt.Item;

                    if ((endTime is DateTime) && (DateTime.Compare(DateTime.Now, (DateTime)endTime) >= 0))
                    {
                        log.Debug("Re-establishing relationship with Organisation for OrgUnit " + unit.Uuid);
                        registration.RelationListe.Tilhoerer.Virkning = virkning;
                        changes = true;
                    }
                }
                else
                {
                    // no existing relationship (should actually never happen, but let us just take care of it)
                    helper.AddOrganisationRelation(StubUtil.GetMunicipalityOrganisationUUID(), virkning, registration);
                    changes = true;
                }
                #endregion

                #region Update parent relationship
                if (registration.RelationListe.Overordnet != null)
                {
                    // there is an existing Overordnet relationship, so let us see if there is a change
                    if (unit.ParentOrgUnitUuid != null)
                    {
                        bool   expired = false;
                        object endDate = registration.RelationListe.Overordnet.Virkning.TilTidspunkt.Item;

                        if (endDate != null && endDate is DateTime && DateTime.Compare(DateTime.Now, (DateTime)endDate) >= 0)
                        {
                            expired = true;
                        }

                        if (expired || !registration.RelationListe.Overordnet.ReferenceID.Item.Equals(unit.ParentOrgUnitUuid))
                        {
                            // overwrite the existing values (we cannot create multiple references on this, so it is the best we can do with regards to storing full history in the latest registration)
                            registration.RelationListe.Overordnet.ReferenceID = StubUtil.GetReference <UnikIdType>(unit.ParentOrgUnitUuid, ItemChoiceType.UUIDIdentifikator);
                            registration.RelationListe.Overordnet.Virkning    = virkning;
                            changes = true;
                        }
                    }
                    else
                    {
                        // attempt to terminate the existing relationship (it might already be terminated)
                        if (StubUtil.TerminateVirkning(registration.RelationListe.Overordnet.Virkning, unit.Timestamp))
                        {
                            changes = true;
                        }
                    }
                }
                else if (unit.ParentOrgUnitUuid != null)
                {
                    // no existing parent, so just create one
                    helper.AddOverordnetEnhed(unit.ParentOrgUnitUuid, virkning, registration);
                    changes = true;
                }
                #endregion

                #region Update opgaver
                if (helper.UpdateOpgaver(unit.Tasks, virkning, registration, unit.Timestamp))
                {
                    changes = true;
                }
                #endregion

                #region Update function references (PayoutUnits)
                // TODO: if we ever have other functions for OrgUnits than payout units, this solution will not work
                if (!registry.DisableUdbetalingsenheder)
                {
                    // terminate the Virkning on all functions (currently there is only one, the payout unit, but this will work for all kinds of functions)
                    changes = StubUtil.TerminateObjectsInOrgNoLongerPresentLocally(input.RelationListe.TilknyttedeFunktioner, unit.OrgFunctionUuids, unit.Timestamp, false) || changes;

                    // add references to function objects that are new
                    List <string> functionUuidsToAdd = StubUtil.FindAllObjectsInLocalNotInOrg(input.RelationListe.TilknyttedeFunktioner, unit.OrgFunctionUuids, false);

                    if (functionUuidsToAdd.Count > 0)
                    {
                        int size = functionUuidsToAdd.Count + ((input.RelationListe.TilknyttedeFunktioner != null) ? input.RelationListe.TilknyttedeFunktioner.Length : 0);
                        OrganisationFunktionFlerRelationType[] newFunctions = new OrganisationFunktionFlerRelationType[size];

                        int i = 0;
                        if (input.RelationListe.TilknyttedeFunktioner != null)
                        {
                            foreach (var functionsInOrg in input.RelationListe.TilknyttedeFunktioner)
                            {
                                newFunctions[i++] = functionsInOrg;
                            }
                        }

                        foreach (string uuidToAdd in functionUuidsToAdd)
                        {
                            OrganisationFunktionFlerRelationType newFunction = new OrganisationFunktionFlerRelationType();
                            newFunction.ReferenceID = StubUtil.GetReference <UnikIdType>(uuidToAdd, ItemChoiceType.UUIDIdentifikator);
                            newFunction.Virkning    = virkning;

                            newFunctions[i++] = newFunction;
                        }

                        input.RelationListe.TilknyttedeFunktioner = newFunctions;
                        changes = true;
                    }
                }
                #endregion

                #region Update Type
                if (helper.SetType(unit.OrgUnitType, virkning, registration))
                {
                    changes = true;
                }
                #endregion

                // if no changes are made, we do not call the service
                if (!changes)
                {
                    log.Debug("Ret on OrganisationEnhed with uuid " + unit.Uuid + " cancelled because of no changes");
                    return;
                }

                // send Ret request
                retRequest request = new retRequest();
                request.RetRequest1                  = new RetRequestType();
                request.RetRequest1.RetInput         = input;
                request.RetRequest1.AuthorityContext = new AuthorityContextType();
                request.RetRequest1.AuthorityContext.MunicipalityCVR = OrganisationRegistryProperties.GetCurrentMunicipality();

                retResponse response = channel.ret(request);

                int statusCode = Int32.Parse(response.RetResponse1.RetOutput.StandardRetur.StatusKode);
                if (statusCode != 20)
                {
                    if (statusCode == 49)
                    {
                        log.Warn("Ret failed on OrgUnit " + unit.Uuid + " as Organisation returned status 49. The most likely cause is that the object has been Passiveret");
                        return;
                    }

                    string message = StubUtil.ConstructSoapErrorMessage(statusCode, "Ret", OrganisationEnhedStubHelper.SERVICE, response.RetResponse1.RetOutput.StandardRetur.FejlbeskedTekst);
                    log.Error(message);
                    throw new SoapServiceException(message);
                }

                log.Debug("Ret succesful on OrganisationEnhed with uuid " + unit.Uuid);
            }
            catch (Exception ex) when(ex is CommunicationException || ex is IOException || ex is TimeoutException || ex is WebException)
            {
                throw new ServiceNotFoundException("Failed to establish connection to the Ret service on OrganisationEnhed", ex);
            }
        }
Esempio n. 28
0
        public void Ret(string overordnetUuid)
        {
            log.Debug("Attempting Ret on Organisation with uuid " + registry.MunicipalityOrganisationUUID[OrganisationRegistryProperties.GetCurrentMunicipality()]);

            RegistreringType1 registration = GetLatestRegistration(registry.MunicipalityOrganisationUUID[OrganisationRegistryProperties.GetCurrentMunicipality()]);

            if (registration == null)
            {
                log.Info("Cannot call Ret on Organisation with uuid " + registry.MunicipalityOrganisationUUID[OrganisationRegistryProperties.GetCurrentMunicipality()] + " because it does not exist in Organisation");
                return;
            }

            VirkningType virkning = helper.GetVirkning(DateTime.Now);

            OrganisationPortType channel = StubUtil.CreateChannel <OrganisationPortType>(OrganisationStubHelper.SERVICE, "Ret", helper.CreatePort());

            try
            {
                bool changes = false;

                RetInputType1 input = new RetInputType1();
                input.UUIDIdentifikator = registry.MunicipalityOrganisationUUID[OrganisationRegistryProperties.GetCurrentMunicipality()];
                input.AttributListe     = registration.AttributListe;
                input.TilstandListe     = registration.TilstandListe;
                input.RelationListe     = registration.RelationListe;

                if (registration.RelationListe.Overordnet != null)
                {
                    // we have an existing Overordnet, let us see if we need to change it
                    bool   expired = false;
                    object endDate = registration.RelationListe.Overordnet.Virkning.TilTidspunkt.Item;

                    if (endDate != null && endDate is DateTime && DateTime.Compare(DateTime.Now, (DateTime)endDate) >= 0)
                    {
                        expired = true;
                    }

                    if (expired || !registration.RelationListe.Overordnet.ReferenceID.Item.Equals(overordnetUuid))
                    {
                        registration.RelationListe.Overordnet.ReferenceID = StubUtil.GetReference <UnikIdType>(overordnetUuid, ItemChoiceType.UUIDIdentifikator);
                        registration.RelationListe.Overordnet.Virkning    = virkning;
                        changes = true;
                    }
                }
                else
                {
                    // no existing parent, so just create one
                    helper.AddOverordnetEnhed(overordnetUuid, virkning, registration);
                    changes = true;
                }

                // if no changes are made, we do not call the service
                if (!changes)
                {
                    log.Debug("Ret on Organisation with uuid " + registry.MunicipalityOrganisationUUID[OrganisationRegistryProperties.GetCurrentMunicipality()] + " cancelled because of no changes");
                    return;
                }

                // send Ret request
                retRequest request = new retRequest();
                request.RetRequest1                  = new RetRequestType();
                request.RetRequest1.RetInput         = input;
                request.RetRequest1.AuthorityContext = new AuthorityContextType();
                request.RetRequest1.AuthorityContext.MunicipalityCVR = OrganisationRegistryProperties.GetCurrentMunicipality();

                retResponse response = channel.ret(request);

                int statusCode = Int32.Parse(response.RetResponse1.RetOutput.StandardRetur.StatusKode);
                if (statusCode != 20)
                {
                    string message = StubUtil.ConstructSoapErrorMessage(statusCode, "Ret", OrganisationStubHelper.SERVICE, response.RetResponse1.RetOutput.StandardRetur.FejlbeskedTekst);
                    log.Error(message);
                    throw new SoapServiceException(message);
                }

                log.Debug("Ret succesful on Organisation with uuid " + registry.MunicipalityOrganisationUUID);
            }
            catch (Exception ex) when(ex is CommunicationException || ex is IOException || ex is TimeoutException || ex is WebException)
            {
                throw new ServiceNotFoundException("Failed to establish connection to the Ret service on Organisation", ex);
            }
        }