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;
        }
        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);
            }
        }