//Generate the Terms collection (of Term) based on an xml document
		public static bool Save(XmlDocument xmlTemplateDoc, Template template, bool bValidate)
		{
            //Convert the xml into an xmldocument
            //XmlDocument xmlTemplateDoc = new XmlDocument();
            //xmlTemplateDoc.PreserveWhitespace = false;
            //xmlTemplateDoc.LoadXml(template.TemplateDef);

            //Convert the objects stored in memory to an xmldocument
            XmlDocument xmlDoc = new XmlDocument();
			XmlElement nodeDetailedDescriptions = xmlDoc.CreateElement(XMLNames._E_DetailedDescriptions);

			if (template.DetailedDescriptions != null)
				foreach (DetailedDescription detailedDescription in template.DetailedDescriptions)
				{
					XmlElement nodeDetailedDescription = xmlDoc.CreateElement(XMLNames._E_DetailedDescription);
					detailedDescription.Build(xmlDoc, nodeDetailedDescription, bValidate);
					nodeDetailedDescriptions.AppendChild(nodeDetailedDescription);
				}

            //Replace the impacted portion of the complete xml with this version from memory
            XmlNode importedNodeDetailedDescriptions = xmlTemplateDoc.ImportNode(nodeDetailedDescriptions, true);
			//Find the "DetailedDescriptions" child node
			XmlNode detailedDescriptionChildNode = xmlTemplateDoc.SelectSingleNode(Utility.XMLHelper.GetXPath(true, XMLNames._E_TemplateDef, XMLNames._E_DetailedDescriptions));
			if (detailedDescriptionChildNode != null)
				xmlTemplateDoc.DocumentElement.ReplaceChild(importedNodeDetailedDescriptions, detailedDescriptionChildNode);
			else
				xmlTemplateDoc.DocumentElement.AppendChild(importedNodeDetailedDescriptions);

			return true;
		}
        public static List<ITATDocument> Create(XmlDocument xmlTemplateDoc, Template template)
        {       
            XmlNodeList nodeDocuments = null;
            bool isNewDocStructure = isNewStructure(xmlTemplateDoc);


            if (isNewDocStructure)
            {
                nodeDocuments = xmlTemplateDoc.SelectNodes(Utility.XMLHelper.GetXPath(true, XMLNames._E_TemplateDef, XMLNames._E_Documents, XMLNames._E_Document));
            }
            else
            {
                nodeDocuments = xmlTemplateDoc.SelectNodes(Utility.XMLHelper.GetXPath(true, XMLNames._E_TemplateDef, XMLNames._E_Document));
            }


            if (nodeDocuments == null)
            {
                return new List<ITATDocument>();
            }

            List<ITATDocument> rtn = new List<ITATDocument>(nodeDocuments.Count);
            foreach (XmlNode nodeDocument in nodeDocuments)
            {
                ITATDocument document = new ITATDocument(xmlTemplateDoc, nodeDocument, template, isNewDocStructure);
                rtn.Add(document);               
                
            }

            return rtn;
        }
		public static bool Save(Template template, ref string sXml, bool bValidate)
		{
            //Convert the xml into an xmldocument
            XmlDocument xmlTemplateDoc = new XmlDocument();
			xmlTemplateDoc.PreserveWhitespace = false;
			xmlTemplateDoc.LoadXml(sXml);

            //Convert the objects stored in memory to an xmldocument
            XmlDocument xmlDoc = new XmlDocument();
			XmlElement rootComplexList = xmlDoc.CreateElement(XMLNames._E_ComplexLists);

			if (template.ComplexLists != null)
				foreach (ComplexList complexList in template.ComplexLists)
				{
					XmlElement elementComplexList = xmlDoc.CreateElement(XMLNames._E_ComplexList);
					complexList.Build(xmlDoc, elementComplexList, bValidate);
					rootComplexList.AppendChild(elementComplexList);
				}

            //Replace the impacted portion of the complete xml with this version from memory
            XmlNode importedRootComplexList = xmlTemplateDoc.ImportNode(rootComplexList, true);
			//Find the "Terms" child node
			XmlNode complexListsChildNode = xmlTemplateDoc.SelectSingleNode(Utility.XMLHelper.GetXPath(true, XMLNames._E_TemplateDef,XMLNames._E_ComplexLists));
			if (complexListsChildNode != null)
				xmlTemplateDoc.DocumentElement.ReplaceChild(importedRootComplexList, complexListsChildNode);
			else
				xmlTemplateDoc.DocumentElement.AppendChild(importedRootComplexList);

            //Store the entire xml back to the database
            sXml = xmlTemplateDoc.OuterXml;

			return true;
		}
