private void PrepareForProcessing()
        {
            //Start off as not ready.
            ready = false;
            try
            {
                #region Get the Document
                //Get Document
                try { document = WCFHandler.GetInstance.GetDocument(this.objectID); }
                catch (Exception e) { throw new Exception(string.Format("Couldn't retrieve documentcontract. Msg:'{0}'", e.Message)); }
                #endregion

                #region Check against Additional Computed Identifier
                //Check against AdditionalComputedIdentifier if document is valid for processing.
                if (Properties.Settings.Default.AddCpIdisActive)
                {
                    try
                    {
                        ready = Convert.ToBoolean(ExpressionsEvaluator.GetInstance.Evaluate(Properties.Settings.Default.AdditionalComputedIdentifier, document));
                        if (!ready)
                        {
                            ready = false;
                            string message = string.Format("ACI validation returned false");
                            info    += message;
                            finished = true;
                        }
                    }
                    catch (Exception e) { throw new Exception(string.Format("ACI validation failed! Msg:'{0}'", e.Message)); }
                }
                else
                {
                    ready = true;
                }
                #endregion

                #region Get the Child-documents
                if (ready && Properties.Settings.Default.GroupingActive)
                {
                    try
                    {
                        var childDocs = WCFHandler.GetInstance.SearchForChildDocuments(document);

                        foreach (DocumentSimpleContract childDoc in childDocs)
                        {
                            //only add to childs if child!=parent
                            if (childDoc.Id != this.objectID)
                            {
                                childDocuments.Add(WCFHandler.GetInstance.GetDocument(childDoc.Id));
                            }
                        }

                        if (childDocuments.Count == 0 && !Properties.Settings.Default.GroupingSendWithoutChild)
                        {
                            ready = false;
                            string message = string.Format("Parent document has no child-documents. It will be ignored.");
                            info    += message;
                            finished = true;
                        }
                        childs = childDocuments.Count;
                    }
                    catch (Exception e) { throw new Exception(string.Format("Couldn't retrieve child-documents. Msg:'{0}'", e.Message)); }
                }
                #endregion

                #region Check CheckoutState of documents
                //Check checkoutstate of document
                if (ready && document.CheckOutStateEnum != "NotCheckedOut")
                {
                    try
                    {
                        //First try to force-checkin documents.
                        WCFHandler.GetInstance.UndoCheckOutDocument(this.objectID);
                    }
                    catch (Exception e) { throw new Exception(string.Format("Document is checked out! Attempt to undo-checkout failed. Is probably being edited by user. Msg:'{0}'", e.Message)); }
                }

                //Check checkoutstate of childdocuments if Markerproperties get inherited on childdocuments.
                if (ready && Properties.Settings.Default.GroupingInheritMarkerProperties)
                {
                    try
                    {
                        foreach (DocumentContract childDoc in childDocuments)
                        {
                            if (childDoc.CheckOutStateEnum != "NotCheckedOut")
                            {
                                try { WCFHandler.GetInstance.UndoCheckOutDocument(childDoc.Id); }
                                catch (Exception e) { throw new Exception(string.Format("Child-ObjectID:'{0}'. Msg:'{1}'", childDoc.Id, e.Message)); }
                            }
                        }
                    }
                    catch (Exception e) { throw new Exception(string.Format("A child-document is checked out! Attempt to undo-checkout failed. Is probably being edited by user. Msg:'{0}'", e.Message)); }
                }
                #endregion

                #region Prepare list of all documents touched by this WorkObject.
                allAffectedDocuments = new List <DocumentContract>();
                allAffectedDocuments.Add(this.document);
                //Only add ChildDocuments if Markerproperties get inherited on childdocuments.
                if (Properties.Settings.Default.GroupingInheritMarkerProperties)
                {
                    allAffectedDocuments.AddRange(childDocuments);
                }
                #endregion

                #region Deserialize or Evaluate the Processtemplate
                if (ready && Properties.Settings.Default.StartProcessActive)
                {
                    try
                    {
                        //Get ProcessTemplate from settings.
                        try { procTemplate = (ProcessTemplateContract)FileHelper.XmlDeserializeFromString(Properties.Settings.Default.ProcessName, procTemplate.GetType()); }
                        catch { }

                        if (procTemplate == null)
                        {
                            try
                            {
                                //Get ProcessTemplate from evaluated name value.
                                string processName = ExpressionsEvaluator.GetInstance.Evaluate(Properties.Settings.Default.ProcessName, this.document);
                                procTemplate = WCFHandler.GetInstance.GetProcessTemplateByName(processName);
                            }
                            catch (Exception e) { throw new Exception(string.Format("Couldn't evaluate processtemplate from property. Msg:'{0}'", e.Message)); }
                        }


                        //Get all userids from recipients-array.
                        try
                        {
                            string[] recipientsInput = Properties.Settings.Default.ProcessRecipient.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                            for (int i = 0; i < recipientsInput.Length; i++)
                            {
                                recipientsInput[i] = ExpressionsEvaluator.GetInstance.Evaluate(recipientsInput[i], this.document);
                            }


                            string[] sUserIDs = new string[recipientsInput.Length];


                            //Convert USERID TO GUID!
                            //if (lUsers == null)
                            //    lUsers = getAllUsers();

                            UserContract[] lUsers = WCFHandler.GetInstance.GetAllUsers();

                            for (int i = 0; i < recipientsInput.Length; i++)
                            {
                                foreach (UserContract uInf in lUsers)
                                {
                                    if (uInf.DisplayName.ToLower() == recipientsInput[i].ToLower() || uInf.LoginName.ToLower() == recipientsInput[i].ToLower() || uInf.Email.ToLower() == recipientsInput[i].ToLower())
                                    {
                                        sUserIDs[i] = uInf.Id;
                                        break;
                                    }
                                }
                            }
                            procUserIDS = sUserIDs;
                        }
                        catch (Exception e) { throw new Exception(string.Format("Couldn't prepare process recipients for document. Msg:'{0}'", e.Message)); }
                    }

                    catch (Exception e) { throw new Exception(string.Format("Couldn't prepare processtemplate for document. Msg:'{0}'", e.Message)); }
                }
                #endregion


                #region Markerproperties and new DocumentContracts
                if (ready)
                {
                    try
                    {
                        //Get Markerproperties from settings.
                        markerProperties = (List <BO.MarkerProperty>)(FileHelper.XmlDeserializeFromString(Properties.Settings.Default.MarkerProperties, markerProperties.GetType()));

                        if (markerProperties.Count > 0)
                        {
                            DateTime start = DateTime.Now;
                            //Evaluate MarkerProperty-Values
                            foreach (MarkerProperty mProp in markerProperties)
                            {
                                //Evaluate markerproperty
                                for (int i = 0; i < mProp.values.Length; i++)
                                {
                                    //mProp.values[i] = ExpressionsEvaluator.GetInstance.Evaluate(mProp.values[i], this.document, true, true);
                                    //Do TEST-Evaluation WITHOUT setting value on new document-contract.
                                    ExpressionsEvaluator.GetInstance.Evaluate(mProp.values[i], this.document, true, true);
                                }
                            }
                            DateTime end = DateTime.Now;
                            log4.Debug(string.Format("Test-evaulation of markerproperties for document took {0}ms. ObjectID:'{1}'", (end - start).TotalMilliseconds.ToString(), this.objectID));
                        }
                    }
                    catch (Exception e) { throw new Exception(string.Format("Markerproperties could not be prepared! Msg: {0}", e.Message)); }
                }
                #endregion
            }

            catch (Exception e)
            {
                string message = string.Format("There was a problem preparing the document for processing. ObjectID:'{0}', Msg:'{1}'", objectID, e.Message);
                log4.Error(message);
                ready = false;
                error = true;
                info  = message;
            }
            finally
            {
                prepared = true;
            }
        }
        private void Settings_Load(object sender, EventArgs e)
        {
            string sProgramPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            #region Tooltip
            // Create the ToolTip and associate with the Form container.
            ToolTip toolTip1 = new ToolTip
            {
                // Set up the delays for the ToolTip.
                AutoPopDelay = 20000,
                InitialDelay = 0,
                ReshowDelay  = 0,
                // Force the ToolTip text to be displayed whether or not the form is active.
                ShowAlways = true
            };

            // Set up the ToolTip text for the Button and Checkbox.
            toolTip1.SetToolTip(this.btnInsertIndexMailSubject, "Add a documentproperty");
            toolTip1.SetToolTip(this.btnBrowseEmailTemplate, "Browse e-mail template.");

            toolTip1.SetToolTip(this.txtBxAdditionalComputedIdentifier, "Result must be a boolean.\r\n" +
                                "Custom Functions: TodayDate, TodayTime,\r\n" +
                                "IDX('Prop'),DateDiff(date,date), AddDays(date,days).\r\n" +
                                "Hard-coded dates in # like '#01.01.2015#'");
            toolTip1.SetToolTip(this.btnInsertMultiLanguageProperty, "If selected, the template is selected using the value of this property.\r\n" +
                                "For Example: template.html is selected -> template.html.de, template.html.fr,template.html.en is used.");

            toolTip1.SetToolTip(this.btnInsertAttachmentRenameProperty, "If this is configured, the configured value will be used as the filename of the attachment (also works with grouping).\r\n" +
                                "This field uses the NCALC-Syntax. The Filetype is automatically added depending on the original file.");


            #region Archive/Mail
            toolTip1.SetToolTip(this.cbEncodePW, "Save password encrypted.");
            toolTip1.SetToolTip(this.txtBxKendoxWebserviceURL, "URL to KX WCF-Webservice 'http://SERVER/InfoShare'");
            #endregion

            #region Process
            toolTip1.SetToolTip(this.txtBxProcessRecipient, "Recipient(s) (kendox-user) of process. Can be logon-name, display name or e-mail of kendox user.\r\n" +
                                "If left emtpy, process will be sent to standard user(s) defined in process-template.\r\n" +
                                "Example: IDX('Ersteller');'philipp.aeberhard' -> would send to 'Ersteller' AND user 'p.a.'");


            toolTip1.SetToolTip(this.cBSelectedProcess, "Process that gets startet with document attached. Select template for fixed process.\r\n" +
                                "Name of template can be dinamically evaluated on runtime.\r\n" +
                                "Example: IDX('Vertragsart') -> Would start process named after the 'Vertragsart' of document.");
            #endregion

            #endregion


            //Load All Configuration from Config
            txtBxSMTPServer.Text   = Properties.Settings.Default.SMTPServerAdress;
            txtBxSMTPPort.Text     = Properties.Settings.Default.SMTPPort;
            txtBXSMTPUsername.Text = Properties.Settings.Default.SMTPUsername;
            txtBxSMTPPassword.Text = Properties.Settings.Default.SMPTPassword;
            cBUseTSL.Checked       = Properties.Settings.Default.SMTPUseSSL;

            cBSendMailActive.Checked = Properties.Settings.Default.SendMailActive;
            txtBxSMTPSender.Text     = Properties.Settings.Default.SMTPSender;
            txtBxSMTPSendTo.Text     = Properties.Settings.Default.EBillSendTo;
            txtBxSMTPSubject.Text    = Properties.Settings.Default.EBillSubject;
            //EmailTemplate
            txtBxEmailTemplatePath.Text        = Properties.Settings.Default.EmailTemplatePath;
            txtBxMultiLanguageProperty.Text    = Properties.Settings.Default.MultiLanguageTemplateProperty;
            txtBxAttachmentRenameProperty.Text = Properties.Settings.Default.AttachmentRenameProperty;

            if ((string)Properties.Settings.Default.EmailTemplatePath == "")
            {
                string templateFilePath = Path.Combine(sProgramPath, "standard_email_template.html");
                txtBxEmailTemplatePath.Text = templateFilePath;
            }
            else
            {
                txtBxEmailTemplatePath.Text = Properties.Settings.Default.EmailTemplatePath;
            }



            cBDocSafeActive.Checked = Properties.Settings.Default.DocSafeActive;

            txtBxKendoxWebserviceURL.Text = Properties.Settings.Default.KendoxWCFURL;
            txtBxKendoxUsername.Text      = Properties.Settings.Default.KendoxUsername;
            cbEncodePW.Checked            = Properties.Settings.Default.isKXPWEncrypted;
            txtBxKendoxPassword.Text      = Properties.Settings.Default.KendoxPassword;
            cBCulture.SelectedText        = Properties.Settings.Default.Culture;

            cBSendErrorMail.Checked       = Properties.Settings.Default.SendErrorMail;
            tbErrorMailSendTo.Text        = Properties.Settings.Default.ErrorMailSendTo;
            tBErrorMailSubject.Text       = Properties.Settings.Default.ErrorMailSubject;
            cBErrorMailIncludeLog.Checked = Properties.Settings.Default.ErrorMailIncludeLog;



            //ProcessTemplate
            cBStartProcessActive.Checked = Properties.Settings.Default.StartProcessActive;
            txtBxProcessRecipient.Text   = Properties.Settings.Default.ProcessRecipient;

            cBSelectedProcess.DisplayMember = "Text";
            cBSelectedProcess.ValueMember   = "Value";

            ProcessTemplateContract processTemplateItem = new ProcessTemplateContract();

            if (Properties.Settings.Default.ProcessName != "")
            {
                //Try to deserialize
                try
                {
                    processTemplateItem = (ProcessTemplateContract)FileHelper.XmlDeserializeFromString(Properties.Settings.Default.ProcessName, processTemplateItem.GetType());
                    cBSelectedProcess.Items.Add(new { Text = WCFHandler.GetInstance.GetProcessTemplateName(processTemplateItem.Id), Value = processTemplateItem.Id });
                    cBSelectedProcess.SelectedIndex = 0;
                }
                //if it doesn't work, its a string.
                catch
                {
                    cBSelectedProcess.Text = Properties.Settings.Default.ProcessName;
                }
            }
            else
            {
                //cBSelectedProcess.Items.Add("Template auswählen...");
                //cBSelectedProcess.SelectedIndex = 0;
                cBSelectedProcess.Text = "Template auswählen...";
            }


            //cBStartProcessActive.Checked = Properties.Settings.Default.StartProcessActive;
            //txtBxProcessRecipient.Text = Properties.Settings.Default.ProcessRecipient;
            //cBSelectedProcess.Items.Add(Properties.Settings.Default.ProcessName);
            //cBSelectedProcess.SelectedIndex = 0;



            //linkfile
            cBAttFile.Checked = Properties.Settings.Default.AttachDocument;
            if (!cBAttFile.Checked)
            {
                Properties.Settings.Default.GroupingActive = false;
                cBGroupingActive.Enabled = false;
            }

            cBKxLinkFile.Checked = Properties.Settings.Default.AttachLnkFile;
            if ((string)Properties.Settings.Default.LnkFilePath == "")
            {
                string templateFilePath = Path.Combine(sProgramPath, "standard_linkfile_template.dlk");
                txtBxLinkFilePath.Text = templateFilePath;
            }
            else
            {
                txtBxLinkFilePath.Text = Properties.Settings.Default.LnkFilePath;
            }

            //Grouping
            cBGroupingActive.Checked = Properties.Settings.Default.GroupingActive;

            //Report
            cbIsReportActive.Checked  = Properties.Settings.Default.IsReportActive;
            txtBxReportRecipient.Text = Properties.Settings.Default.ReportRecipient;
            txtBxReportSubject.Text   = Properties.Settings.Default.ReportSubject;
            if ((string)Properties.Settings.Default.ReportTemplatePath == "")
            {
                string templateFilePath = Path.Combine(sProgramPath, "standard_report_template.html");
                txtBxReportTemplatePath.Text = templateFilePath;
            }
            else
            {
                txtBxReportTemplatePath.Text = Properties.Settings.Default.ReportTemplatePath;
            }

            //AdditionalIdentifier
            txtBxAdditionalComputedIdentifier.Text = Properties.Settings.Default.AdditionalComputedIdentifier;
            cBAddCpIdisActive.Checked = Properties.Settings.Default.AddCpIdisActive;


            foreach (string store in Properties.Settings.Default.KendoxInfoStores.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
            {
                lInfoStores.Add(new KeyValuePair <string, bool>(store, true));
            }
            UpdateInfoStoreList(lInfoStores);

            //SearchQuantity
            nUdSearchQuantity.Value = Properties.Settings.Default.SearchQuantity;

            //SearchConditions
            List <InfoShareService.SearchConditionContract> searchonlist = new List <InfoShareService.SearchConditionContract>();
            if (Properties.Settings.Default.SearchProperties != "")
            {
                searchonlist = (List <InfoShareService.SearchConditionContract>)(FileHelper.XmlDeserializeFromString(Properties.Settings.Default.SearchProperties, searchonlist.GetType()));
            }

            //Fill SearchProperties
            foreach (InfoShareService.SearchConditionContract searchcon in searchonlist)
            {
                string comparisonEnum = Enum.GetName(typeof(BO.Utility.SearchComparisonEnum), Convert.ToInt16(searchcon.ComparisonEnum));
                string relationEnum   = Enum.GetName(typeof(BO.Utility.SearchRelationEnum), Convert.ToInt16(searchcon.RelationEnum));

                string[] row = { WCFHandler.GetInstance.GetPropertyTypeName(searchcon.PropertyTypeId), comparisonEnum, string.Join(";", searchcon.Values), relationEnum };
                dgwSearchProperties.Rows.Add(row);
            }

            //MarkerProperites
            List <BO.MarkerProperty> NEWmarkerProperties = new List <BO.MarkerProperty>();
            if (Properties.Settings.Default.MarkerProperties != "")
            {
                NEWmarkerProperties = (List <BO.MarkerProperty>)(FileHelper.XmlDeserializeFromString(Properties.Settings.Default.MarkerProperties, NEWmarkerProperties.GetType()));
            }

            //Fill MarkerProperties
            foreach (BO.MarkerProperty markerproperty in NEWmarkerProperties)
            {
                string propertyTypeID = markerproperty.propertyTypeID;
                string values         = string.Join(";", markerproperty.values);
                string updateAction   = markerproperty.updateAction.ToString();

                string[] row = { WCFHandler.GetInstance.GetPropertyTypeName(propertyTypeID), values, updateAction };
                dGwMarkerProperties.Rows.Add(row);
            }

            preLoadSettingsData();
        }