/// <summary> /// Updates the value of a document property with the new property value. /// /// Gets the property type id for the specified property type name. /// Gets the document contract for the specified document id. The contract /// contains an array of property contracts. Gets a list of property contracts. /// The method searches for the property contract with the property type id. /// If it finds the contract, it updates the property contract with the new /// value. Then it updates the document contract's properties field. /// Afterwards it calls the updateDocument method on an instance of the /// InfoShareService class and passes the connection id, the document contract, /// and the check in parameter contract as arguments. /// Releases the reservation of the document in order that other users can edit the document /// Returns a document contract, if the document is successfully updated. /// /// </summary> /// <param name="documentClient">the document client of the info share WCF service</param> /// <param name="commonClient">the common client of the info share WCF service</param> /// <param name="connectionID">the connection id</param> /// <param name="documentID">the document id</param> /// <param name="propertyTypeName">the property type name</param> /// <param name="newPropertyValue">the new property value</param> /// <param name="schemaCulture">the schema culture</param> /// <returns>the document contract</returns> public DocumentContract UpdateDocumentProperty(CommonService commonService, string connectionID, string documentID, string propertyTypeName, string newPropertyValue, string schemaCulture) { string propertyTypeID = commonService.GetPropertyTypeID(propertyTypeName, schemaCulture); DocumentContract documentContract = this.DocumentClient.GetDocument(connectionID, documentID); // Loops through all properties of property contract foreach (PropertyContract propertyContract in documentContract.Properties) { if (propertyContract.PropertyTypeId == propertyTypeID) { // If property contract found, set new value propertyContract.Values = new string[] { newPropertyValue }; break; } } CheckInParameterContract checkInParameterContract = new CheckInParameterContract { // Releases the reservation of the document in order that other users can edit the document ReleaseReservation = true }; documentContract = this.DocumentClient.UpdateDocument(connectionID, documentContract, null, checkInParameterContract); return(documentContract); }
public FormInput(DocumentContract contract) { Date = contract.Date; Name = contract.Name; AddressDetails_City = contract.AddressDetails.City; AddressDetails_PostCode = contract.AddressDetails.PostCode; AddressDetails_BuildingNumber = contract.AddressDetails.BuildingNumber; AddressDetails_StreetName = contract.AddressDetails.StreetName; Corr_StreetName = contract.CorrespondenceAddressDetails?.StreetName ?? string.Empty; Corr_BuildingNumber = contract.CorrespondenceAddressDetails?.BuildingNumber ?? string.Empty; Corr_City = contract.CorrespondenceAddressDetails?.City ?? string.Empty; Corr_PostCode = contract.CorrespondenceAddressDetails?.PostCode ?? string.Empty; PhoneNumber = contract.PhoneNumber; Email = contract.Email; PlannedCompletionDate = contract.PlannedCompletionDate; EstimatedCost = contract.EstimatedCost; HeatingNetworkDetails = contract.CanConnectToHeatingNetwork ? "mam" : "nie mam"; GasNetworkDetails = contract.CanConnectToGasNetwork ? "mam" : "nie mam"; YearOfInvestment = contract.YearOfInvestment; DokumentyPotwierdzajace = contract.DispositionLawDocuments; ExectuionCompany = contract.ExectuionCompany; UczestnicyPrawa = string.Join( ", ", contract.LawParticipants.Select(up => up.Name + " " + up.AddressDetails.StreetName + " " + up.AddressDetails.BuildingNumber + " " + up.AddressDetails.PostCode + " " + up.AddressDetails.City).ToList()); BankDetails_Name = contract.BankDetails.Name; BankDetails_Number = contract.BankDetails.Number; Inv_NumerEwidencjiDzialki = contract.PlannedWorkAddressDetails.PropertyRegistrationNumber; Inv_Obreb = contract.PlannedWorkAddressDetails.District; Inv_PostCode = contract.PlannedWorkAddressDetails.PostCode; Inv_BuildingNumber = contract.PlannedWorkAddressDetails.BuildingNumber; Inv_StreetName = contract.PlannedWorkAddressDetails.StreetName; Inv_City = contract.PlannedWorkAddressDetails.City; Inv_PowierzchniaUzytkowa = contract.PlannedWorkAddressDetails.UsableArea.ToString(); PlannedWorkAddressDetails_UzytkowanieDlaDzialalnosciGospodarczej = contract.PlannedWorkAddressDetails.IsForCommercialUse ? "tak" : "nie"; PowierzchniaPodDzialalnosc = contract.PlannedWorkAddressDetails.CommercialArea.ToString(); StosunekPowierzchniDzialalnosciDoUzytkowej = contract.PlannedWorkAddressDetails.CommercialToUsableAreaRatio.ToString(); PlannedWorkAddressDetails_StreetName = contract.PlannedWorkAddressDetails.StreetName; PlannedWorkAddressDetails_BuildingNumber = contract.PlannedWorkAddressDetails.BuildingNumber; PlannedWorkAddressDetails_City = contract.PlannedWorkAddressDetails.City; PlannedWorkAddressDetails_PostCode = contract.PlannedWorkAddressDetails.PostCode; OldEnergyCharacteristics_Power = contract.OldEnergyCharacteristics.Power.ToString(); OldEnergyCharacteristics_Age = contract.OldEnergyCharacteristics.Age.ToString(); OldEnergyCharacteristics_ConsumptionPerYear = contract.OldEnergyCharacteristics.ConsumptionPerYear.ToString(); OldEnergyCharacteristics_Type = GetHeatingType(contract.OldEnergyCharacteristics.Type); PlannedEnergyCharacteristics_Power = contract.PlannedEnergyCharacteristics.Power.ToString(); PlannedEnergyCharacteristics_ConsumptionPerYear = contract.PlannedEnergyCharacteristics.ConsumptionPerYear.ToString(); PlannedEnergyCharacteristics_Type = GetHeatingType(contract.PlannedEnergyCharacteristics.Type); TytulPrawaDoDyspozycji = string.Format(GetOwnershipType(contract.PropertyOwnershipType), UczestnicyPrawa); CompanyDetails_Type = GetCompanyDetails(contract.InvestorType); InvestorType_B = GetInvestorType(contract.InvestorType); Date_Today = DateTime.Today.ToString("dd-MM-yyyy"); Nip = contract.Nip; }
internal DocumentSimpleContract[] SearchForChildDocuments(DocumentContract parentDoc) { isConnected(); //Get Grouping-Search Properties and evaluate them. List <SearchConditionContract> searchConContractList = new List <SearchConditionContract>(); searchConContractList = (List <SearchConditionContract>)(FileHelper.XmlDeserializeFromString(Properties.Settings.Default.GroupingSearchProperties, searchConContractList.GetType())); searchConContractList = EvaluateSearchConditions(searchConContractList, parentDoc); SearchDefinitionContract sDefContract = new SearchDefinitionContract { Conditions = searchConContractList.ToArray() }; //***ADDITIONAL CHECKS FOR SAFETY*** //Check against no grouping search-properties. if (searchConContractList.Count() < 1) { throw new Exception("No grouping searchproperties defined! This could result in an accidental sending of an entire archive. This file will thus be ignored!"); } //If grouping searchproperty of parent evaluated to empty (val = "") we could end up sending an entire archive by accident. foreach (SearchConditionContract scc in searchConContractList) { foreach (string val in scc.Values) { if (val == "") { throw new Exception("Searchproperties for child-document-search were empty. This could result in an accidental sending of an entire archive. This file will thus be ignored!"); } } } //Set InfoStores to search for. //If "All" is selected, "null" is sent. List <string> infoStores = new List <string>(); var infoStoresArray = Properties.Settings.Default.KendoxInfoStores.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); if (!infoStoresArray.Contains("All")) { foreach (string infoStore in infoStoresArray) { infoStores.Add(commonService.GetInfoStoreID(ConnectionID, infoStore, Properties.Settings.Default.Culture)); } sDefContract.SearchStores = infoStores.ToArray(); } //Set PageSize //Maximum of 50 childdocuments would get send. sDefContract.PageSize = 50; var resultContract = searchService.SearchDocument(commonService, ConnectionID, sDefContract, null); return(resultContract.Documents); }
/// <summary> /// Creates a document for the specified file id. /// /// Searches for the import template contract with the specified import /// template id and assigns the template to the document contract. It also /// takes over the protection domain and the info store from the import /// template and assigns it to the document contract. It reads out the /// properties passed in the hash map and sets the properties' keys and /// values for the document contract. Furthermore, it sets the name of /// the document. Calls the createDocument method on an instance of the /// InfoShareService class and passes the connection id, the document /// contract, and the file id as arguments. Returns the document contract, /// if the contract is successfully created. /// /// Before creating a document you must call either the uploadFileBytes or /// uploadFileBytesInChunks method on an instance of the File class. These /// methods return the file id you need to create a document. /// /// </summary> /// <param name="documentClient">the document client of the info share WCF service</param> /// <param name="commonClient">the common client of the info share WCF service</param> /// <param name="connectionID">the connection id</param> /// <param name="fileID">the file name</param> /// <param name="documentName">the document name</param> /// <param name="importTemplateID">the import template id</param> /// <param name="schemaCulture">the schema culture</param> /// <param name="dictionaryProperties">the dictionary that contains the properties as key/value pairs</param> /// <returns>the document contract</returns> public DocumentContract CreateDocument(CommonService commonService, string connectionID, string fileID, string documentName, string importTemplateID, string schemaCulture, Dictionary <string, string[]> dictionaryProperties) { DocumentContract documentContract = null; // Gets the import template contract for the specified import template id ImportTemplateContract importTemplateContract = commonService.GetImportTemplateContract(importTemplateID); string propertyPageTemplateID = importTemplateContract.PropertyPageTemplateId; // Gets the property page template contract assigned to the import template contract PropertyPageTemplateContract propertyPageTemplateContract = commonService.GetPropertyPageTemplateContract(propertyPageTemplateID); if (propertyPageTemplateContract != null) { // Gets an array of all property template contracts assigned to the property page template PropertyTemplateContract[] arrayOfPropertyTemplateContract = propertyPageTemplateContract.PropertyTemplates; // Array of property contracts to be set on the document contract further down (see A) IList <PropertyContract> listOfPropertyContract = new List <PropertyContract>(); foreach (PropertyTemplateContract template in arrayOfPropertyTemplateContract) { string propertyTypeID = template.PropertyTypeId; PropertyTypeContract propertyTypeContract = commonService.GetPropertyTypeContract(propertyTypeID); string propertyName = Utility.GetValue(propertyTypeContract.Name, schemaCulture); if (!String.IsNullOrEmpty(propertyName)) { string[] values; dictionaryProperties.TryGetValue(propertyName, out values); // Gets value for key from dictionary PropertyContract propertyContract = new PropertyContract { PropertyTypeId = propertyTypeID, Values = values }; listOfPropertyContract.Add(propertyContract); // Adds property contract } } // Sets mandatory fields documentContract = new DocumentContract { ImportTemplateId = importTemplateID, ProtectionDomainId = importTemplateContract.ProtectionDomainId, InfoStoreId = importTemplateContract.InfoStoreId, Properties = listOfPropertyContract.ToArray(), // Sets all property contracts (A) Name = documentName }; //documentContract = this.DocumentClient.CreateDocument(connectionID, documentContract, fileID, options: null); } return(documentContract); }
/// <summary> /// Uses the Name of the <c>DocumentContract</c> object to build a file name. /// </summary> /// <param name="documentContract">The <c>DocumentContract</c> object.</param> /// <returns>The file name value.</returns> private string DocumentContractFileName(DocumentContract documentContract) { Debug.Assert(documentContract != null, "Parameter 'documentContract' must not be null or empty."); Debug.Assert(!string.IsNullOrWhiteSpace(documentContract.Name), "Parameter 'documentContract.Name' must not be null or empty."); string value = Path.GetFileNameWithoutExtension(documentContract.Name); value = string.Concat(value, Constants.PdfExtension); return(value); }
/// <summary> /// Updates the document with a new file version. /// </summary> /// <param name="connectionID">the connection id</param> /// <param name="documentContract">the document contract to be updated</param> /// <param name="fileId">the file id of the new file version</param> /// <returns>the updated document contract</returns> public DocumentContract UpdateDocument(string connectionID, DocumentContract documentContract, string fileId = null) { CheckInParameterContract checkInParameterContract = new CheckInParameterContract { // Releases the reservation of the document in order that other users can edit the document ReleaseReservation = true, Comment = "Updated trough FIVE-Docreminder." }; DocumentContract updatedDocumentContract = this.DocumentClient.UpdateDocument(connectionID, documentContract, fileId, checkInParameterContract); return(updatedDocumentContract); }
public async Task <string> SendDocumentMail(DocumentContract doc, string tempDirectory) { //PrepareMail using (MailMessage mail = new MailMessage()) { mail.Sender = new MailAddress(Properties.Settings.Default.SMTPSender); mail.From = new MailAddress(Properties.Settings.Default.SMTPSender); //Prepare Recipients string[] recipientsInput = Properties.Settings.Default.EBillSendTo.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries); string[] validRecipients = new string[recipientsInput.Length]; try { for (int i = 0; i < recipientsInput.Length; i++) { //AEPH 11.02.2016 - check if recipient may be a username. recipientsInput[i] = ExpressionsEvaluator.GetInstance.Evaluate(recipientsInput[i], doc); } for (int i = 0; i < recipientsInput.Length; i++) { if (FileHelper.IsValidMail(recipientsInput[i])) { validRecipients[i] = recipientsInput[i]; } else { string evaluatedRecipient = recipientsInput[i].ToLower(); foreach (UserContract uInf in WCFHandler.GetInstance.GetAllUsers()) { if (uInf.DisplayName.ToLower() == evaluatedRecipient || uInf.LoginName.ToLower() == evaluatedRecipient || uInf.Id == evaluatedRecipient) { if (uInf.Email != null && uInf.Email != "") { evaluatedRecipient = uInf.Email; if (FileHelper.IsValidMail(evaluatedRecipient.ToString())) { validRecipients[i] = evaluatedRecipient; break; } } else { log4.Warn(string.Format("No valid E-Mail could be resolved for recipient: '{0}'. Object ID: '{1}'", uInf.DisplayName, doc.Id)); } } } } } } catch (Exception e) { throw new Exception(string.Format("An Error happened during preparation of the e-mail recipients. Msg:'{0}'", e.Message)); } //Add Recipients to mail. foreach (string address in validRecipients) { if (address != null) { mail.To.Add(address); } } if (mail.To.Count == 0) { throw new Exception("No valid E-mail could be extracted from configured recipients:" + string.Join(";", recipientsInput)); } //Evaluate MailSubject string mailSubject = Properties.Settings.Default.EBillSubject; try { mailSubject = ExpressionsEvaluator.GetInstance.Evaluate(mailSubject, doc); } catch (Exception e) { log4.Warn(string.Format("An Error happened during preparation of the e-mail subject. Msg:'{0}'", e.Message)); } mail.Subject = mailSubject; string mailBody = ""; //Check if MulitlanguageTemplateSupport is Active if (Properties.Settings.Default.MultiLanguageTemplateProperty == "") { Encoding enc; using (StreamReader reader = new StreamReader(Properties.Settings.Default.EmailTemplatePath, Encoding.GetEncoding(1252), true)) { reader.Peek(); // you need this! enc = reader.CurrentEncoding; } //Note: Maybe read as HTML here to maintain format of all expressions. mailBody = System.IO.File.ReadAllText(Properties.Settings.Default.EmailTemplatePath, enc); } else { string usedTemplatePath = Properties.Settings.Default.EmailTemplatePath; string sMultiLangPropVal = ExpressionsEvaluator.GetInstance.Evaluate(Properties.Settings.Default.MultiLanguageTemplateProperty, doc); string sMLPath = Properties.Settings.Default.EmailTemplatePath + "." + sMultiLangPropVal; if (sMultiLangPropVal == "" || !System.IO.File.Exists(sMLPath)) { log4.Warn(string.Format("MultiLanguage prop not on document, or template not found! Using standard template instead. Object ID: '{0}'", doc.Id)); } else { usedTemplatePath = sMLPath; } Encoding enc; using (StreamReader reader = new StreamReader(usedTemplatePath, Encoding.GetEncoding(1252), true)) { reader.Peek(); // you need this! enc = reader.CurrentEncoding; } mailBody = System.IO.File.ReadAllText(usedTemplatePath, enc); } //AEPH 10.02.2016 Multiline Support for Regex Match. //But replace new-line char. string[] IndexHits = Regex.Matches(mailBody, @"(?<=\$\[)(.|\s)*?(?=\]\$)").Cast <Match>().Select(m => m.Value).ToArray(); foreach (string expression in IndexHits) { string expressionNewLineEscaped = expression.Replace(System.Environment.NewLine, ""); string rep = "$[" + expression + "]$"; string with = "$[" + expression + "]$"; try { with = ExpressionsEvaluator.GetInstance.Evaluate(expressionNewLineEscaped, doc); } catch (Exception e) { log4.Warn(string.Format("Ignoring expression in E-Mail Template. Expression: '{0}' Object ID: '{1}' Msg:'{2}'", rep, doc.Id, e.Message)); } with = WebUtility.HtmlEncode(with); mailBody = mailBody.Replace(rep, with); } //Check for HTML Regex tagRegex = new Regex(@"<\s*([^ >]+)[^>]*>.*?<\s*/\s*\1\s*>"); if (tagRegex.IsMatch(mailBody)) { mail.IsBodyHtml = true; } mail.Body = mailBody; //Attachements if (Properties.Settings.Default.AttachDocument) { //DONE - SwissRe Sorting functionality. //AEPH 23.03.2017 - Getting Files in Alphabetical Order. var files = Directory.GetFiles(tempDirectory, "*", SearchOption.AllDirectories).OrderBy(f => f); foreach (string file in files) { mail.Attachments.Add(new Attachment(file)); } //Dont delete Directory yet or attachements will not be sent. //Directory.Delete(tempDirectory,true); } if (Properties.Settings.Default.AttachLnkFile) { //Get some binary data string sFileContent = ""; string templateFilePath = ""; string docID = ""; string storeID = ""; string docname = ""; docID = doc.Id; storeID = doc.InfoStoreId; docname = doc.Name; if (Properties.Settings.Default.LnkFilePath != "") { templateFilePath = Properties.Settings.Default.LnkFilePath; } else { string progPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); templateFilePath = Path.Combine(progPath, "DefaultTemplates/standard_linkfile_template.dlk"); } if (System.IO.File.Exists(templateFilePath)) { try { XmlDocument xDoc = new XmlDocument(); xDoc.Load(templateFilePath); XmlNode nodeDocID = xDoc.SelectSingleNode("/InfoShareLink/InfoShareFiles/InfoShareFile/InfoObjectID"); XmlNode nodeStoreID = xDoc.SelectSingleNode("/InfoShareLink/InfoShareFiles/InfoShareFile/InfoStoreID"); nodeDocID.InnerText = docID; nodeStoreID.InnerText = storeID; sFileContent = xDoc.InnerXml; } catch (Exception e) { log4.Warn(string.Format("Error happened during preparation of the linkfile. Ignoring template. Object ID: '{0}' Msg:'{1}'", doc.Id, e.Message)); sFileContent = "<InfoShareLink><InfoShareFiles><InfoShareFile><InfoObjectID>" + docID + "</InfoObjectID><InfoStoreID>" + storeID + "</InfoStoreID></InfoShareFile></InfoShareFiles><InfoShareFolderConfiguration><GroupedListViewColumns /></InfoShareFolderConfiguration></InfoShareLink>"; } } else { //AEPH 09.02.2016 log4.Warn(string.Format("No template path for linkfile defined, using standard link-file template instead. Object ID: '{0}'", doc.Id)); sFileContent = "<InfoShareLink><InfoShareFiles><InfoShareFile><InfoObjectID>" + docID + "</InfoObjectID><InfoStoreID>" + storeID + "</InfoStoreID></InfoShareFile></InfoShareFiles><InfoShareFolderConfiguration><GroupedListViewColumns /></InfoShareFolderConfiguration></InfoShareLink>"; } byte[] data = new byte[sFileContent.Length * sizeof(char)]; System.Buffer.BlockCopy(sFileContent.ToCharArray(), 0, data, 0, data.Length); //save the data to a memory stream MemoryStream ms = new MemoryStream(data); //create the attachment from a stream. Be sure to name the data //with a file and //media type that is respective of the data mail.Attachments.Add(new Attachment(ms, docname + ".dlk", "text/plain")); } //AEPH 25.01.2017 string result = null; log4.Info(string.Format("Trying to send Mail. Recipient:'{0}' Object ID: '{1}'", mail.To.ToString(), doc.Id)); try { Task <bool> AsyncTaskSendMail = SendEmailAsync(mail); await AsyncTaskSendMail; //result = AsyncTaskSendMail.Result; result = mail.To.ToString(); log4.Info(string.Format("Positive answer from mail server. Recipient:'{0}' Object ID: '{1}'", mail.To.ToString(), doc.Id)); } catch (Exception e) { throw new Exception(string.Format("Error happened while sending mail! Recipient:'{0}', Object ID: '{1}', Msg:'{2}'", mail.To.ToString(), doc.Id, e.Message)); } return(result); } }
public List <SearchConditionContract> EvaluateSearchConditions(List <SearchConditionContract> searchConList, DocumentContract doc = null) { //Evaluate Searchconditions foreach (SearchConditionContract sCon in searchConList) { try { string[] sNewValues = new string[sCon.Values.Length]; int i = 0; foreach (string sValue in sCon.Values) { //don't evaluate if "" if (sValue != "") { string sEvaluatedValue = ""; sEvaluatedValue = ExpressionsEvaluator.GetInstance.Evaluate(sValue, doc, false, true); sNewValues[i] = sEvaluatedValue; } else { sNewValues[i] = sValue; } i++; } sCon.Values = sNewValues; } catch (Exception e) { throw new Exception(string.Format("An Error happened while evaluating the SearchProperties. Msg: {0}", e.Message)); } } return(searchConList); }
internal void UpdateDocument(DocumentContract documentConctract) { documentService.UpdateDocument(ConnectionID, documentConctract); }
/// <summary> /// Can insert the document if: /// 1. DocumentContract.Data is not empty AND /// 2. A document with the same file name doesn't already exist in the database. /// </summary> /// <param name="contract">The DocumentContract.</param> /// <param name="context">The document Database context.</param> /// <returns></returns> private static bool CanInsertDocument(DocumentContract contract, DocumentLibraryContext context) { return(!string.IsNullOrEmpty(contract.Data) && !context.TestDocuments.Any(x => x.FileName.Equals(contract.FileName, StringComparison.OrdinalIgnoreCase))); }
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; } }
public void MergeMarkerPropertiesToDocument(DocumentContract doc) { //Merge new properties to current document properties. foreach (MarkerProperty mProp in markerProperties) { var prop = doc.Properties.Where(x => x.PropertyTypeId == mProp.propertyTypeID).FirstOrDefault(); if (mProp.updateAction == MarkerProperty.UpdateAction.ADD) { //If prop exists. Add at the end. if (prop != null) { List <string> vals = prop.Values.ToList(); vals.AddRange(mProp.values); prop.Values = vals.ToArray(); } //Create new else { PropertyContract newProp = new PropertyContract() { PropertyTypeId = mProp.propertyTypeID, Values = mProp.values }; var props = this.document.Properties.ToList(); props.Add(newProp); this.document.Properties = props.ToArray(); } } if (mProp.updateAction == MarkerProperty.UpdateAction.UPDATE) { //If prop exists. Replace values. if (prop != null) { prop.Values = mProp.values.ToArray(); } //Create new else { PropertyContract newProp = new PropertyContract() { PropertyTypeId = mProp.propertyTypeID, Values = mProp.values }; var props = this.document.Properties.ToList(); props.Add(newProp); this.document.Properties = props.ToArray(); } } if (mProp.updateAction == MarkerProperty.UpdateAction.DELETE) { //Remove property if it exists. if (prop != null) { var props = this.document.Properties.ToList(); props.Remove(prop); this.document.Properties = props.ToArray(); } } if (mProp.updateAction == MarkerProperty.UpdateAction.NONE) { //Do Nothing } } }
public void Process() { if (ready && !error) { try { log4.Info(string.Format("Processing Document. ObjectID:'{0}'", objectID)); string mailRecipient = null; string docSafeRecipient = null; #region Checkout all documents needed during processing. //Try to checkout document. try { WCFHandler.GetInstance.CheckOutDocument(this.objectID); } catch (Exception e) { throw new Exception(string.Format("Document could not be checked out. Msg:'{0}'", e.Message)); } if (Properties.Settings.Default.GroupingInheritMarkerProperties) { try { foreach (DocumentContract childDoc in childDocuments) { try { WCFHandler.GetInstance.CheckOutDocument(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("Child-Document could not be checked out. Msg:'{0}'", e.Message)); } } #endregion #region Send E-Mail if (Properties.Settings.Default.SendMailActive) { string attachmentDirectory = ""; try { DateTime startOfDownload = DateTime.Now; if (Properties.Settings.Default.AttachDocument) { //Create temp-directory. string tempDirectory = Path.Combine(Path.GetTempPath(), Convert.ToString(Guid.NewGuid())); Directory.CreateDirectory(tempDirectory); //Prepare list of all documents to send. List <DocumentContract> documentsToSend = new List <DocumentContract>(); if (!Properties.Settings.Default.GroupingActive) { documentsToSend.Add(this.document); } else { documentsToSend.AddRange(childDocuments); if (Properties.Settings.Default.GroupingAddParent) { documentsToSend.Add(this.document); } } foreach (DocumentContract doc in documentsToSend) { byte[] docBytes = WCFHandler.GetInstance.GetDocumentFile(this.objectID); string fileName = Properties.Settings.Default.AttachmentRenameProperty; if (fileName != "") { fileName = ExpressionsEvaluator.GetInstance.Evaluate(fileName, doc); if (fileName == "") { fileName = doc.Name; } else { string fileExtension = Path.GetExtension(doc.Name); fileName = fileName + fileExtension; } } else { fileName = doc.Name; } fileName = FileHelper.CleanUpFileName(fileName); string path = Path.Combine(tempDirectory, fileName); path = FileHelper.GetUniqueFilePath(path); System.IO.File.WriteAllBytes(path, docBytes); } DateTime endOfDownload = DateTime.Now; log4.Debug(string.Format("Downloading documents took {0}ms. ObjectID:'{1}'", (endOfDownload - startOfDownload).TotalMilliseconds.ToString(), this.objectID)); if (Properties.Settings.Default.GroupingZipped) { //Create directory withing tempDirectory. string dirName = new DirectoryInfo(@tempDirectory).Name; //Create name of ZipFile string zipName = ""; if (Properties.Settings.Default.GroupingZipName != "") { zipName = Properties.Settings.Default.GroupingZipName + ".zip"; } else { zipName = "Documents.zip"; } //Create ZipFilePath string zipTempDirectory = Path.Combine(Path.GetTempPath(), Convert.ToString(Guid.NewGuid())); Directory.CreateDirectory(zipTempDirectory); string zipFilePath = Path.Combine(zipTempDirectory, zipName); //Create Zip-File. ZipFile.CreateFromDirectory(tempDirectory, zipFilePath); //Delete old Tempdirectory Directory.Delete(tempDirectory, true); //Set new tempdirectory where ZIP file is. tempDirectory = zipTempDirectory; DateTime endOfZipping = DateTime.Now; log4.Debug(string.Format("Zipping took {0}ms. ObjectID:'{1}'", (endOfZipping - endOfDownload).TotalMilliseconds.ToString(), this.objectID)); } attachmentDirectory = tempDirectory; } try { using (Task <string> AsyncTaskSendMail = MailHandler.GetInstance.SendDocumentMail(this.document, attachmentDirectory)) { mailRecipient = AsyncTaskSendMail.Result; } } catch (Exception e) { throw new Exception(string.Format(e.InnerException.Message)); } if (attachmentDirectory != "") { Directory.Delete(attachmentDirectory, true); } #region OldStuff ////If no grouping is active. //if (!Properties.Settings.Default.GroupingActive) //{ // document = WCFHandler.GetInstance.GetDocumentFile(this.objectID); // string fileName = Properties.Settings.Default.AttachmentRenameProperty; // if (fileName != "") // { // fileName = NEWExpressionsEvaluator.GetInstance.Evaluate(fileName, this.document); // if (fileName == "") // fileName = this.document.Name; // else // { // string fileExtension = Path.GetExtension(this.document.Name); // fileName = fileName + fileExtension; // } // } // else // fileName = this.document.Name; // fileName = FileHelper.CleanUpFileName(fileName); // //docinfo.fileName = fileName; //} ////If Grouping is active. //else //{ //} //11.02.2016 AEPH: Get UserList //if (lUsers == null) // lUsers = getAllUsers(); //using (Task<bool> AsyncTaskSendMail = MailHandler.GetInstance.SendDocumentMail(document, docinfo, row, lUsers, attachmentDirectory)) //{ // processed = AsyncTaskSendMail.Result; //} // using (Task<bool> AsyncTaskSendMail = MailHandler.GetInstance.SendDocumentMail(this.document, attachmentDirectory)) // { // bool processed = AsyncTaskSendMail.Result; // if (!processed) // throw new Exception(string.Format("Document E-Mail could not be sent.")); // } // //MailHandler.GetInstance.SendDocumentMail(this.document, attachmentDirectory); // if (attachmentDirectory != "") // Directory.Delete(attachmentDirectory, true); // } #endregion } catch (Exception e) { throw new Exception(string.Format("Document E-Mail could not be sent. Msg:'{0}'", e.Message)); } } #endregion #region Send to DocSafe if (Properties.Settings.Default.DocSafeActive) { try { DocSafe.DocSafeHandler dsHandler = new DocSafe.DocSafeHandler(); byte[] document = null; //document = WebService.GetDocumentFile(sSessionGuid, Properties.Settings.Default.Culture, Properties.Settings.Default.Culture, docGuid, null, null, KXWS.AccessTypesEnum.ContentExport, out docinfo); document = WCFHandler.GetInstance.GetDocumentFile(this.objectID); docSafeRecipient = dsHandler.SendDocumentToDocsafe(document, this.document); } catch (Exception e) { throw new Exception("Document E-Mail could not be sent."); } } #endregion #region Start Process if (Properties.Settings.Default.StartProcessActive) { try { WCFHandler.GetInstance.StartProcess(this.procTemplate, this.objectID, this.procUserIDS); } catch (Exception e) { throw new Exception(string.Format("Process could not be started. Msg{0}", e.Message)); } } #endregion #region Set Markerproperties try { 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, false, true); } } DateTime end = DateTime.Now; log4.Debug(string.Format("Evaulation of markerproperties for document took {0}ms. ObjectID:'{1}'", (end - start).TotalMilliseconds.ToString(), this.objectID)); start = DateTime.Now; //Merge propertyupdates into all affected documents foreach (DocumentContract doc in allAffectedDocuments) { MergeMarkerPropertiesToDocument(doc); } end = DateTime.Now; log4.Debug(string.Format("Merging of markerproperties for document took {0}ms. ObjectID:'{1}'", (end - start).TotalMilliseconds.ToString(), this.objectID)); start = DateTime.Now; foreach (DocumentContract doc in allAffectedDocuments) { WCFHandler.GetInstance.UpdateDocument(doc); } end = DateTime.Now; log4.Debug(string.Format("Documentupdates 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 set! Msg:'{0}'", e.Message)); } #endregion string message = string.Format("Document processed sucessfully. ObjectID:'{0}' {1} {2}", this.objectID, mailRecipient != null ? "E-Mail Recipient: '" + mailRecipient + "'" : "", docSafeRecipient != null ? "DocSafe Recipient: '" + docSafeRecipient + "'" : ""); log4.Info(message); info = message; finished = true; } //If an error happens during processing. catch (Exception e) { string message = string.Format("An error happened during documentprocessing! ObjectID:'{0}', Msg:'{1}'", this.objectID, e.Message); log4.Error(message); info = message; error = true; } //Documents are always checked back in in when finished. finally { try { foreach (DocumentContract doc in allAffectedDocuments) { WCFHandler.GetInstance.UndoCheckOutDocument(doc.Id); } } catch { } } } }
public string Evaluate(string input, DocumentContract doc = null, bool testmode = false, bool isForSearchOrUpdate = false) { var start = DateTime.Now; Hashtable hTenteredIDX = new Hashtable(); string returnvalue = ""; Expression e = new Expression(input); e.Parameters["TodayDate"] = DateTime.Now.Date; e.Parameters["TodayTime"] = DateTime.Now; int year = DateTime.Now.Year; e.Parameters["EndYear"] = new DateTime(year, 12, 31); foreach (KeyValuePair <string, string> kvp in variables) { e.Parameters[kvp.Key] = new Expression(kvp.Value); } e.EvaluateFunction += delegate(string name, FunctionArgs args) { if (name == "AddDays") { var date1 = args.Parameters[0].Evaluate(); var days = args.Parameters[1].Evaluate(); //Check if days are a TimeSpan if (days.GetType() == typeof(TimeSpan)) { args.Result = ((DateTime)date1).Add((TimeSpan)days); } //Check if are a string. else if (days.GetType() == typeof(string)) { args.Result = ((DateTime)date1).AddDays(0); } //Else they are a double. (Use AddDays) else { args.Result = ((DateTime)date1).AddDays(Convert.ToDouble(days)); } } if (name == "DateDiff") { var date1 = args.Parameters[0].Evaluate(); var date2 = args.Parameters[1].Evaluate(); //args.Result = ((DateTime)args.Parameters[0].Evaluate() - (DateTime)args.Parameters[1].Evaluate()).TotalDays; args.Result = (DateTime)date2 - (DateTime)date1; } if (name == "IDX") { string index = args.Parameters[0].Evaluate().ToString(); string idxvalue = ""; //Get IDX Value from DocumentContract if available. if (doc != null) { var propID = WCFHandler.GetInstance.GetPropertyTypeID(index); string[] values = doc.Properties.Where(x => x.PropertyTypeId == propID).Select(x => x.Values).FirstOrDefault(); if (values == null) { throw new Exception(string.Format("Document did not contain a value for '{0}'.", index)); } //if (values.Count() > 1) //{ idxvalue = values.First(); //} } if (testmode) { if (hTenteredIDX.ContainsKey(index)) { idxvalue = hTenteredIDX[index].ToString(); } else { FormInputDialog inputDialog = new FormInputDialog("IDX Value", "Set Value for '" + index.ToString() + "':", "OK"); if (inputDialog.ShowDialog(null) == DialogResult.OK) { //recipient = inputDialog.txtBxInput.Text; idxvalue = inputDialog.txtBxInput.Text; hTenteredIDX.Add(index.ToString(), idxvalue); inputDialog.Dispose(); } } } //Check if its a Date DateTime idxValueDate; string[] formats = { "dd.MM.yyyy", "dd.MM.yyyy HH:mm", "dd.MM.yyyy HH:mm:ss", "yyyy-MM-ddTHH:mm:ss" }; if (DateTime.TryParseExact(idxvalue, formats, new CultureInfo(Properties.Settings.Default.Culture), DateTimeStyles.None, out idxValueDate)) { //AEPH 03.01.2019: Convert DateTime to UNIX Timestamp as needed by WCFWebService args.Result = idxValueDate; return; } //Check if its a number int idxValueInt; if (int.TryParse(idxvalue, out idxValueInt) && idxValueInt != 0) { args.Result = idxValueInt; return; } //Check if its a Decimal decimal idxValueDecimal; if (decimal.TryParse(idxvalue.Replace(',', '.'), NumberStyles.Any, CultureInfo.InvariantCulture, out idxValueDecimal) && idxValueDecimal != 0) { args.Result = idxValueDecimal; return; } //Else, forward it as a string. args.Result = idxvalue; } if (name == "SQL") { string connection = ((NCalc.Domain.ValueExpression)(args.Parameters[0].ParsedExpression)).Value.ToString(); var selectstatement = args.Parameters[1].Evaluate(); SqlConnection sqlCon = (sqlConnections.Find(item => item.name == connection.ToString())).connection; if (sqlCon == null) { throw new System.ArgumentException(string.Format("SQL-Connection '{0}' not defined.", connection)); } if (sqlCon != null && sqlCon.State == ConnectionState.Closed) { sqlCon.Open(); } SqlCommand command = new SqlCommand(selectstatement.ToString()) { Connection = sqlCon }; //AEPH 03.02.2016 //If testmode is on, command is only tested on server, not executed. (noexec mode) //This is used to validate the markerproperties prior to output processing. if (testmode) { command.CommandType = CommandType.Text; command.CommandText = "SET NOEXEC ON;"; } using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { args.Result = (string)reader[0].ToString(); } } if (args.Result == null) { args.Result = ""; } } if (name == "RegEx") { var value = args.Parameters[0].Evaluate(); string expression = ((NCalc.Domain.ValueExpression)(args.Parameters[1].ParsedExpression)).Value.ToString(); Regex regex = new Regex(@expression); Match match = regex.Match(value.ToString()); args.Result = match.Success; } if (name == "RegExReplace") { var sInput = args.Parameters[0].Evaluate(); var sReplacement = args.Parameters[1].Evaluate(); string expression = ((NCalc.Domain.ValueExpression)(args.Parameters[2].ParsedExpression)).Value.ToString(); Regex regex = new Regex(@expression); args.Result = regex.Replace(sInput.ToString(), sReplacement.ToString()); } if (name == "SS") { var sInput = args.Parameters[0].Evaluate(); string arg1 = args.Parameters[1].Evaluate().ToString(); string arg2 = args.Parameters[2].Evaluate().ToString(); int iStartIndex; int.TryParse(arg1, out iStartIndex); int iEndIndex; int.TryParse(arg2, out iEndIndex); string output = sInput.ToString(); args.Result = output.Substring(iStartIndex, iEndIndex); } }; if (e.HasErrors()) { throw new Exception(e.Error); } else { try { var output = e.Evaluate().ToString(); //AEPH 05.02.2016 //Decimal sign is used based on system settings. //AEPH 03.01.2019 //Convert Date or DateTime Values to correct format for new WCF-WebServices. //yyyy-MM-ddTHH:mm:ss for DateTime. //yyyy-MM-dd for dates. if (isForSearchOrUpdate) { DateTime idxValueDate; string[] formats = { "dd.MM.yyyy", "dd.MM.yyyy HH:mm", "dd.MM.yyyy HH:mm:ss" }; IFormatProvider culture = CultureInfo.InvariantCulture; if (DateTime.TryParseExact(output, formats, culture, DateTimeStyles.None, out idxValueDate)) { //Check if its a Date or DateTime //Source: https://stackoverflow.com/questions/15893339/check-if-date-time-string-contains-time if (idxValueDate.TimeOfDay.TotalSeconds == 0) { output = idxValueDate.ToString("yyyy-MM-dd"); } else { output = idxValueDate.ToString("yyyy-MM-ddTHH:mm:ss"); } } } returnvalue = output; } catch (Exception ex) { throw new Exception(ex.Message); } } var end = DateTime.Now - start; log4.Debug(string.Format("Evaluation of expression took {0}ms. in:'{1}' out:'{2}'", end.TotalMilliseconds.ToString(), input, returnvalue)); return(returnvalue); }