Beispiel #4
0
		public static Term CreateTerm(TermType termType, bool systemTerm, bool IsManagedItem, Template template, bool isFilter)
		{
			switch (termType)
			{
				case TermType.Text:
                    return new TextTerm(systemTerm, template, isFilter);
				case TermType.Date:
                    return new DateTerm(systemTerm, template, isFilter);
				case TermType.Link:
                    return new LinkTerm(systemTerm, template, isFilter);
				case TermType.MSO:
                    return new MSOTerm(systemTerm, template, isFilter);
				case TermType.Renewal:
                    return new RenewalTerm(systemTerm, IsManagedItem, template, isFilter);
				case TermType.Facility:
                    return new FacilityTerm(systemTerm, template, isFilter);
				case TermType.PickList:
                    return new PickListTerm(systemTerm, template, isFilter);
				case TermType.ComplexList:
                    return new ComplexList(systemTerm, template, false, isFilter);
				case TermType.External:
				   throw new Exception("The CreateTerm method is not to be used when creating an external term.");
                case TermType.PlaceHolderAttachments:
                   throw new Exception("The CreateTerm method is not to be used when creating a PlaceHolderAttachments term.");
                case TermType.PlaceHolderComments:
                   throw new Exception("The CreateTerm method is not to be used when creating a PlaceHolderComments term.");
                default:
					throw new Exception(string.Format("Edit screen not implemented for TermType = {0}", termType));
			}
		}
        public static bool Save(Template template, ref string sXml, bool bValidate)
        {
            //Convert the xml into an xmldocument
            XmlDocument xmlTemplateDoc = new XmlDocument();
            xmlTemplateDoc.PreserveWhitespace = false;
            xmlTemplateDoc.LoadXml(sXml);

            //Convert the objects stored in memory to an xmldocument
            XmlDocument xmlDoc = new XmlDocument();
            XmlElement nodeUserDocumentPrinters = xmlDoc.CreateElement(XMLNames._E_UserDocumentPrinters);

            if (template.UserDocumentPrinters != null)
                foreach (Role userDocumentPrinter in template.UserDocumentPrinters)
                {
                    XmlElement nodeUserDocumentPrinter = xmlDoc.CreateElement(XMLNames._E_Role);
                    userDocumentPrinter.Build(xmlDoc, nodeUserDocumentPrinter, bValidate);
                    nodeUserDocumentPrinters.AppendChild(nodeUserDocumentPrinter);
                }

            //Replace the impacted portion of the complete xml with this version from memory
            XmlNode importedNodeUserDocumentPrinters = xmlTemplateDoc.ImportNode(nodeUserDocumentPrinters, true);
            //Find the "Comments" child node
            XmlNode userDocumentPrinterChildNode = xmlTemplateDoc.SelectSingleNode(Utility.XMLHelper.GetXPath(true, XMLNames._E_TemplateDef, XMLNames._E_UserDocumentPrinters));
            if (userDocumentPrinterChildNode != null)
                xmlTemplateDoc.DocumentElement.ReplaceChild(importedNodeUserDocumentPrinters, userDocumentPrinterChildNode);
            else
                xmlTemplateDoc.DocumentElement.AppendChild(importedNodeUserDocumentPrinters);

            //Store the entire xml back to the database
            sXml = xmlTemplateDoc.OuterXml;

            return true;
        }
		public TermDependencyCondition(Template template, string sourceTerm, string oper, string value1, string value2)
		{
			_template = template;
			_sourceTermID = _template.FindTerm(sourceTerm).ID;
			_oper = oper;
			_value1 = value1;
			_value2 = value2;
		}
        public DateTerm(XmlNode termNode, Template template, bool isFilter)
            : base(termNode, template, isFilter)
		{
			TermType = TermType.Date;
			NameRequired = true;

			_value = Utility.XMLHelper.GetValueDate(termNode);
			_format = Utility.XMLHelper.GetAttributeString(termNode, XMLNames._A_Format);
		}
 //Generate the Comments collection (of N) based on an existing Template
 public static List<Role> Create(string templateDef, Template template)
 {
     if (templateDef == null)
         return null;
     XmlDocument xmlTemplateDoc = new XmlDocument();
     xmlTemplateDoc.PreserveWhitespace = false;
     xmlTemplateDoc.LoadXml(templateDef);
     return Create(xmlTemplateDoc, template);
 }
		//Generate the Terms collection (of Term) based on an existing Template
        //2090429 - This will be called with a param for the XPath, depending...
        //This is called from ManagedItem.Create and from BasicTerms prop-get
		public static List<Term> Create(string templateDef, ManagedItem managedItem, Template template)
		{
			if (templateDef == null)
				return null;
            //Convert the xml into an xmldocument
            XmlDocument xmlTemplateDoc = new XmlDocument();
			xmlTemplateDoc.PreserveWhitespace = false;
			xmlTemplateDoc.LoadXml(templateDef);

            return Create(xmlTemplateDoc.SelectSingleNode(Utility.XMLHelper.GetXPath(true, XMLNames._E_TemplateDef, XMLNames._E_Terms)), managedItem, template);
		}
		public static Guid Copy(Template template, Guid copyFromID, string newName)
		{
			Workflow workflowFrom = template.FindWorkflow(copyFromID);
			if (workflowFrom == null)
				return Guid.Empty;

            Workflow workflowCopy = workflowFrom.Copy(newName, template is ManagedItem, template);
			workflowCopy.Name = newName;
			template.Workflows.Add(workflowCopy);
			return workflowCopy.ID;
		}
