Beispiel #1
0
        ///<summary>
        /// Get Communication Contact Type for current Tenant from DB or create it if there is no entry
        ///<summary>
        public static Guid Get_CommunactionContactType_for_GlobalPropertyMatchingID(DbConnection Connection, DbTransaction Transaction, String globalPropertyMatchingID, SessionSecurityTicket securityTicket)
        {
            var query = new ORM_CMN_PER_CommunicationContact_Type.Query();

            query.Type         = globalPropertyMatchingID;
            query.IsDeleted    = false;
            query.Tenant_RefID = securityTicket.TenantID;
            var result = ORM_CMN_PER_CommunicationContact_Type.Query.Search(Connection, Transaction, query);

            if (result == null || result.Count() == 0)
            {
                return(Save_CommunactionContactTypeForTenant(Connection, Transaction, globalPropertyMatchingID, securityTicket));
            }

            if (result.Count() == 1)
            {
                return(result.First().CMN_PER_CommunicationContact_TypeID);
            }
            else
            {
                throw new Exception("Multiple ComunicationContactTypes with same \"type\" field are defined in the database!");
            }
        }
        protected static FR_Guid Execute(DbConnection Connection, DbTransaction Transaction, P_L5US_SSU_1847 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            //Leave UserCode region to enable user code saving
            #region UserCode
            var returnValue = new FR_Guid();

            var userAccount = new ORM_USR_Account();
            var result      = userAccount.Load(Connection, Transaction, Parameter.USR_AccountID);

            if (result.Status == FR_Status.Success)
            {
                //Get business participant via userAccount
                var businessParticipant = new ORM_CMN_BPT_BusinessParticipant();
                businessParticipant.Load(Connection, Transaction, userAccount.BusinessParticipant_RefID);

                //Load person
                var personInfo = new ORM_CMN_PER_PersonInfo();
                personInfo.Load(Connection, Transaction, businessParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID);

                //Load communication contacts for person
                P_L2CN_GCCfPI_1222 contactsParam = new P_L2CN_GCCfPI_1222();
                contactsParam.PersonInfoID = personInfo.CMN_PER_PersonInfoID;
                var contactsForPersonInfo = cls_Get_ComunicationContacts_for_PersonInfoID.Invoke(Connection, Transaction, contactsParam, securityTicket).Result.ToList();

                if (!Parameter.IsInitialSave)
                {
                    if (Parameter.IsDeleted)
                    {
                        #region Delete

                        var queryApplicationSubscription = new ORM_CMN_Account_ApplicationSubscription.Query();
                        queryApplicationSubscription.Application_RefID = Parameter.ApplicationID;
                        queryApplicationSubscription.Account_RefID     = userAccount.USR_AccountID;
                        queryApplicationSubscription.Tenant_RefID      = securityTicket.TenantID;

                        var foundApplicationSubscription = ORM_CMN_Account_ApplicationSubscription.Query.SoftDelete(Connection, Transaction, queryApplicationSubscription);

                        return(new FR_Guid(FR_Base.Status_OK, userAccount.USR_AccountID));

                        #endregion
                    }

                    #region Edit


                    personInfo.FirstName = Parameter.FirstName_ContactPerson;
                    personInfo.LastName  = Parameter.LastName_ContactPerson;
                    personInfo.Save(Connection, Transaction);

                    var employeeTemp = ORM_CMN_BPT_EMP_Employee.Query.Search(Connection, Transaction, new ORM_CMN_BPT_EMP_Employee.Query()
                    {
                        BusinessParticipant_RefID = businessParticipant.CMN_BPT_BusinessParticipantID,
                        Tenant_RefID = securityTicket.TenantID,
                        IsDeleted    = false
                    }).SingleOrDefault();

                    if (employeeTemp == null)
                    {
                        var newEmployee = new ORM_CMN_BPT_EMP_Employee();
                        newEmployee.CMN_BPT_EMP_EmployeeID    = Guid.NewGuid();
                        newEmployee.BusinessParticipant_RefID = businessParticipant.CMN_BPT_BusinessParticipantID;
                        newEmployee.StandardFunction          = "APOAdminEmployee";
                        newEmployee.Tenant_RefID = securityTicket.TenantID;
                        newEmployee.Save(Connection, Transaction);
                    }


                    var address = new ORM_CMN_Address();
                    address.Load(Connection, Transaction, personInfo.Address_RefID);
                    address.Street_Name     = Parameter.Street_Name;
                    address.Street_Number   = Parameter.Street_Number;
                    address.City_Name       = Parameter.Town;
                    address.City_PostalCode = Parameter.ZIP;
                    address.Save(Connection, Transaction);


                    try
                    {
                        //telephone
                        var telephone = contactsForPersonInfo.Where(i => i.Type == EnumUtils.GetEnumDescription(EComunactionContactType.Phone))
                                        .First().Contacts;

                        if (telephone.Count() == 1)
                        {
                            var contactID = telephone[0].CMN_PER_CommunicationContactID;

                            var contactTelephone = new ORM_CMN_PER_CommunicationContact();
                            contactTelephone.Load(Connection, Transaction, contactID);
                            contactTelephone.Content = Parameter.Contact_Telephone;
                            contactTelephone.Save(Connection, Transaction);
                        }
                    }
                    catch
                    {
                        //Log this
                    }

                    #region CommentedUsefull-PreviousWayOfContactEmailHandling

                    //try
                    //{
                    //    //email
                    //    var email = contactsForPersonInfo.Where(i => i.Type == EnumUtils.GetEnumDescription(EComunactionContactType.Email))
                    //        .First().Contacts;

                    //    if (email.Count() == 1)
                    //    {
                    //        var contactID = email[0].CMN_PER_CommunicationContactID;

                    //        var contactEmail = new ORM_CMN_PER_CommunicationContact();
                    //        contactEmail.Load(Connection, Transaction, contactID);
                    //        contactEmail.Content = Parameter.Contact_Email;
                    //        contactEmail.Save(Connection, Transaction);
                    //    }

                    //}
                    //catch
                    //{

                    //    //Log this
                    //}

                    #endregion

                    #endregion
                }

                #region SaveGroup

                var userAccountToGroup = ORM_USR_Account_2_Group.Query.Search(Connection, Transaction, new ORM_USR_Account_2_Group.Query()
                {
                    USR_Account_RefID = userAccount.USR_AccountID,
                    Tenant_RefID      = securityTicket.TenantID,
                    IsDeleted         = false
                }).SingleOrDefault();


                if (userAccountToGroup == null)
                {
                    var newGroup = new ORM_USR_Account_2_Group();
                    newGroup.AssignmentID       = Guid.NewGuid();
                    newGroup.USR_Account_RefID  = userAccount.USR_AccountID;
                    newGroup.USR_Group_RefID    = Parameter.USR_GroupID;
                    newGroup.Creation_Timestamp = DateTime.Now;
                    newGroup.Tenant_RefID       = securityTicket.TenantID;
                    newGroup.Save(Connection, Transaction);
                }
                else
                {
                    userAccountToGroup.USR_Group_RefID = Parameter.USR_GroupID;
                    userAccountToGroup.Save(Connection, Transaction);
                }

                #endregion

                #region SaveEmployee

                var employee = ORM_CMN_BPT_EMP_Employee.Query.Search(Connection, Transaction, new ORM_CMN_BPT_EMP_Employee.Query()
                {
                    BusinessParticipant_RefID = businessParticipant.CMN_BPT_BusinessParticipantID,
                    Tenant_RefID = securityTicket.TenantID,
                    IsDeleted    = false
                }).SingleOrDefault();

                if (employee == null)
                {
                    var newEmployee = new ORM_CMN_BPT_EMP_Employee();
                    newEmployee.CMN_BPT_EMP_EmployeeID    = Guid.NewGuid();
                    newEmployee.BusinessParticipant_RefID = businessParticipant.CMN_BPT_BusinessParticipantID;
                    newEmployee.StandardFunction          = "APOAdminEmployee";
                    newEmployee.Tenant_RefID = securityTicket.TenantID;
                    newEmployee.Save(Connection, Transaction);
                }

                #endregion

                #region CreateOrUpdateContactEmail

                var emailTypeProperty     = EnumUtils.GetEnumDescription(EComunactionContactType.Email);
                var contactEmailTypeQuery = new ORM_CMN_PER_CommunicationContact_Type.Query();
                contactEmailTypeQuery.Type         = emailTypeProperty;
                contactEmailTypeQuery.Tenant_RefID = securityTicket.TenantID;
                var contactEmailType = ORM_CMN_PER_CommunicationContact_Type.Query.Search(Connection, Transaction, contactEmailTypeQuery).FirstOrDefault();

                //Search for default contact email and create it if don't exist

                var defaultContactEmailQuery = new ORM_CMN_PER_CommunicationContact.Query();
                defaultContactEmailQuery.PersonInfo_RefID = personInfo.CMN_PER_PersonInfoID;
                defaultContactEmailQuery.Contact_Type     = contactEmailType.CMN_PER_CommunicationContact_TypeID;
                defaultContactEmailQuery.Tenant_RefID     = securityTicket.TenantID;
                var defaultContactEmail = ORM_CMN_PER_CommunicationContact.Query.Search(Connection, Transaction, defaultContactEmailQuery).FirstOrDefault();

                if (defaultContactEmail == null)
                {
                    defaultContactEmail = new ORM_CMN_PER_CommunicationContact();
                    defaultContactEmail.PersonInfo_RefID        = personInfo.CMN_PER_PersonInfoID;
                    defaultContactEmail.Contact_Type            = contactEmailType.CMN_PER_CommunicationContact_TypeID;
                    defaultContactEmail.IsDefaultForContactType = true;
                    defaultContactEmail.Tenant_RefID            = securityTicket.TenantID;
                }

                defaultContactEmail.Content = Parameter.Contact_Email;
                defaultContactEmail.IsDefaultForContactType = true;
                defaultContactEmail.Save(Connection, Transaction);

                #endregion
            }
            else
            {
                FR_Guid error = new FR_Guid();
                error.ErrorMessage = "No Such ID.";
                error.Status       = FR_Status.Error_Internal;
                return(error);
            }

            return(new FR_Guid(FR_Base.Status_OK, userAccount.USR_AccountID));

            #endregion UserCode
        }
        protected static FR_Guid Execute(DbConnection Connection, DbTransaction Transaction, P_L5PA_GPBD_1613 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var returnValue = new FR_Guid();
            returnValue.Result = new Guid();
            var patient = new ORM_HEC_Patient();
            //var serializer = new JsonNetSerializer();
            //var connection = new ElasticConnection((String)HttpContext.GetGlobalResourceObject("Global", "ElasticConnection"), 9200);

            #region Save

            if (Parameter.ID == null || Parameter.ID == Guid.Empty)
            {
                //ORM_HEC_Patient
                patient.HEC_PatientID      = Guid.NewGuid();
                patient.Tenant_RefID       = securityTicket.TenantID;
                patient.Creation_Timestamp = DateTime.Now;
                patient.CMN_BPT_BusinessParticipant_RefID = Guid.NewGuid();
                patient.Save(Connection, Transaction);

                //ORM_CMN_BPT_BusinessParticipant
                var businessParticipant = new ORM_CMN_BPT_BusinessParticipant();
                businessParticipant.CMN_BPT_BusinessParticipantID = patient.CMN_BPT_BusinessParticipant_RefID;
                businessParticipant.IsNaturalPerson        = true;
                businessParticipant.Tenant_RefID           = securityTicket.TenantID;
                businessParticipant.Creation_Timestamp     = DateTime.Now;
                businessParticipant.Modification_Timestamp = DateTime.Now;
                businessParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID = Guid.NewGuid();
                businessParticipant.Save(Connection, Transaction);

                //ORM_CMN_PER_PersonInfo
                var personInfo = new ORM_CMN_PER_PersonInfo();
                personInfo.CMN_PER_PersonInfoID = businessParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID;
                personInfo.FirstName            = Parameter.FirstName;
                personInfo.LastName             = Parameter.LastName;
                personInfo.PrimaryEmail         = Parameter.PrimaryEmail;
                personInfo.Title = Parameter.Title;
                personInfo.ProfileImage_Document_RefID = Parameter.ProfileImage_Document_RefID;
                personInfo.BirthDate                  = Parameter.BirthDate;
                personInfo.Gender                     = Int32.Parse(Parameter.Gender);
                personInfo.Salutation_General         = Parameter.AcademicTitle;
                personInfo.Address_RefID              = Guid.NewGuid();
                personInfo.Tenant_RefID               = securityTicket.TenantID;
                personInfo.Creation_Timestamp         = DateTime.Now;
                personInfo.Modification_Timestamp     = DateTime.Now;
                personInfo.AgeCalculation_YearOfBirth = DateTime.Now.Year - personInfo.BirthDate.Year;
                personInfo.Save(Connection, Transaction);

                //ORM_CMN_Address
                var address = new ORM_CMN_Address();
                address.CMN_AddressID      = personInfo.Address_RefID;
                address.Street_Name        = Parameter.Street_Name;
                address.Street_Number      = Parameter.Street_Number;
                address.City_Name          = Parameter.City_Name;
                address.City_PostalCode    = Parameter.City_PostalCode;
                address.Country_ISOCode    = Parameter.Country_ISOCode;
                address.Tenant_RefID       = securityTicket.TenantID;
                address.Creation_Timestamp = DateTime.Now;
                address.Save(Connection, Transaction);

                //ORM_CMN_PER_PersonInfo_SocialSecurityNumber
                var socialSecurityNumber = new ORM_CMN_PER_PersonInfo_SocialSecurityNumber();
                socialSecurityNumber.CMN_PER_PersonInfo_SocialSecurityNumberID = Guid.NewGuid();
                socialSecurityNumber.PersonInfo_RefID     = personInfo.CMN_PER_PersonInfoID;
                socialSecurityNumber.SocialSecurityNumber = Parameter.SocialSecurityNumber;
                socialSecurityNumber.Tenant_RefID         = securityTicket.TenantID;
                socialSecurityNumber.Creation_Timestamp   = DateTime.Now;
                socialSecurityNumber.Save(Connection, Transaction);

                var TelephoneCompanyType = CL1_CMN_PER.ORM_CMN_PER_CommunicationContact_Type.Query.Search(Connection, Transaction,
                                                                                                          new CL1_CMN_PER.ORM_CMN_PER_CommunicationContact_Type.Query()
                {
                    Type         = DLCore_DBCommons.Utils.EnumUtils.GetEnumDescription(CL2_Contact.DomainManagement.EComunactionContactType.Phone),
                    Tenant_RefID = securityTicket.TenantID,
                    IsDeleted    = false
                }).SingleOrDefault();

                var MobileCompanyType = CL1_CMN_PER.ORM_CMN_PER_CommunicationContact_Type.Query.Search(Connection, Transaction,
                                                                                                       new CL1_CMN_PER.ORM_CMN_PER_CommunicationContact_Type.Query()
                {
                    Type         = DLCore_DBCommons.Utils.EnumUtils.GetEnumDescription(CL2_Contact.DomainManagement.EComunactionContactType.Mobile),
                    Tenant_RefID = securityTicket.TenantID,
                    IsDeleted    = false
                }).Single();
                var EmailType = CL1_CMN_PER.ORM_CMN_PER_CommunicationContact_Type.Query.Search(Connection, Transaction,
                                                                                               new CL1_CMN_PER.ORM_CMN_PER_CommunicationContact_Type.Query()
                {
                    Type         = DLCore_DBCommons.Utils.EnumUtils.GetEnumDescription(CL2_Contact.DomainManagement.EComunactionContactType.Email),
                    Tenant_RefID = securityTicket.TenantID,
                    IsDeleted    = false
                }).Single();
                //add into database
                //var UrlType = CL1_CMN_PER.ORM_CMN_PER_CommunicationContact_Type.Query.Search(Connection, Transaction,
                //      new CL1_CMN_PER.ORM_CMN_PER_CommunicationContact_Type.Query()
                //      {
                //          Type = DLCore_DBCommons.Utils.EnumUtils.GetEnumDescription(CL2_Contact.DomainManagement.EComunactionContactType.URL),
                //          Tenant_RefID = securityTicket.TenantID,
                //          IsDeleted = false
                //      }).Single();
                var FaxType = CL1_CMN_PER.ORM_CMN_PER_CommunicationContact_Type.Query.Search(Connection, Transaction,
                                                                                             new CL1_CMN_PER.ORM_CMN_PER_CommunicationContact_Type.Query()
                {
                    Type         = DLCore_DBCommons.Utils.EnumUtils.GetEnumDescription(CL2_Contact.DomainManagement.EComunactionContactType.Fax),
                    Tenant_RefID = securityTicket.TenantID,
                    IsDeleted    = false
                }).Single();



                ORM_CMN_PER_CommunicationContact communicationContactsPhone = new ORM_CMN_PER_CommunicationContact();

                communicationContactsPhone.CMN_PER_CommunicationContactID = Guid.NewGuid();
                communicationContactsPhone.PersonInfo_RefID       = personInfo.CMN_PER_PersonInfoID;
                communicationContactsPhone.Contact_Type           = TelephoneCompanyType.CMN_PER_CommunicationContact_TypeID;
                communicationContactsPhone.Content                = Parameter.ContactTypes.Where(p => p.Type == DLCore_DBCommons.Utils.EnumUtils.GetEnumDescription(CL2_Contact.DomainManagement.EComunactionContactType.Phone)).Single().Content;
                communicationContactsPhone.Creation_Timestamp     = DateTime.Now;
                communicationContactsPhone.Modification_Timestamp = DateTime.Now;
                communicationContactsPhone.Tenant_RefID           = securityTicket.TenantID;
                communicationContactsPhone.Save(Connection, Transaction);

                ORM_CMN_PER_CommunicationContact communicationContactsMobile = new ORM_CMN_PER_CommunicationContact();

                communicationContactsMobile.CMN_PER_CommunicationContactID = Guid.NewGuid();
                communicationContactsMobile.PersonInfo_RefID       = personInfo.CMN_PER_PersonInfoID;
                communicationContactsMobile.Contact_Type           = MobileCompanyType.CMN_PER_CommunicationContact_TypeID;
                communicationContactsMobile.Content                = Parameter.ContactTypes.Where(p => p.Type == DLCore_DBCommons.Utils.EnumUtils.GetEnumDescription(CL2_Contact.DomainManagement.EComunactionContactType.Mobile)).Single().Content;
                communicationContactsMobile.Creation_Timestamp     = DateTime.Now;
                communicationContactsMobile.Modification_Timestamp = DateTime.Now;
                communicationContactsMobile.Tenant_RefID           = securityTicket.TenantID;

                communicationContactsMobile.Save(Connection, Transaction);

                ORM_CMN_PER_CommunicationContact communicationContactsEmail = new ORM_CMN_PER_CommunicationContact();

                communicationContactsEmail.CMN_PER_CommunicationContactID = Guid.NewGuid();
                communicationContactsEmail.PersonInfo_RefID       = personInfo.CMN_PER_PersonInfoID;
                communicationContactsEmail.Contact_Type           = EmailType.CMN_PER_CommunicationContact_TypeID;
                communicationContactsEmail.Content                = Parameter.ContactTypes.Where(p => p.Type == DLCore_DBCommons.Utils.EnumUtils.GetEnumDescription(CL2_Contact.DomainManagement.EComunactionContactType.Email)).Single().Content;
                communicationContactsEmail.Creation_Timestamp     = DateTime.Now;
                communicationContactsEmail.Modification_Timestamp = DateTime.Now;
                communicationContactsEmail.Tenant_RefID           = securityTicket.TenantID;

                communicationContactsEmail.Save(Connection, Transaction);

                //*******************Save languages to patient************************

                if (Parameter.Languages != null && Parameter.Languages.Count() != 0)
                {
                    foreach (var language in Parameter.Languages)
                    {
                        ORM_CMN_BPT_BusinessParticipant_SpokenLanguage bpLanguage = new ORM_CMN_BPT_BusinessParticipant_SpokenLanguage();
                        bpLanguage.CMN_BPT_BusinessParticipant_RefID            = businessParticipant.CMN_BPT_BusinessParticipantID;
                        bpLanguage.CMN_BPT_BusinessParticipant_SpokenLanguageID = Guid.NewGuid();
                        bpLanguage.CMN_Language_RefID = language.CMN_Language_RefID;
                        bpLanguage.IsDeleted          = false;
                        bpLanguage.Tenant_RefID       = securityTicket.TenantID;
                        bpLanguage.Save(Connection, Transaction);
                    }
                }

                //#region Upload To Elastic

                //bool indexExists = true;
                //#region set Mapping
                //string jsonPatientMapping = new MapBuilder<Patient>()
                //             .RootObject("patient", ro => ro
                //             .Properties(pr => pr
                //                 .MultiField("name", mfp => mfp.Fields(f => f
                //                     .String("name", sp => sp.IndexAnalyzer("autocomplete").SearchAnalyzer(DefaultAnalyzers.standard))
                //                     .String("lower_case_sort", sp => sp.Analyzer("caseinsensitive"))
                //                     )
                //                 )
                //                  .MultiField("last_name", mfp => mfp.Fields(f => f
                //                                     .String("last_name", sp => sp.IndexAnalyzer("autocomplete").SearchAnalyzer(DefaultAnalyzers.standard))
                //                                     .String("lower_case_sort", sp => sp.Analyzer("caseinsensitive"))
                //                                     )
                //                                  )
                //                    .MultiField("birthday", mfp => mfp.Fields(f => f
                //                                     .String("birthday", sp => sp.IndexAnalyzer("autocomplete").SearchAnalyzer(DefaultAnalyzers.standard))
                //                                     .String("lower_case_sort", sp => sp.Analyzer("caseinsensitive"))
                //                                     )
                //                                  )
                //                 .MultiField("age", mfp => mfp.Fields(f => f
                //                                     .String("age", sp => sp.IndexAnalyzer("autocomplete").SearchAnalyzer(DefaultAnalyzers.standard))
                //                                     .String("lower_case_sort", sp => sp.Analyzer("caseinsensitive"))
                //                                     )
                //                                  )
                //                 )).BuildBeautified();
                //#endregion


                //try
                //{
                //    connection.Head(new IndexExistsCommand(securityTicket.TenantID.ToString()));
                //}
                //catch (OperationException ex)
                //{
                //    if (ex.HttpStatusCode == 404)
                //        indexExists = false;
                //}

                //if (!indexExists)
                //{

                //    #region set index settings
                //    string settings = new IndexSettingsBuilder()
                //                          .Analysis(anl => anl
                //                              .Filter(fil => fil
                //                                  .EdgeNGram("autocomplete_filter", gr => gr.MinGram(1).MaxGram(20)))
                //                              .Analyzer(a => a
                //                                  .Custom("caseinsensitive", custom => custom
                //                                      .Tokenizer(DefaultTokenizers.keyword)
                //                                      .Filter("lowercase")
                //                                  )
                //                                  .Custom("autocomplete", custom => custom
                //                                      .Tokenizer(DefaultTokenizers.standard)
                //                                      .Filter("lowercase", "autocomplete_filter")
                //                                  )
                //                              )
                //                          )
                //                          .BuildBeautified();
                //    #endregion
                //    connection.Put(securityTicket.TenantID.ToString(), settings);

                //}


                //#region check if type exists

                //bool typeExists = true;

                //try
                //{
                //    connection.Head(new IndexExistsCommand(securityTicket.TenantID.ToString() + "/patient"));
                //}
                //catch (OperationException ex)
                //{
                //    if (ex.HttpStatusCode == 404)
                //        typeExists = false;
                //}
                //#endregion


                //if (!typeExists)
                //    connection.Put(new PutMappingCommand(securityTicket.TenantID.ToString(), "patient"), jsonPatientMapping);

                //string bulkCommand = new BulkCommand(index: securityTicket.TenantID.ToString(), type: "patient").Refresh();

                //List<Patient> patientList = new List<Patient>();
                //Patient patient_elastic = new Patient();
                //patient_elastic.id = patient.HEC_PatientID.ToString();
                //patient_elastic.age = (DateTime.Today.Year - Parameter.BirthDate.Year).ToString();
                //patient_elastic.birthday = Parameter.BirthDate.ToShortDateString();
                //patient_elastic.last_name = Parameter.LastName;
                //patient_elastic.name = Parameter.FirstName;
                //patientList.Add(patient_elastic);

                //string bulkJson = new BulkBuilder(serializer)
                //    .BuildCollection(patientList, (builder, pro) => builder.Index(data: pro, id: pro.id)
                //    );
                //connection.Post(bulkCommand, bulkJson);

                //#endregion
            }
            #endregion
            else
            {
                #region Delete
                if (Parameter.isDeleted)
                {
                    var patientQuery = new ORM_HEC_Patient.Query();
                    patientQuery.HEC_PatientID = Parameter.ID;
                    patientQuery.IsDeleted     = false;
                    patientQuery.Tenant_RefID  = securityTicket.TenantID;

                    patient           = ORM_HEC_Patient.Query.Search(Connection, Transaction, patientQuery).Single();
                    patient.IsDeleted = true;
                    patient.Save(Connection, Transaction);

                    var businessParticipantQuery = new ORM_CMN_BPT_BusinessParticipant.Query();
                    businessParticipantQuery.CMN_BPT_BusinessParticipantID = patient.CMN_BPT_BusinessParticipant_RefID;
                    businessParticipantQuery.IsDeleted    = false;
                    businessParticipantQuery.Tenant_RefID = securityTicket.TenantID;

                    var businessParticipant = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, businessParticipantQuery).Single();
                    businessParticipant.IsDeleted = true;
                    businessParticipant.Save(Connection, Transaction);

                    var personInfoQuery = new ORM_CMN_PER_PersonInfo.Query();
                    personInfoQuery.CMN_PER_PersonInfoID = businessParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID;
                    personInfoQuery.IsDeleted            = false;
                    personInfoQuery.Tenant_RefID         = securityTicket.TenantID;

                    var personInfo = ORM_CMN_PER_PersonInfo.Query.Search(Connection, Transaction, personInfoQuery).Single();
                    personInfo.IsDeleted = true;
                    personInfo.Save(Connection, Transaction);

                    var addressQuery = new ORM_CMN_Address.Query();
                    addressQuery.CMN_AddressID = personInfo.Address_RefID;
                    addressQuery.IsDeleted     = false;
                    addressQuery.Tenant_RefID  = securityTicket.TenantID;

                    var address = ORM_CMN_Address.Query.Search(Connection, Transaction, addressQuery).Single();
                    address.IsDeleted = true;
                    address.Save(Connection, Transaction);

                    var socialSecurityNumberQuery = new ORM_CMN_PER_PersonInfo_SocialSecurityNumber.Query();
                    socialSecurityNumberQuery.PersonInfo_RefID = personInfo.CMN_PER_PersonInfoID;
                    socialSecurityNumberQuery.IsDeleted        = false;
                    socialSecurityNumberQuery.Tenant_RefID     = securityTicket.TenantID;

                    var socialSecurityNumber = ORM_CMN_PER_PersonInfo_SocialSecurityNumber.Query.Search(Connection, Transaction, socialSecurityNumberQuery).Single();
                    socialSecurityNumber.IsDeleted = true;
                    socialSecurityNumber.Save(Connection, Transaction);

                    var communicationContactQuery = new ORM_CMN_PER_CommunicationContact.Query();
                    communicationContactQuery.PersonInfo_RefID = personInfo.CMN_PER_PersonInfoID;
                    communicationContactQuery.IsDeleted        = false;
                    communicationContactQuery.Tenant_RefID     = securityTicket.TenantID;

                    var communicationContactList = ORM_CMN_PER_CommunicationContact.Query.Search(Connection, Transaction, communicationContactQuery).ToList();

                    ORM_CMN_BPT_BusinessParticipant_SpokenLanguage.Query.SoftDelete(Connection, Transaction, new ORM_CMN_BPT_BusinessParticipant_SpokenLanguage.Query {
                        CMN_BPT_BusinessParticipant_RefID = businessParticipant.CMN_BPT_BusinessParticipantID, IsDeleted = false, Tenant_RefID = securityTicket.TenantID
                    });

                    //// delete on Elastic
                    //connection.Delete(securityTicket.TenantID.ToString() + "/patient/" + Parameter.ID.ToString());
                }
                #endregion
                #region Edit
                else
                {
                    var patientQuery = new ORM_HEC_Patient.Query();
                    patientQuery.HEC_PatientID = Parameter.ID;
                    patientQuery.IsDeleted     = false;
                    patientQuery.Tenant_RefID  = securityTicket.TenantID;

                    patient = ORM_HEC_Patient.Query.Search(Connection, Transaction, patientQuery).Single();

                    var businessParticipantQuery = new ORM_CMN_BPT_BusinessParticipant.Query();
                    businessParticipantQuery.CMN_BPT_BusinessParticipantID = patient.CMN_BPT_BusinessParticipant_RefID;
                    businessParticipantQuery.IsDeleted    = false;
                    businessParticipantQuery.Tenant_RefID = securityTicket.TenantID;

                    var businessParticipant = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, businessParticipantQuery).Single();

                    var personInfoQuery = new ORM_CMN_PER_PersonInfo.Query();
                    personInfoQuery.CMN_PER_PersonInfoID = businessParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID;
                    personInfoQuery.IsDeleted            = false;
                    personInfoQuery.Tenant_RefID         = securityTicket.TenantID;

                    var personInfo = ORM_CMN_PER_PersonInfo.Query.Search(Connection, Transaction, personInfoQuery).Single();
                    personInfo.FirstName    = Parameter.FirstName;
                    personInfo.LastName     = Parameter.LastName;
                    personInfo.PrimaryEmail = Parameter.PrimaryEmail;
                    personInfo.Title        = Parameter.Title;
                    personInfo.Gender       = Int32.Parse(Parameter.Gender);
                    personInfo.ProfileImage_Document_RefID = Parameter.ProfileImage_Document_RefID;
                    personInfo.BirthDate                  = Parameter.BirthDate;
                    personInfo.Salutation_General         = Parameter.AcademicTitle;
                    personInfo.Modification_Timestamp     = DateTime.Now;
                    personInfo.AgeCalculation_YearOfBirth = DateTime.Now.Year - personInfo.BirthDate.Year;
                    personInfo.Save(Connection, Transaction);

                    if (personInfo.Address_RefID != Guid.Empty)
                    {
                        var addressQuery = new ORM_CMN_Address.Query();
                        addressQuery.CMN_AddressID = personInfo.Address_RefID;
                        addressQuery.IsDeleted     = false;
                        addressQuery.Tenant_RefID  = securityTicket.TenantID;

                        var address = ORM_CMN_Address.Query.Search(Connection, Transaction, addressQuery).Single();
                        address.Street_Name     = Parameter.Street_Name;
                        address.Street_Number   = Parameter.Street_Number;
                        address.City_Name       = Parameter.City_Name;
                        address.City_PostalCode = Parameter.City_PostalCode;
                        address.Country_ISOCode = Parameter.Country_ISOCode;
                        address.Save(Connection, Transaction);
                    }
                    else
                    {
                        var address = new ORM_CMN_Address();
                        address.CMN_AddressID      = Guid.NewGuid();
                        address.Street_Name        = Parameter.Street_Name;
                        address.Street_Number      = Parameter.Street_Number;
                        address.City_Name          = Parameter.City_Name;
                        address.City_PostalCode    = Parameter.City_PostalCode;
                        address.Country_ISOCode    = Parameter.Country_ISOCode;
                        address.Tenant_RefID       = securityTicket.TenantID;
                        address.Creation_Timestamp = DateTime.Now;
                        address.Save(Connection, Transaction);


                        personInfo.Address_RefID = address.CMN_AddressID;
                        personInfo.Save(Connection, Transaction);
                    }


                    var socialSecurityNumberQuery = new ORM_CMN_PER_PersonInfo_SocialSecurityNumber.Query();
                    socialSecurityNumberQuery.PersonInfo_RefID = personInfo.CMN_PER_PersonInfoID;
                    socialSecurityNumberQuery.IsDeleted        = false;
                    socialSecurityNumberQuery.Tenant_RefID     = securityTicket.TenantID;

                    var socialSecurityNumber = ORM_CMN_PER_PersonInfo_SocialSecurityNumber.Query.Search(Connection, Transaction, socialSecurityNumberQuery).SingleOrDefault();

                    if (socialSecurityNumber == null)
                    {
                        socialSecurityNumber = new ORM_CMN_PER_PersonInfo_SocialSecurityNumber();
                        socialSecurityNumber.CMN_PER_PersonInfo_SocialSecurityNumberID = Guid.NewGuid();
                        socialSecurityNumber.PersonInfo_RefID = personInfo.CMN_PER_PersonInfoID;
                        socialSecurityNumber.Tenant_RefID     = securityTicket.TenantID;
                    }

                    socialSecurityNumber.SocialSecurityNumber = Parameter.SocialSecurityNumber;
                    socialSecurityNumber.Save(Connection, Transaction);

                    var communicationContactQuery = new ORM_CMN_PER_CommunicationContact.Query();
                    communicationContactQuery.PersonInfo_RefID = personInfo.CMN_PER_PersonInfoID;
                    communicationContactQuery.IsDeleted        = false;
                    communicationContactQuery.Tenant_RefID     = securityTicket.TenantID;

                    var communicationContactList = ORM_CMN_PER_CommunicationContact.Query.Search(Connection, Transaction, communicationContactQuery).ToList();

                    List <string> unusedTypes = new List <string>()
                    {
                        DLCore_DBCommons.Utils.EnumUtils.GetEnumDescription(CL2_Contact.DomainManagement.EComunactionContactType.URL),
                        DLCore_DBCommons.Utils.EnumUtils.GetEnumDescription(CL2_Contact.DomainManagement.EComunactionContactType.Mobile),
                        DLCore_DBCommons.Utils.EnumUtils.GetEnumDescription(CL2_Contact.DomainManagement.EComunactionContactType.Phone),
                        DLCore_DBCommons.Utils.EnumUtils.GetEnumDescription(CL2_Contact.DomainManagement.EComunactionContactType.Email)
                    };

                    foreach (var communicationContact in communicationContactList)
                    {
                        var communicationContact_TypeQuery = new ORM_CMN_PER_CommunicationContact_Type.Query();
                        communicationContact_TypeQuery.CMN_PER_CommunicationContact_TypeID = communicationContact.Contact_Type;
                        communicationContact_TypeQuery.IsDeleted    = false;
                        communicationContact_TypeQuery.Tenant_RefID = securityTicket.TenantID;
                        var communicationContact_Type = ORM_CMN_PER_CommunicationContact_Type.Query.Search(Connection, Transaction, communicationContact_TypeQuery).Single();

                        var newType = Parameter.ContactTypes.Where(i => i.Type == communicationContact_Type.Type).Single();
                        communicationContact.Content = newType.Content;
                        communicationContact.Modification_Timestamp = DateTime.Now;
                        communicationContact.Save(Connection, Transaction);

                        if (unusedTypes.Contains(communicationContact_Type.Type))
                        {
                            unusedTypes.Remove(communicationContact_Type.Type);
                        }
                    }

                    var contactTypes = cls_Get_AllComunicationContactTypes.Invoke(Connection, Transaction, securityTicket).Result.ToList();

                    foreach (var type in unusedTypes)
                    {
                        ORM_CMN_PER_CommunicationContact communicationContactsPhone = new ORM_CMN_PER_CommunicationContact();

                        communicationContactsPhone.CMN_PER_CommunicationContactID = Guid.NewGuid();
                        communicationContactsPhone.PersonInfo_RefID = personInfo.CMN_PER_PersonInfoID;
                        P_L2CN_GCTIDfGPMID_1359 contantTypeParam = new P_L2CN_GCTIDfGPMID_1359();
                        contantTypeParam.Type = type;
                        var contantTypeID = cls_Get_ContantTypeID_for_GlobalPropertyMatchingID.Invoke(Connection, Transaction, contantTypeParam, securityTicket).Result.ContactTypeID;
                        communicationContactsPhone.Contact_Type           = contantTypeID;
                        communicationContactsPhone.Content                = Parameter.ContactTypes.Where(p => p.Type == DLCore_DBCommons.Utils.EnumUtils.GetEnumDescription(CL2_Contact.DomainManagement.EComunactionContactType.Phone)).Single().Content;
                        communicationContactsPhone.Creation_Timestamp     = DateTime.Now;
                        communicationContactsPhone.Modification_Timestamp = DateTime.Now;
                        communicationContactsPhone.Tenant_RefID           = securityTicket.TenantID;
                        communicationContactsPhone.Save(Connection, Transaction);
                    }

                    //connection.Delete(securityTicket.TenantID.ToString() + "/patient/" + Parameter.ID.ToString());
                    //string bulkCommand = new BulkCommand(index: securityTicket.TenantID.ToString(), type: "patient").Refresh();

                    //List<Patient> patientList = new List<Patient>();
                    //Patient patient_elastic = new Patient();
                    //patient_elastic.id = patient.HEC_PatientID.ToString();
                    //patient_elastic.age = (DateTime.Today.Year - Parameter.BirthDate.Year).ToString();
                    //patient_elastic.birthday = Parameter.BirthDate.ToShortDateString();
                    //patient_elastic.last_name = Parameter.LastName;
                    //patient_elastic.name = Parameter.FirstName;
                    //patientList.Add(patient_elastic);

                    //string bulkJson = new BulkBuilder(serializer)
                    //    .BuildCollection(patientList, (builder, pro) => builder.Index(data: pro, id: pro.id)
                    //    );
                    //connection.Post(bulkCommand, bulkJson);


                    #region languages

                    if (Parameter.Languages == null || Parameter.Languages.Count() == 0)
                    {
                        P_L5PA_GPBD_1613_Languages Languages = new P_L5PA_GPBD_1613_Languages();
                        Languages.CMN_Language_RefID = Guid.Empty;
                    }
                    else if (Parameter.Languages != null || Parameter.Languages.Count() != 0)
                    {
                        foreach (var language in Parameter.Languages)
                        {
                            var languageToPatient = ORM_CMN_BPT_BusinessParticipant_SpokenLanguage.Query.Search(Connection, Transaction, new ORM_CMN_BPT_BusinessParticipant_SpokenLanguage.Query {
                                CMN_Language_RefID = language.CMN_Language_RefID, CMN_BPT_BusinessParticipant_RefID = patient.CMN_BPT_BusinessParticipant_RefID, IsDeleted = false, Tenant_RefID = securityTicket.TenantID
                            }).FirstOrDefault();
                            if (languageToPatient == null)
                            {
                                ORM_CMN_BPT_BusinessParticipant_SpokenLanguage bpLanguage = new ORM_CMN_BPT_BusinessParticipant_SpokenLanguage();
                                bpLanguage.CMN_BPT_BusinessParticipant_RefID            = patient.CMN_BPT_BusinessParticipant_RefID;
                                bpLanguage.CMN_BPT_BusinessParticipant_SpokenLanguageID = Guid.NewGuid();
                                bpLanguage.CMN_Language_RefID = language.CMN_Language_RefID;
                                bpLanguage.IsDeleted          = false;
                                bpLanguage.Tenant_RefID       = securityTicket.TenantID;
                                bpLanguage.Save(Connection, Transaction);
                            }
                        }

                        // deleting languages to patient that were deleted during edit

                        List <ORM_CMN_BPT_BusinessParticipant_SpokenLanguage> languageToDoctorList = ORM_CMN_BPT_BusinessParticipant_SpokenLanguage.Query.Search(Connection, Transaction, new ORM_CMN_BPT_BusinessParticipant_SpokenLanguage.Query {
                            CMN_BPT_BusinessParticipant_RefID = patient.CMN_BPT_BusinessParticipant_RefID, IsDeleted = false, Tenant_RefID = securityTicket.TenantID
                        });
                        foreach (var languageToDoctor in languageToDoctorList)
                        {
                            if (Parameter.Languages.FirstOrDefault(x => x.CMN_Language_RefID == languageToDoctor.CMN_Language_RefID) == null)
                            {
                                languageToDoctor.IsDeleted = true;
                                languageToDoctor.Save(Connection, Transaction);
                            }
                        }
                    }
                    else
                    {
                        List <ORM_CMN_BPT_BusinessParticipant_SpokenLanguage> languageToDoctorList = ORM_CMN_BPT_BusinessParticipant_SpokenLanguage.Query.Search(Connection, Transaction, new ORM_CMN_BPT_BusinessParticipant_SpokenLanguage.Query {
                            CMN_BPT_BusinessParticipant_RefID = patient.CMN_BPT_BusinessParticipant_RefID, IsDeleted = false, Tenant_RefID = securityTicket.TenantID
                        });
                        if (languageToDoctorList != null || languageToDoctorList.Count() != 0)
                        {
                            foreach (var language in languageToDoctorList)
                            {
                                language.IsDeleted = true;
                                language.Save(Connection, Transaction);
                            }
                        }
                    }

                    #endregion
                }
                #endregion
            }
            returnValue.Result = patient.HEC_PatientID;
            return(returnValue);

            #endregion UserCode
        }
        protected static FR_L2CN_GCCfPI_1222_Array Execute(DbConnection Connection, DbTransaction Transaction, P_L2CN_GCCfPI_1222 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            //Leave UserCode region to enable user code saving
            #region UserCode
            var returnValue = new FR_L2CN_GCCfPI_1222_Array();

            #region xmlContactTypes

            var xmlContactTypes = cls_Get_AllComunicationContactTypes.Invoke(Connection, Transaction, securityTicket).Result;

            #endregion

            #region peristedContactTypes
            var query = new ORM_CMN_PER_CommunicationContact_Type.Query();
            query.IsDeleted    = false;
            query.Tenant_RefID = securityTicket.TenantID;

            var peristedContactTypes = ORM_CMN_PER_CommunicationContact_Type.Query.Search(Connection, Transaction, query);
            #endregion

            #region contacts

            var query2 = new ORM_CMN_PER_CommunicationContact.Query();
            query2.IsDeleted        = false;
            query2.Tenant_RefID     = securityTicket.TenantID;
            query2.PersonInfo_RefID = Parameter.PersonInfoID;

            var contacts = ORM_CMN_PER_CommunicationContact.Query.Search(Connection, Transaction, query2);

            #endregion

            var result = new List <L2CN_GCCfPI_1222>();

            var differentTypes = contacts.GroupBy(i => i.Contact_Type).Select(g => g.First()).ToList();

            foreach (var contact in differentTypes)
            {
                var persitedContactType = peristedContactTypes.Where(i => i.CMN_PER_CommunicationContact_TypeID == contact.Contact_Type).SingleOrDefault();

                if (persitedContactType == null)
                {
                    continue;
                }

                var xmlContactType = xmlContactTypes.Where(i => i.Type == persitedContactType.Type).Single();

                var temp = new L2CN_GCCfPI_1222();
                temp.CMN_PER_CommunicationContact_TypeID = persitedContactType.CMN_PER_CommunicationContact_TypeID;
                temp.Type     = persitedContactType.Type;
                temp.TypeName = xmlContactType.Name;

                var relevantContacts = contacts.Where(i => i.Contact_Type == contact.Contact_Type);

                temp.Contacts = relevantContacts.Select(i => new L2CN_GCCfPI_1222a()
                {
                    CMN_PER_CommunicationContactID = i.CMN_PER_CommunicationContactID,
                    Content = i.Content
                }).ToArray();

                result.Add(temp);
            }

            returnValue.Result = result.ToArray();

            return(returnValue);

            #endregion UserCode
        }