Beispiel #11
0
        public LinkTerm(XmlNode termNode, Template template, bool isFilter)
            : base(termNode, template, isFilter)
		{
			TermType = TermType.Link;
			NameRequired = true;

			_url = Utility.XMLHelper.GetAttributeString(termNode, XMLNames._A_URL);
			_caption = Utility.XMLHelper.GetAttributeString(termNode, XMLNames._A_Caption);
			_isManagedItemReference = Utility.XMLHelper.GetAttributeBool(termNode, XMLNames._A_IsManagedItemReference);
			_complexListID = Term.CreateID(termNode, XMLNames._A_ComplexListID);
			_linkSource = Utility.XMLHelper.GetAttributeString(termNode, XMLNames._A_LinkSource);
		}
		//Generate the Terms collection (of Term) based on an existing Template
		public static List<Workflow> Create(XmlDocument xmlTemplateDoc, Template template)
		{
			XmlNodeList nodeWorkflows = null;
			XmlNode nodeWorkflow = null;
			List<Workflow> rtn = new List<Workflow>();

			nodeWorkflows = xmlTemplateDoc.SelectNodes(Utility.XMLHelper.GetXPath(true, XMLNames._E_TemplateDef, XMLNames._E_Workflows, XMLNames._E_Workflow));
			if (nodeWorkflows.Count == 0)
			{
				nodeWorkflow = xmlTemplateDoc.SelectSingleNode(Utility.XMLHelper.GetXPath(true, XMLNames._E_TemplateDef, XMLNames._E_Workflow));
				if (nodeWorkflow == null)
				{
					//No Workflow defined
					throw new Exception(string.Format("No workflow defined for older structure template '{0}', ID = '{1}'", template.Name, template.ID.ToString()));
				}
				else
				{
					//This is the 'old' structure
                    Workflow workflow = new Workflow(nodeWorkflow, template is ManagedItem, template);
					template.ActiveWorkflowID = workflow.ID;
					Event revertToDraft = template.OldWorkflowRevertEvent;
					if (revertToDraft != null)
					{
						workflow.Events.Add(revertToDraft);
						template.OldWorkflowRevertEvent = null;
					}
					rtn.Add(workflow);
				}
			}
			else
			{
				//This is the 'new' structure - assume that RevertToDraft already set up properly.
				XmlNode singleNodeWorkflows = xmlTemplateDoc.SelectSingleNode(Utility.XMLHelper.GetXPath(true, XMLNames._E_TemplateDef, XMLNames._E_Workflows));
				foreach (XmlNode nodeEachWorkflow in nodeWorkflows)
				{
                    rtn.Add(new Workflow(nodeEachWorkflow, template is ManagedItem, template));
				}

				string sActiveWorkflowID = string.Empty; 
				//if (sActiveWorkflowID == null)
				//   throw new Exception("The Active Workflow ID is not defined");
				sActiveWorkflowID = Utility.XMLHelper.GetAttributeString(singleNodeWorkflows, XMLNames._A_ActiveWorkflowID);
				if (Utility.TextHelper.IsGuid(sActiveWorkflowID))
					template.ActiveWorkflowID = new Guid(sActiveWorkflowID);
				else
					if (rtn.Count > 0)
						template.ActiveWorkflowID = rtn[0].ID;
					else
						throw new Exception("Unable to set the Active Workflow because no workflows are defined for this template.");
			}

			return rtn;
		}
        public static bool Save(XmlDocument xmlTemplateDoc, Template template, bool bValidate)
        {

            //Convert the xml into an xmldocument
            bool bWriteToDatabase = false;
            if (xmlTemplateDoc == null)
            {
                xmlTemplateDoc = new XmlDocument();
                xmlTemplateDoc.PreserveWhitespace = false;
                xmlTemplateDoc.LoadXml(template.TemplateDef);
                bWriteToDatabase = true;
            }

            //Convert the objects stored in memory to an xmldocument
            XmlDocument xmlDoc = new XmlDocument();
            XmlElement rootITATDocuments = xmlDoc.CreateElement(XMLNames._E_Documents);


            if (template.Documents != null)
                foreach (ITATDocument document in template.Documents)
                {
                    XmlElement elementDocument = xmlDoc.CreateElement(XMLNames._E_Document);
                    document.Build(xmlTemplateDoc, xmlDoc, elementDocument, bValidate);
                    rootITATDocuments.AppendChild(elementDocument);

                }

            //Replace the impacted portion of the complete xml with this version from memory
            XmlNode importedRootITATDocument = xmlTemplateDoc.ImportNode(rootITATDocuments, true);
            //Find the "Terms" child node
            XmlNode documentsChildNode = xmlTemplateDoc.SelectSingleNode(Utility.XMLHelper.GetXPath(true, XMLNames._E_TemplateDef, XMLNames._E_Documents));
            XmlNode documentChildNode = xmlTemplateDoc.SelectSingleNode(Utility.XMLHelper.GetXPath(true, XMLNames._E_TemplateDef, XMLNames._E_Document));

            if (documentChildNode!=null)
            {
                xmlTemplateDoc.DocumentElement.RemoveChild(documentChildNode);
                xmlTemplateDoc.DocumentElement.AppendChild(importedRootITATDocument);
            }                
            else if (documentsChildNode != null)
                xmlTemplateDoc.DocumentElement.ReplaceChild(importedRootITATDocument, documentsChildNode);
            else 
                xmlTemplateDoc.DocumentElement.AppendChild(importedRootITATDocument);

            //Store the entire xml back to the database
            if (bWriteToDatabase)
                Template.UpdateTemplateDef(template, xmlTemplateDoc.OuterXml);



            return true;
        }
		public TermDependencyCondition(Template template, XmlNode conditionNode)
		{
			_template = template;
			string sourceTerm = Utility.XMLHelper.GetAttributeString(conditionNode, XMLNames._A_SourceTerm);
			if (!string.IsNullOrEmpty(sourceTerm))
			{
				_sourceTermID = _template.FindTerm(sourceTerm).ID;
			}
			else
			{
				_sourceTermID = Term.CreateID(conditionNode, XMLNames._A_SourceTermID);
			}
			_oper = Utility.XMLHelper.GetAttributeString(conditionNode, XMLNames._A_Oper);
			_value1 = Utility.XMLHelper.GetAttributeString(conditionNode, XMLNames._A_Value1);
			_value2 = Utility.XMLHelper.GetAttributeString(conditionNode, XMLNames._A_Value2);
		}
 public ExternalTerm(bool systemTerm, Business.ExternalInterfaceConfig eic, ManagedItem managedItem, Template template, bool isFilter)
     : base(systemTerm, template, isFilter)
 {
     TermType = TermType.External;
     NameRequired = true;
     Name = eic.Name;
     _interfaceConfig = eic;
     //NOTE - This operation is valid only the FIRST time this is set...
     if (TermTransforms == null && _interfaceConfig.TransformTermType.HasValue)
     {
         TransformTermType = _interfaceConfig.TransformTermType;
         TermTransforms = _interfaceConfig.TermTransforms;
     }
     _managedItem = managedItem;
     _valuesLoaded = false;
     _value = null;
 }
		//Generate the Terms collection (of Term) based on an existing Template
		public static List<Term> Create(XmlDocument xmlTemplateDoc, Template template)
		{
			XmlNodeList nodeComplexLists = xmlTemplateDoc.SelectNodes(Utility.XMLHelper.GetXPath(true, XMLNames._E_TemplateDef, XMLNames._E_ComplexLists, XMLNames._E_ComplexList));
			if (nodeComplexLists == null)
			{
				return new List<Term>();
			}

			List<Term> rtn = new List<Term>(nodeComplexLists.Count);
			foreach (XmlNode nodeComplexList in nodeComplexLists)
			{
                ComplexList complexList = new ComplexList(nodeComplexList, template, false);
				rtn.Add(complexList);
			}

			return rtn;
		}
        //Generate the Comments collection (of N) based on an existing Template
        public static List<Role> Create(XmlDocument xmlTemplateDoc, Template template)
        {
            List<Role> userDocumentPrinters = new List<Role>();

            XmlNode nodeUserDocumentPrinters = xmlTemplateDoc.SelectSingleNode(Utility.XMLHelper.GetXPath(true, XMLNames._E_TemplateDef, XMLNames._E_UserDocumentPrinters));
            if (nodeUserDocumentPrinters == null)
            {
                ITATSystem system = ITATSystem.Get(template.SystemID);
                userDocumentPrinters = new List<Role>(system.Roles);
            }
            else
            {
                XmlNodeList nodeUserDocumentPrintersList = xmlTemplateDoc.SelectNodes(Utility.XMLHelper.GetXPath(true, XMLNames._E_TemplateDef, XMLNames._E_UserDocumentPrinters, XMLNames._E_Role));
                foreach (XmlNode nodeUserDocumentPrinter in nodeUserDocumentPrintersList)
                {
                    Role userDocumentPrinter = new Role(nodeUserDocumentPrinter);
                    userDocumentPrinters.Add(userDocumentPrinter);
                }
            }
            return userDocumentPrinters;
        }
        private List<Business.Template> GetSystemTemplates(Guid gSystemID)
        {
            Dictionary<string, Business.Template> dictTemplates = new Dictionary<string, Business.Template>();

            using (DataSet dsTemplates = Data.Template.GetRetroTemplateList(gSystemID))
            {
                foreach (DataRow drTemplate in dsTemplates.Tables[0].Rows)
                {
                    Guid templateID = (Guid)drTemplate[Data.DataNames._C_TemplateID];
                    Business.Template template = new Business.Template(templateID, Business.DefType.Final);
                    if (template.RetroModel != Business.Retro.RetroModel.Off)
                    {
                        //Determine how many ManagedItems would require retro applied 
                        int managedItemCount = GetManagedItems(templateID, template.RetroDate).Count;
                        if (managedItemCount > 0)
                        {
                            string templateKey = string.Format("{0:D10}|{1}", managedItemCount, templateID.ToString());
                            dictTemplates.Add(templateKey, template);
                        }
                    }
                }
            }
            //Sort the templates according to number of ManagedItems, in decreasing order.
            List<KeyValuePair<string, Business.Template>> dictTemplatesSorted = new List<KeyValuePair<string, Business.Template>>(dictTemplates);
            dictTemplatesSorted.Sort(
                  delegate(KeyValuePair<string, Business.Template> firstPair, KeyValuePair<string, Business.Template> secondPair)
                  {
                      return secondPair.Key.CompareTo(firstPair.Key);
                  }
            );

            //Create a list for returning to the caller
            List<Business.Template> templates = new List<Business.Template>(dictTemplatesSorted.Count);
            foreach (KeyValuePair<string, Business.Template> kvp in dictTemplatesSorted)
            {
                templates.Add(kvp.Value);
            }
            return templates;
        }
Beispiel #19
0
		public static List<string> ReplaceEmbeddedTermNames(Template template, List<Event> notifications)
		{
			List<string> sErrors = new List<string>();
			foreach (Event notification in notifications)
			{
				if (!Term.ValidID(notification.BaseDateTermID))
					if (!string.IsNullOrEmpty((notification as Event).BaseDateTermName))
					{
						try
						{
							(notification as Event).BaseDateTermID = template.FindTerm((notification as Event).BaseDateTermName).ID;
						}
						catch (Exception)
						{
							sErrors.Add(string.Format("Unable to find Event term '{0}'", (notification as Event).BaseDateTermName));
						}
					}

				if (!Term.ValidID(notification.OffsetTermID))
					if (!string.IsNullOrEmpty((notification as Event).OffsetTermName))
					{
						try
						{
							(notification as Event).OffsetTermID = template.FindTerm((notification as Event).OffsetTermName).ID;
						}
						catch (Exception)
						{
							sErrors.Add(string.Format("Unable to find Event term '{0}'", (notification as Event).BaseDateTermName));
						}
					}

				foreach (Message message in notification.Messages)
				{
					message.Text = Term.SubstituteTermNames(template, message.Text);
				}
			}
			return sErrors;
		}
        public PlaceHolderTerm(XmlNode termNode, Template template, bool isFilter)
            : base(termNode, template, isFilter)
		{
            NameRequired = true;
        }
        public PlaceHolderTerm(bool systemTerm, Template template, bool isFilter)
            : base(systemTerm, template, isFilter)
		{
			NameRequired = true;
            _template = template;
        }
 /// <summary>
 /// Creates a new instance of a ManagedItem using the specified template where the system uses the OwningFacility concept
 /// </summary>
 /// <param name="template">The template that this ManagedItem is based on</param>
 /// <param name="facilityIds">One or more facilities that this ManagedItem is associated with</param>
 public static ManagedItem CreateRetro(Template template, bool useAlternateTemplate, Guid sourceManagedItemID, bool hasOwningFacility, Utility.DocumentStorageType documentStorageType, out bool returnToDraft)
 {
     ManagedItem sourceManagedItem = Business.ManagedItem.Get(sourceManagedItemID, true);
     ManagedItem newManagedItem = new ManagedItem(template.ID, sourceManagedItem.ManagedItemID);
     newManagedItem.RetroCopy(template, useAlternateTemplate);
     returnToDraft = newManagedItem.Migrate(sourceManagedItem);
     if (returnToDraft)
     {
         //Changed for Multiple Documents
         foreach (ITATDocument doc in sourceManagedItem.Documents)
         {
             if (!string.IsNullOrEmpty(doc.GeneratedDocumentID))
             {
                 RemoveGeneratedDocument(sourceManagedItem, doc.GeneratedDocumentID, documentStorageType);
                 newManagedItem.GetITATDocument(doc.ITATDocumentID).GeneratedDocumentID = null;
             }
         }
     }
     return newManagedItem;
 }
Beispiel #23
0
        public LinkTerm(bool systemTerm, Template template, bool isFilter)
            : base(systemTerm, template, isFilter)
		{
			TermType = TermType.Link;
			NameRequired = true;
		}
        public void Rollback(Guid managedItemAuditId, string sEnvironment, bool? orphanTheItem)
        {
			bool retroRollback;
            Retro.RetroData retroData = GetRetroData(_itemNumber, _managedItemID, managedItemAuditId);
			if (retroData.TemplateRetroDate.HasValue && retroData.AuditDate < retroData.TemplateRetroDate.Value)
            {
                //May require retro
                switch (RetroModel)
                {
                    case Retro.RetroModel.Off:
                        retroRollback = false;
                        break;

                    case Retro.RetroModel.OnWithEditLanguage:
                        if (_isOrphaned)
                        {
                            retroRollback = false;
                        }
                        else
                        {
                            if (!orphanTheItem.HasValue)
                                throw new Exception(string.Format("The 'orphan' value was required but not supplied for the rollback of ManagedItem '{0}'", ManagedItemID.ToString()));
                            retroRollback = !(orphanTheItem.Value);
                            _isOrphaned = orphanTheItem.Value;
                            if (_isOrphaned)
                            {
								retroData.AuditType = Retro.AuditType.Orphaned;
                                ILog log = LogManager.GetLogger(this.GetType());
                                log.Debug(string.Format("ManagedItem {0} ({1}) (System {2}) Orphaned due to Rollback", ItemNumber, ManagedItemID.ToString(), SystemID.ToString()));
                            }
                        }
                        break;

                    case Retro.RetroModel.OnWithoutEditLanguage:
                        retroRollback = true;
                        break;

                    default:
                        throw new Exception(string.Format("RetroModel case '{0}' not handled for ManagedItem '{1}'", RetroModel.ToString(),ManagedItemID.ToString()));
                }
            }
            else
                retroRollback = false;

            ITATSystem itatSystem = null;
            Business.ManagedItem newManagedItem = null;
            if (retroRollback)
            {
                Template currentTemplate = new Template(TemplateID, Business.DefType.Final);
                itatSystem = ITATSystem.Get(SystemID);
                bool returnToDraft;
                newManagedItem = Business.ManagedItem.CreateRetro(currentTemplate, false, ManagedItemID, itatSystem.HasOwningFacility.Value, itatSystem.DocumentStorageType, out returnToDraft);
                newManagedItem.Update(false, retroData.AuditType);    //Update also calls UpdateManagedItemStateRole
                if (returnToDraft)
                {
                    //No action required here as of last spec update
                }
                newManagedItem.UpdateScheduledEvents(ScheduledEvent.ExecutedCalculationType.UseGracePeriod);
            }
            else
            {
                newManagedItem = new ManagedItem(TemplateID, ManagedItemID, ItemNumber, IsOrphaned, retroData.StateID, retroData.TemplateDef);
                //Ensure that the database is updated with the older External term values
                foreach (Term t in newManagedItem.BasicTerms)
                    if (t.TermType == TermType.External)
                    {
                        (t as ExternalTerm).SaveValues(false);
                    }
				newManagedItem.Update(false, retroData.AuditType);    //Update also calls UpdateManagedItemStateRole
            }
            
           
            //Changed for Multiple Documents
            foreach (ITATDocument doc in Documents)
            {
                if (!string.IsNullOrEmpty(doc.GeneratedDocumentID) && newManagedItem.GetITATDocument(doc.ITATDocumentID).GeneratedDocumentID != doc.GeneratedDocumentID)
                {
                    if (itatSystem == null)
                        itatSystem = ITATSystem.Get(SystemID);
                    //Changed for Multiple Documents
                    RemoveGeneratedDocument(newManagedItem, doc.GeneratedDocumentID, itatSystem.DocumentStorageType);
                }

            }



        }
        public static ManagedItemStore CreateStore(
            ILog log, 
            Template template, 
            string managedItem, 
            Guid managedItemID, 
            string managedItemNumber, 
            string status, 
            string state, 
            Dictionary<string /* Term Name */, Term> templateTerms,
            List<string> basicTermsToProcess,
            List<string> complexListTermsToProcess)
        {
            ManagedItemStore managedItemStore = new ManagedItemStore(template.ID, template.Name, managedItemNumber, status, state);
            bool basicTermsProcessed = false;
            bool complexListsProcessed = false;
            bool workflowsProcessed = false;
            int basicTermsToProcessCount = basicTermsToProcess.Count;
            int complexListTermsToProcessCount = complexListTermsToProcess.Count;

            XmlTextReader txtReader = new XmlTextReader(new MemoryStream(Encoding.UTF8.GetBytes(managedItem)));
            XmlReaderSettings readerSettings = new XmlReaderSettings();
            readerSettings.IgnoreWhitespace = true;
            readerSettings.IgnoreComments = true;
            readerSettings.IgnoreProcessingInstructions = true;

            using (XmlReader reader = XmlReader.Create(txtReader, readerSettings))
            {
                reader.MoveToContent();     //Reader initialized and positioned at the 'TemplateDef' node.

                while (!(basicTermsProcessed && complexListsProcessed && workflowsProcessed))
                {
                    if (!reader.Read())     //At start element of a TemplateDef child node.
                    {
                        throw new Exception(string.Format("CreateStore call stopped unexpectedly on failed reader.Read call for ManagedItemNumber '{0}', ManagedItemID '{1}'", managedItemNumber, managedItemID.ToString()));
                    }

                    //Ensure completion before quitting...
                    if (reader.NodeType == XmlNodeType.EndElement && reader.Name == XMLNames._E_TemplateDef)
                    {
                        string error = string.Empty;
                        if (basicTermsToProcessCount > 0 && !basicTermsProcessed)
                            error += "Basic Terms were not processed.  ";
                        if (complexListTermsToProcessCount > 0 && !complexListsProcessed)
                            error += "Complex Lists were not processed.  ";
                        if (!workflowsProcessed)
                            error += "WorkFlows were not processed.  ";
                        if (!string.IsNullOrEmpty(error))
                            throw new Exception(string.Format("CreateStore call at end element before processing completed for ManagedItemNumber '{0}', ManagedItemID '{1}'.  {2}", managedItemNumber, managedItemID.ToString(), error));
                        break;
                    }

                    switch (reader.Name)
                    {
                        case XMLNames._E_Workflows:
                            Guid activeWorkflowID = new Guid(reader.GetAttribute(XMLNames._A_ActiveWorkflowID));
                            //NOTE - The search for active workflow may fail if the template information does not match the manageditem's information.
                            Workflow activeWorkflow = template.FindWorkflow(activeWorkflowID);
                            if (activeWorkflow != null)
                                managedItemStore.ActiveWorkflow = activeWorkflow.Name;
                            else
                                managedItemStore.ActiveWorkflow = string.Empty;
                            using (reader.ReadSubtree()) { }
                            workflowsProcessed = true;
                            break;

                        case XMLNames._E_Terms:
                            if (basicTermsToProcess.Count > 0)
                            {
                                ReadTermStore(
                                    template.Name,
                                    managedItemID,
                                    reader.ReadSubtree(),
                                    managedItemStore,
                                    templateTerms,
                                    basicTermsToProcess);
                            }
                            else
                            {
                                using (reader.ReadSubtree()) { }
                            }
                            basicTermsProcessed = true;
                            break;

                        case XMLNames._E_ComplexLists:
                            if (complexListTermsToProcess.Count > 0)
                            {
                                ReadComplexListStore(
                                    reader.ReadSubtree(),
                                    managedItemStore,
                                    templateTerms,
                                    complexListTermsToProcess);
                            }
                            else
                            {
                                using (reader.ReadSubtree()) { }
                            }
                            complexListsProcessed = true;
                            break;

                        case XMLNames._E_Events:
                        case XMLNames._E_Document:
                        case XMLNames._E_Comments:
                        case XMLNames._E_TermDependencies:
                        case XMLNames._E_DetailedDescriptions:
                        case XMLNames._E_TermGroups:
                        case XMLNames._E_DocumentPrinters:
                        default:
                            using (reader.ReadSubtree()) { }
                            break;
                    }

                }
            }

            return managedItemStore;
        }
		public static ScheduledEvent Find(Template template, Guid scheduledEventID)
		{
			if (template == null)
				return null;

			ScheduledEvent scheduledEvent = null;

			foreach (Event eachEvent in template.Events)
			{
				scheduledEvent = Find(eachEvent.ScheduledEvents, scheduledEventID);
				if (scheduledEvent != null)
					return scheduledEvent;
			}

			foreach (Event eachEvent in template.Workflow.Events)
			{
				scheduledEvent = Find(eachEvent.ScheduledEvents, scheduledEventID);
				if (scheduledEvent != null)
					return scheduledEvent;
			}

			RenewalTerm renewalTerm = template.FindBasicTerm(TermType.Renewal) as RenewalTerm;
			if (renewalTerm != null)
				return Find(renewalTerm.RenewalEvent.ScheduledEvents, scheduledEventID);

			return null;
		}
Beispiel #27
0
		internal List<string> TermReferences(Template template, string termName, string sClient)
		{
			return Term.TermReferences(template, termName, System.Web.HttpUtility.HtmlDecode(Text), sClient, "notification");
		}
        public List<string> ProcessSystem(Guid gSystemID, string systemName, ref int batchTemplateDraftCount, ref int batchTemplateFinalCount, ref int batchManagedItemCount)
        {
            batchTemplateDraftCount = 0;
            batchTemplateFinalCount = 0;
            batchManagedItemCount = 0;
            Stopwatch stopWatchTemplate = new Stopwatch();
            Stopwatch stopWatchManagedItem = new Stopwatch();
            ILog log = Kindred.Common.Logging.LogManager.GetLogger(this.GetType());
            List<string> badDraftTemplateDefGuids = new List<string>();
            using (DataSet dsTemplates = Business.Template.GetTemplateList(gSystemID, null))
            {
                log.Info(string.Format("Processing {0:D} Templates", dsTemplates.Tables[0].Rows.Count));
                foreach (DataRow drTemplate in dsTemplates.Tables[0].Rows)
                {
                    Guid templateID = (Guid)drTemplate[Data.DataNames._C_TemplateID];

                    if (Business.Template.DraftTemplateDefValid(templateID))
                    {
                        batchTemplateDraftCount++;
                        string templateName = "UNDEFINED";
                        stopWatchTemplate.Start();
                        try
                        {
                            Business.Template template = new Business.Template(templateID, Business.DefType.Draft);
                            //Ensure that the SecurityModel is loaded.
                            Business.SecurityModel securityModel = template.SecurityModel;
                            //Ensure that the Terms, ComplexLists, Workflows are updated.
                            int nBasicTermsCount = template.BasicTerms.Count;
                            int nComplexListsCount = template.ComplexLists.Count;
                            int nWorkflowsCount = template.Workflows.Count;
                            templateName = template.Name;
                            template.SaveLoaded(false, true, null);
                            log.Info(string.Format("Processed Template '{0}'", templateName));
                        }
                        catch (Exception ex)
                        {
                            log.Error(string.Format("Failed to process DraftTemplateDef for System '{0}', Template '{1}' - Error Message = '{2}'", systemName, templateName, ex.Message), ex);
                        }
                        stopWatchTemplate.Stop();

                        if (Business.Template.FinalTemplateDefValid(templateID))
                        {
                            batchTemplateFinalCount++;
                            stopWatchTemplate.Start();
                            try
                            {
                                Business.Template template = new Business.Template(templateID, Business.DefType.Final);
                                //Ensure that the Terms, ComplexLists, Workflows are updated.
                                int nBasicTermsCount = template.BasicTerms.Count;
                                int nComplexListsCount = template.ComplexLists.Count;
                                int nWorkflowsCount = template.Workflows.Count;
                                template.SaveLoaded(false, true, null);
                                Data.Template.UpdateTemplateBaseStateRole(template.ID, Utility.ListHelper.EliminateDuplicates(template.Workflow.FindBaseState().EditorRoleNames));
                            }
                            catch (Exception ex)
                            {
                                log.Error(string.Format("Failed to process FinalTemplateDef for System '{0}', Template '{1}' - Error Message = '{2}'", systemName, templateName, ex.Message), ex);
                            }
                            stopWatchTemplate.Stop();

                            List<Guid> managedItemIDs = GetManagedItems(gSystemID, templateID);
                            if (managedItemIDs.Count > 0)
                            {
                                log.Info(string.Format("Processing {0:D} ManagedItems", managedItemIDs.Count));
                                int templateManagedItemCount = 0;
                                int nLog = 200;
                                foreach (Guid managedItemID in managedItemIDs)
                                {
                                    batchManagedItemCount++;
                                    templateManagedItemCount++;

                                    stopWatchManagedItem.Start();
                                    try
                                    {
                                        Business.ManagedItem managedItem = Business.ManagedItem.Get(managedItemID, true);
                                        //Ensure that the Terms, ComplexLists, Workflows are updated.
                                        int nBasicTermsCount = managedItem.BasicTerms.Count;
                                        int nComplexListsCount = managedItem.ComplexLists.Count;
                                        int nWorkflowsCount = managedItem.Workflows.Count;
										managedItem.Update(false, Kindred.Knect.ITAT.Business.Retro.AuditType.Saved);   //Update also calls UpdateManagedItemStateRole
										managedItem.UpdateScheduledEvents(Business.ScheduledEvent.ExecutedCalculationType.UseGracePeriod);
                                        if (templateManagedItemCount % nLog == 0)
                                            log.Info(string.Format("Processed {0:D} ManagedItems", templateManagedItemCount));
                                    }
                                    catch (Exception ex)
                                    {
                                        log.Error(string.Format("Failed to process ManagedItem '{0}' for System '{1}', Template '{2}' - Error Message = '{3}'", managedItemID.ToString(), systemName, templateName, ex.Message), ex);
                                    }
                                    stopWatchManagedItem.Stop();
                                }
                                log.Info(string.Format("Processed a total of {0:D} ManagedItems", templateManagedItemCount));
                            }
                        }
                        else
                            log.Debug(string.Format("FinalTemplateDef invalid for System '{0}', Template '{1}'", systemName, templateName));
                    }
                    else
                    {
                        badDraftTemplateDefGuids.Add(templateID.ToString());
                        if (Business.Template.FinalTemplateDefValid(templateID))
                        {
                            log.Error(string.Format("For System '{0}', TemplateID '{1}' - DraftTemplateDef invalid BUT FinalTemplateDef valid!", systemName, templateID.ToString()));
                        }
                    }
                }
            }
            if (badDraftTemplateDefGuids.Count > 0)
                log.Error(string.Format("DraftTemplateDef invalid for the following {0:D} templates: '{1}'", badDraftTemplateDefGuids.Count, string.Join(",", badDraftTemplateDefGuids.ToArray())));
            log.Debug(string.Format("System {0} - Total Template elapsed time = {1};  Average Template elapsed time = {2} sec", systemName, stopWatchTemplate.Elapsed, stopWatchTemplate.Elapsed.TotalSeconds / (batchTemplateDraftCount + batchTemplateFinalCount)));
            if (batchManagedItemCount > 0)
                log.Debug(string.Format("System {0} - Total ManagedItem elapsed time = {1};  Average ManagedItem elapsed time = {2} sec", systemName, stopWatchManagedItem.Elapsed, stopWatchManagedItem.Elapsed.TotalSeconds / batchManagedItemCount));
            else
                log.Debug(string.Format("System {0} - Total ManagedItem elapsed time = 0;  Average ManagedItem elapsed time = 0 sec", systemName));
            return null;
        }
		//Generate the Terms collection (of Term) based on an existing Template
        //Called by ManagedItem.GetBasic and by ManagedItem.Get
        public static List<Term> Create(XmlDocument xmlTemplateDoc, ManagedItem managedItem, Template template)
		{
            return Create(xmlTemplateDoc.SelectSingleNode(Utility.XMLHelper.GetXPath(true, XMLNames._E_TemplateDef, XMLNames._E_Terms)), managedItem, template);
		}
		//Generate the Terms collection (of Term) based on an xml document
        //Called by BasicTerms.Create, once from ITATSystem.LoadFromDatabase
 		public static List<Term> Create(XmlNode termsNode, ManagedItem managedItem, Template template)
		{
			List<Term> rtn = new List<Term>(termsNode.ChildNodes.Count);
            int order = 0;
			foreach (XmlNode termNode in termsNode)
			{
				Term t = null;
				switch (termNode.Name.ToString())
				{
					case XMLNames._E_Text:
                        t = new TextTerm(termNode, template, false);
						break;
					case XMLNames._E_Date:
                        t = new DateTerm(termNode, template, false);
						break;
					case XMLNames._E_MSO:
                        t = new MSOTerm(termNode, template, false);
						break;
					case XMLNames._E_Link:
                        t = new LinkTerm(termNode, template, false);
						break;
					case XMLNames._E_Facility:
                        t = new FacilityTerm(termNode, template, false);
						break;
					case XMLNames._E_Renewal:
                        t = new RenewalTerm(termNode, managedItem != null, template, false);
						break;
					case XMLNames._E_PickList:
                        t = new PickListTerm(termNode, template, false);
						break;
					case XMLNames._E_External:
                        t = new ExternalTerm(termNode, managedItem, template, false);
						break;
                    case XMLNames._E_PlaceHolderAttachments:
                        t = new PlaceHolderAttachments(termNode, template, false);
                        break;
                    case XMLNames._E_PlaceHolderComments:
                        t = new PlaceHolderComments(termNode, template, false);
                        break;
                    default:
						throw new XmlException(string.Format("Tried to create undefined term type {0}", termNode.Name.ToString()));
				}
                t.Order = order++;
                rtn.Add(t);
			}
            //If this is not a load of the ITATSystem terms, then ensure that the collection includes the Attachments and Comments terms.
            if (template != null)
            {
                List<Term> placeholderTerms = FindTermsOfType(rtn, (TermType.PlaceHolderAttachments | TermType.PlaceHolderComments));
                if (placeholderTerms == null || (placeholderTerms != null && placeholderTerms.Count == 0))
                {
                    //If this is the first time these are being added, then this should be under Basic Security.
                    Term t = new PlaceHolderAttachments(false, template, false);
                    t.TermGroupID = template.BasicSecurityTermGroupID;
                    t.Order = order++;
                    rtn.Add(t);

                    t = new PlaceHolderComments(false, template, false);
                    t.TermGroupID = template.BasicSecurityTermGroupID;
                    t.Order = order++;
                    rtn.Add(t);
                }
                else if (placeholderTerms.Count != 2)
                {
                    throw new Exception(string.Format("Encountered a PlaceHolder term count of {0:D} when 2 were expected", placeholderTerms.Count));
                }
            }
			return rtn;
		}