protected virtual IXmlPersistEngine GetXmlPersistEngine(IDictionary<string, IList<string>> properties)
        {
            const string PROP_TOKEN_KNOWN_XML_OBJECT_AQTN = "KnownXmlObjectType";
            const string PROP_TOKEN_KNOWN_XML_TEXT_OBJECT_AQTN = "KnownXmlTextObjectType";
            IXmlPersistEngine xpe;
            IList<string> values;
            string xmlObjectAqtn;
            Type xmlObjectType = null;

            if (properties == null)
                throw new ArgumentNullException("properties");

            xpe = new XmlPersistEngine();

            xmlObjectAqtn = null;
            if (properties.TryGetValue(PROP_TOKEN_KNOWN_XML_TEXT_OBJECT_AQTN, out values))
            {
                if ((object)values != null && values.Count == 1)
                {
                    xmlObjectAqtn = values[0];
                    xmlObjectType = Type.GetType(xmlObjectAqtn, false);
                }
            }

            if ((object)xmlObjectType == null)
                throw new InvalidOperationException(string.Format("Failed to load the XML text object type '{0}' via Type.GetType(..).", xmlObjectAqtn));

            if (!typeof(IXmlTextObject).IsAssignableFrom(xmlObjectType))
                throw new InvalidOperationException(string.Format("The XML text object type is not assignable to type '{0}'.", typeof(IXmlTextObject).FullName));

            xpe.RegisterKnownXmlTextObject(xmlObjectType);

            xmlObjectType = null;
            if (properties.TryGetValue(PROP_TOKEN_KNOWN_XML_OBJECT_AQTN, out values))
            {
                if ((object)values != null)
                {
                    foreach (string value in values)
                    {
                        xmlObjectAqtn = value;
                        xmlObjectType = Type.GetType(xmlObjectAqtn, false);

                        if ((object)xmlObjectType == null)
                            throw new InvalidOperationException(string.Format("Failed to load the XML object type '{0}' via Type.GetType(..).", xmlObjectAqtn));

                        if (!typeof(IXmlObject).IsAssignableFrom(xmlObjectType))
                            throw new InvalidOperationException(string.Format("The XML object type is not assignable to type '{0}'.", typeof(IXmlObject).FullName));

                        xpe.RegisterKnownXmlObject(xmlObjectType);
                    }
                }
            }

            // [email protected]@2012-08-01: is this needed?
            //if ((object)xmlObjectType == null)
            //throw new InvalidOperationException("???");

            return xpe;
        }
		protected override IXmlPersistEngine GetXmlPersistEngine(IDictionary<string, IList<string>> properties)
		{
			IXmlPersistEngine xpe;

			xpe = new XmlPersistEngine();
			xpe.RegisterWellKnownConstructs();

			return xpe;
		}
Пример #3
0
        protected override IXmlPersistEngine GetXmlPersistEngine(IDictionary <string, IList <string> > properties)
        {
            IXmlPersistEngine xpe;

            xpe = new XmlPersistEngine();
            xpe.RegisterWellKnownConstructs();

            return(xpe);
        }
        protected override IXmlPersistEngine GetXmlPersistEngine(IDictionary<string, IList<string>> properties)
        {
            IXmlPersistEngine xpe;

            xpe = new XmlPersistEngine();
            xpe.RegisterKnownXmlObject<ArrayConstruct>();
            xpe.RegisterKnownXmlObject<ObjectConstruct>();
            xpe.RegisterKnownXmlObject<PropertyConstruct>();

            return xpe;
        }
Пример #5
0
        public void Host(string templateFilePath, object source, TextWriter textWriter)
        {
            IXmlPersistEngine xpe;
            TemplateConstruct template;
            ITemplatingContext templatingContext;
            Dictionary<string, object> globalVariableTable;
            string toolVersion;
            string templateDirectoryPath;

            if ((object)templateFilePath == null)
                throw new ArgumentNullException("templateFilePath");

            if ((object)textWriter == null)
                throw new ArgumentNullException("textWriter");

            if (DataType.IsWhiteSpace(templateFilePath))
                throw new ArgumentOutOfRangeException("templateFilePath");

            toolVersion = Assembly.GetAssembly(typeof(IXmlPersistEngine)).GetName().Version.ToString();
            templateFilePath = Path.GetFullPath(templateFilePath);
            templateDirectoryPath = Path.GetDirectoryName(templateFilePath);

            xpe = new XmlPersistEngine();
            xpe.RegisterWellKnownConstructs();

            template = (TemplateConstruct)xpe.DeserializeFromXml(templateFilePath);

            using (IInputMechanism inputMechanism = new FileInputMechanism(templateDirectoryPath, xpe)) // relative to template
            {
                using (IOutputMechanism outputMechanism = new TextWriterOutputMechanism(textWriter))
                {
                    templatingContext = new TemplatingContext(xpe, new Tokenizer(true), inputMechanism, outputMechanism);

                    templatingContext.Tokenizer.TokenReplacementStrategies.Add("StaticPropertyResolver", new DynamicValueTokenReplacementStrategy(DynamicValueTokenReplacementStrategy.StaticPropertyResolver));
                    templatingContext.Tokenizer.TokenReplacementStrategies.Add("StaticMethodResolver", new DynamicValueTokenReplacementStrategy(DynamicValueTokenReplacementStrategy.StaticMethodResolver));

                    // globals
                    templatingContext.VariableTables.Push(globalVariableTable = new Dictionary<string, object>());
                    globalVariableTable.Add("ToolVersion", toolVersion);

                    /*
                    if ((object)properties != null)
                    {
                        foreach (KeyValuePair<string, IList<string>> property in properties)
                        {
                            if (property.Value.Count == 0)
                                continue;

                            if (property.Value.Count == 1)
                                globalVariableTable.Add(property.Key, property.Value[0]);
                            else
                                globalVariableTable.Add(property.Key, property.Value);
                        }
                    }*/

                    templatingContext.IteratorModels.Push(source);
                    template.ExpandTemplate(templatingContext);
                    templatingContext.IteratorModels.Pop();
                    templatingContext.VariableTables.Pop();
                }
            }
        }
Пример #6
0
        /// <summary>
        /// Provides a hosting shim between a 'tool' host and the underlying TextMetal run-time.
        /// </summary>
        /// <param name="templateFilePath"> The file path of the input TextMetal template file to execute. </param>
        /// <param name="sourceFilePath"> The file path (or source specific URI) of the input data source to leverage. </param>
        /// <param name="baseDirectoryPath"> The root output directory path to place output arifacts (since this implementation uses file output mechanics). </param>
        /// <param name="sourceStrategyAssemblyQualifiedTypeName"> The assembly qualified type name for the ISourceStrategy to instantiate and execute. </param>
        /// <param name="strictMatching"> A value indicating whether to use strict matching semantics for tokens. </param>
        /// <param name="properties"> Arbitrary dictionary of string lists used to further customize the text templating process. The individual components or template files can use the properties as they see fit. </param>
        public void Host(string templateFilePath, string sourceFilePath, string baseDirectoryPath,
            string sourceStrategyAssemblyQualifiedTypeName, bool strictMatching, IDictionary<string, IList<string>> properties)
        {
            DateTime startUtc = DateTime.UtcNow, endUtc;
            IXmlPersistEngine xpe;
            TemplateConstruct template;
            object source;
            ObjectConstruct objectConstruct = null;
            ITemplatingContext templatingContext;
            Dictionary<string, object> globalVariableTable;
            string toolVersion;
            string templateDirectoryPath;
            Type sourceStrategyType;
            ISourceStrategy sourceStrategy;

            if ((object)templateFilePath == null)
                throw new ArgumentNullException("templateFilePath");

            if ((object)sourceFilePath == null)
                throw new ArgumentNullException("sourceFilePath");

            if ((object)baseDirectoryPath == null)
                throw new ArgumentNullException("baseDirectoryPath");

            if ((object)sourceStrategyAssemblyQualifiedTypeName == null)
                throw new ArgumentNullException("sourceStrategyAssemblyQualifiedTypeName");

            if ((object)properties == null)
                throw new ArgumentNullException("properties");

            if (DataType.IsWhiteSpace(templateFilePath))
                throw new ArgumentOutOfRangeException("templateFilePath");

            if (DataType.IsWhiteSpace(sourceFilePath))
                throw new ArgumentOutOfRangeException("sourceFilePath");

            if (DataType.IsWhiteSpace(baseDirectoryPath))
                throw new ArgumentOutOfRangeException("baseDirectoryPath");

            if (DataType.IsWhiteSpace(sourceStrategyAssemblyQualifiedTypeName))
                throw new ArgumentOutOfRangeException("sourceStrategyAssemblyQualifiedTypeName");

            toolVersion = new AssemblyInformation(Assembly.GetAssembly(typeof(IXmlPersistEngine))).AssemblyVersion;
            templateFilePath = Path.GetFullPath(templateFilePath);
            templateDirectoryPath = Path.GetDirectoryName(templateFilePath);
            baseDirectoryPath = Path.GetFullPath(baseDirectoryPath);

            if (!Directory.Exists(baseDirectoryPath))
                Directory.CreateDirectory(baseDirectoryPath);

            sourceStrategyType = Type.GetType(sourceStrategyAssemblyQualifiedTypeName, false);

            if ((object)sourceStrategyType == null)
                throw new InvalidOperationException("TODO (enhancement): add meaningful message");

            if (!typeof(ISourceStrategy).IsAssignableFrom(sourceStrategyType))
                throw new InvalidOperationException("TODO (enhancement): add meaningful message");

            sourceStrategy = (ISourceStrategy)Activator.CreateInstance(sourceStrategyType);

            xpe = new XmlPersistEngine();
            xpe.RegisterWellKnownConstructs();

            template = (TemplateConstruct)xpe.DeserializeFromXml(templateFilePath);
            source = sourceStrategy.GetSourceObject(sourceFilePath, properties);

            if ((object)source == null)
                return;

            objectConstruct = source as ObjectConstruct;

            xpe.SerializeToXml(template, Path.Combine(baseDirectoryPath, "#template.xml"));

            if ((object)objectConstruct != null)
                xpe.SerializeToXml(objectConstruct, Path.Combine(baseDirectoryPath, "#source.xml"));
            else if ((object)source != null && (object)Reflexion.GetOneAttribute<SerializableAttribute>(source.GetType()) != null)
                Cerealization.SetObjectToFile(Path.Combine(baseDirectoryPath, "#source.xml"), source);

            using (IInputMechanism inputMechanism = new FileInputMechanism(templateDirectoryPath, xpe)) // relative to template
            {
                using (IOutputMechanism outputMechanism = new FileOutputMechanism(baseDirectoryPath, "#textmetal.log"))
                {
                    outputMechanism.LogTextWriter.WriteLine("['{0:O}' (UTC)]\tText templating started.", startUtc);

                    templatingContext = new TemplatingContext(xpe, new Tokenizer(strictMatching), inputMechanism, outputMechanism);

                    templatingContext.Tokenizer.TokenReplacementStrategies.Add("StaticPropertyResolver", new DynamicValueTokenReplacementStrategy(DynamicValueTokenReplacementStrategy.StaticPropertyResolver));
                    templatingContext.Tokenizer.TokenReplacementStrategies.Add("StaticMethodResolver", new DynamicValueTokenReplacementStrategy(DynamicValueTokenReplacementStrategy.StaticMethodResolver));

                    // globals
                    templatingContext.VariableTables.Push(globalVariableTable = new Dictionary<string, object>());
                    globalVariableTable.Add("ToolVersion", toolVersion);

                    foreach (KeyValuePair<string, IList<string>> property in properties)
                    {
                        if (property.Value.Count == 0)
                            continue;

                        if (property.Value.Count == 1)
                            globalVariableTable.Add(property.Key, property.Value[0]);
                        else
                            globalVariableTable.Add(property.Key, property.Value);
                    }

                    templatingContext.IteratorModels.Push(source);
                    template.ExpandTemplate(templatingContext);
                    templatingContext.IteratorModels.Pop();
                    templatingContext.VariableTables.Pop();

                    endUtc = DateTime.UtcNow;
                    outputMechanism.LogTextWriter.WriteLine("['{0:O}' (UTC)]\tText templating completed with duration: '{1}'.", endUtc, (endUtc - startUtc));
                }
            }
        }
Пример #7
0
        public void SaveTemplateOnly(TemplateConstruct template, string filePath)
        {
            IXmlPersistEngine xpe;

            if ((object)template == null)
                throw new ArgumentNullException("template");

            if ((object)filePath == null)
                throw new ArgumentNullException("filePath");

            if (DataType.IsWhiteSpace(filePath))
                throw new ArgumentOutOfRangeException("filePath");

            filePath = Path.GetFullPath(filePath);

            xpe = new XmlPersistEngine();
            xpe.RegisterWellKnownConstructs();

            xpe.SerializeToXml(template, filePath);
        }
Пример #8
0
        public void SaveModelOnly(ObjectConstruct model, string filePath)
        {
            IXmlPersistEngine xpe;

            if ((object)model == null)
                throw new ArgumentNullException("model");

            if ((object)filePath == null)
                throw new ArgumentNullException("filePath");

            if (DataType.IsWhiteSpace(filePath))
                throw new ArgumentOutOfRangeException("filePath");

            filePath = Path.GetFullPath(filePath);

            xpe = new XmlPersistEngine();
            xpe.RegisterWellKnownConstructs();

            xpe.SerializeToXml(model, filePath);
        }
Пример #9
0
        public TemplateConstruct LoadTemplateOnly(string filePath)
        {
            IXmlPersistEngine xpe;
            TemplateConstruct template;

            if ((object)filePath == null)
                throw new ArgumentNullException("filePath");

            if (DataType.IsWhiteSpace(filePath))
                throw new ArgumentOutOfRangeException("filePath");

            filePath = Path.GetFullPath(filePath);

            xpe = new XmlPersistEngine();
            xpe.RegisterWellKnownConstructs();

            template = (TemplateConstruct)xpe.DeserializeFromXml(filePath);

            return template;
        }
Пример #10
0
        public object LoadModelOnly(string filePath)
        {
            IXmlPersistEngine xpe;
            ObjectConstruct model;

            if ((object)filePath == null)
                throw new ArgumentNullException("filePath");

            if (DataType.IsWhiteSpace(filePath))
                throw new ArgumentOutOfRangeException("filePath");

            filePath = Path.GetFullPath(filePath);

            xpe = new XmlPersistEngine();
            xpe.RegisterWellKnownConstructs();

            model = (ObjectConstruct)xpe.DeserializeFromXml(filePath);

            return model;
        }
        /// <summary>
        /// Provides a hosting shim between a 'tool' host and the underlying TextMetal run-time.
        /// </summary>
        /// <param name="argc"> The raw argument count passed into the host. </param>
        /// <param name="argv"> The raw arguments passed into the host. </param>
        /// <param name="args"> The parsed arguments passed into the host. </param>
        /// <param name="templateFilePath"> The file path of the input TextMetal template file to execute. </param>
        /// <param name="sourceFilePath"> The file path (or source specific URI) of the input data source to leverage. </param>
        /// <param name="baseDirectoryPath"> The root output directory path to place output arifacts (since this implementation uses file output mechanics). </param>
        /// <param name="sourceStrategyAqtn"> The assembly qualified type name for the ISourceStrategy to instantiate and execute. </param>
        /// <param name="strictMatching"> A value indicating whether to use strict matching semantics for tokens. </param>
        /// <param name="properties"> Arbitrary dictionary of string lists used to further customize the text templating process. The individual components or template files can use the properties as they see fit. </param>
        public void Host(int argc, string[] argv, IDictionary <string, object> args, string templateFilePath, string sourceFilePath, string baseDirectoryPath, string sourceStrategyAqtn, bool strictMatching, IDictionary <string, IList <string> > properties)
        {
            DateTime                    startUtc = DateTime.UtcNow, endUtc;
            IXmlPersistEngine           xpe;
            TemplateConstruct           template;
            object                      source;
            Dictionary <string, object> globalVariableTable;
            string                      toolVersion;
            Type            sourceStrategyType;
            ISourceStrategy sourceStrategy;

            if ((object)templateFilePath == null)
            {
                throw new ArgumentNullException(nameof(templateFilePath));
            }

            if ((object)sourceFilePath == null)
            {
                throw new ArgumentNullException(nameof(sourceFilePath));
            }

            if ((object)baseDirectoryPath == null)
            {
                throw new ArgumentNullException(nameof(baseDirectoryPath));
            }

            if ((object)sourceStrategyAqtn == null)
            {
                throw new ArgumentNullException(nameof(sourceStrategyAqtn));
            }

            if ((object)properties == null)
            {
                throw new ArgumentNullException(nameof(properties));
            }

            if (SolderFascadeAccessor.DataTypeFascade.IsWhiteSpace(templateFilePath))
            {
                throw new ArgumentOutOfRangeException(nameof(templateFilePath));
            }

            if (SolderFascadeAccessor.DataTypeFascade.IsWhiteSpace(sourceFilePath))
            {
                throw new ArgumentOutOfRangeException(nameof(sourceFilePath));
            }

            if (SolderFascadeAccessor.DataTypeFascade.IsWhiteSpace(baseDirectoryPath))
            {
                throw new ArgumentOutOfRangeException(nameof(baseDirectoryPath));
            }

            if (SolderFascadeAccessor.DataTypeFascade.IsWhiteSpace(sourceStrategyAqtn))
            {
                throw new ArgumentOutOfRangeException(nameof(sourceStrategyAqtn));
            }

            toolVersion       = new AssemblyInformationFascade(this.ReflectionFascade, typeof(TextMetalToolHost).GetTypeInfo().Assembly).AssemblyVersion;
            templateFilePath  = Path.GetFullPath(templateFilePath);
            baseDirectoryPath = Path.GetFullPath(baseDirectoryPath);

            sourceStrategyType = Type.GetType(sourceStrategyAqtn, false);

            if ((object)sourceStrategyType == null)
            {
                throw new InvalidOperationException(string.Format("Failed to load source strategy from assembly qualified type name '{0}'.", sourceStrategyAqtn));
            }

            if (!typeof(ISourceStrategy).IsAssignableFrom(sourceStrategyType))
            {
                throw new InvalidOperationException(string.Format("Source strategy type '{0}' is not assignable to '{1}'.", sourceStrategyType, typeof(ISourceStrategy)));
            }

            sourceStrategy = (ISourceStrategy)Activator.CreateInstance(sourceStrategyType);

            xpe = new XmlPersistEngine();
            xpe.RegisterWellKnownConstructs();

            // TODO: this was a bad idea and need to be fixed in a next version.
            using (IInputMechanism inputMechanism = new FileInputMechanism(templateFilePath, xpe, sourceStrategy))             // relative to template directory
            {
                source = inputMechanism.LoadSource(sourceFilePath, properties);

                if ((object)source == null)
                {
                    return;
                }

                template = (TemplateConstruct)inputMechanism.LoadTemplate(templateFilePath);

                using (IOutputMechanism outputMechanism = new FileOutputMechanism(baseDirectoryPath, "#textmetal.log", Encoding.UTF8, xpe))                 // relative to base directory
                {
                    outputMechanism.LogTextWriter.WriteLine("[DIAGNOSTIC INFOMRATION]", startUtc);

                    outputMechanism.LogTextWriter.WriteLine("argv: '{0}'", string.Join(" ", argv));
                    outputMechanism.LogTextWriter.WriteLine("toolVersion: '{0}'", toolVersion);
                    outputMechanism.LogTextWriter.WriteLine("baseDirectoryPath: \"{0}\"", baseDirectoryPath);
                    outputMechanism.LogTextWriter.WriteLine("sourceFilePath: \"{0}\"", sourceFilePath);
                    outputMechanism.LogTextWriter.WriteLine("templateFilePath: \"{0}\"", templateFilePath);
                    outputMechanism.LogTextWriter.WriteLine("sourceStrategyType: '{0}'", sourceStrategyType.FullName);

                    outputMechanism.WriteObject(template, "#template.xml");
                    outputMechanism.WriteObject(source, "#source.xml");

                    outputMechanism.LogTextWriter.WriteLine("['{0:O}' (UTC)]\tText templating started.", startUtc);

                    using (ITemplatingContext templatingContext = new TemplatingContext(xpe, new Tokenizer(strictMatching), inputMechanism, outputMechanism, properties))
                    {
                        templatingContext.Tokenizer.RegisterWellKnownTokenReplacementStrategies(templatingContext);

                        // globals
                        globalVariableTable = new Dictionary <string, object>();

                        var environment = new
                        {
                            ARGC = argc,
                            ARGV = argv,
                            ARGS = args,
                            CurrentManagedThreadId = Environment.CurrentManagedThreadId,
                            HasShutdownStarted     = Environment.HasShutdownStarted,
                            NewLine        = Environment.NewLine,
                            ProcessorCount = Environment.ProcessorCount,
                            StackTrace     = Environment.StackTrace,
                            TickCount      = Environment.TickCount,
                            Variables      = Environment.GetEnvironmentVariables()
                        };
                        globalVariableTable.Add("ToolVersion", toolVersion);
                        globalVariableTable.Add("Environment", environment);
                        globalVariableTable.Add("StartUtc", startUtc);

                        // add properties to GVT
                        foreach (KeyValuePair <string, IList <string> > property in properties)
                        {
                            if (property.Value.Count == 0)
                            {
                                continue;
                            }

                            if (property.Value.Count == 1)
                            {
                                globalVariableTable.Add(property.Key, property.Value[0]);
                            }
                            else
                            {
                                globalVariableTable.Add(property.Key, property.Value);
                            }
                        }

                        templatingContext.VariableTables.Push(globalVariableTable);
                        templatingContext.IteratorModels.Push(source);
                        template.ExpandTemplate(templatingContext);
                        templatingContext.IteratorModels.Pop();
                        templatingContext.VariableTables.Pop();
                    }

                    endUtc = DateTime.UtcNow;
                    outputMechanism.LogTextWriter.WriteLine("['{0:O}' (UTC)]\tText templating completed with duration: '{1}'.", endUtc, (endUtc - startUtc));
                }
            }
        }
Пример #12
0
        protected virtual IXmlPersistEngine GetXmlPersistEngine(IDictionary <string, IList <string> > properties)
        {
            const string      PROP_TOKEN_KNOWN_XML_OBJECT_AQTN      = "KnownXmlObjectType";
            const string      PROP_TOKEN_KNOWN_XML_TEXT_OBJECT_AQTN = "KnownXmlTextObjectType";
            IXmlPersistEngine xpe;
            IList <string>    values;
            string            xmlObjectAqtn;
            Type xmlObjectType = null;

            if (properties == null)
            {
                throw new ArgumentNullException(nameof(properties));
            }

            xpe           = new XmlPersistEngine();
            xmlObjectAqtn = null;

            if (properties.TryGetValue(PROP_TOKEN_KNOWN_XML_TEXT_OBJECT_AQTN, out values))
            {
                if ((object)values != null && values.Count == 1)
                {
                    xmlObjectAqtn = values[0];
                    xmlObjectType = Type.GetType(xmlObjectAqtn, false);
                }

                if ((object)xmlObjectType == null)
                {
                    throw new InvalidOperationException(string.Format("Failed to load the XML text object type '{0}' via Type.GetType(..).", xmlObjectAqtn));
                }

                if (!typeof(IXmlTextObject).IsAssignableFrom(xmlObjectType))
                {
                    throw new InvalidOperationException(string.Format("The XML text object type is not assignable to type '{0}'.", typeof(IXmlTextObject).FullName));
                }

                xpe.RegisterKnownXmlTextObject(xmlObjectType);
            }

            if (properties.TryGetValue(PROP_TOKEN_KNOWN_XML_OBJECT_AQTN, out values))
            {
                if ((object)values != null)
                {
                    foreach (string value in values)
                    {
                        xmlObjectAqtn = value;
                        xmlObjectType = Type.GetType(xmlObjectAqtn, false);

                        if ((object)xmlObjectType == null)
                        {
                            throw new InvalidOperationException(string.Format("Failed to load the XML object type '{0}' via Type.GetType(..).", xmlObjectAqtn));
                        }

                        if (!typeof(IXmlObject).IsAssignableFrom(xmlObjectType))
                        {
                            throw new InvalidOperationException(string.Format("The XML object type is not assignable to type '{0}'.", typeof(IXmlObject).FullName));
                        }

                        xpe.RegisterKnownXmlObject(xmlObjectType);
                    }
                }
            }

            return(xpe);
        }
Пример #13
0
		public EmailMessage Host(bool strictMatching, EmailTemplate emailTemplate, object modelObject)
		{
			EmailMessage emailMessage;

			XmlPersistEngine xpe;
			TemplateConstruct template;
			ITemplatingContext templatingContext;
			XmlReader templateXmlReader;

			if ((object)emailTemplate == null)
				throw new ArgumentNullException(nameof(emailTemplate));

			emailMessage = new EmailMessage();

			xpe = new XmlPersistEngine();
			xpe.RegisterWellKnownConstructs();

			using (IInputMechanism inputMechanism = new NullInputMechanism())
			{
				using (StringWriter stringWriter = new StringWriter())
				{
					using (IOutputMechanism outputMechanism = new TextWriterOutputMechanism(stringWriter, xpe))
					{
						using (templatingContext = new TemplatingContext(xpe, new Tokenizer(strictMatching), inputMechanism, outputMechanism, new Dictionary<string, IList<string>>()))
						{
							// FROM
							using (templateXmlReader = XmlReader.Create(new StringReader(emailTemplate.FromXml.OuterXml)))
								template = (TemplateConstruct)xpe.DeserializeFromXml(templateXmlReader);

							templatingContext.IteratorModels.Push(modelObject);
							template.ExpandTemplate(templatingContext);
							templatingContext.IteratorModels.Pop();

							emailMessage.From = stringWriter.ToString();
							stringWriter.GetStringBuilder().Clear();

							// SENDER
							using (templateXmlReader = XmlReader.Create(new StringReader(emailTemplate.SenderXml.OuterXml)))
								template = (TemplateConstruct)xpe.DeserializeFromXml(templateXmlReader);

							templatingContext.IteratorModels.Push(modelObject);
							template.ExpandTemplate(templatingContext);
							templatingContext.IteratorModels.Pop();

							emailMessage.Sender = stringWriter.ToString();
							stringWriter.GetStringBuilder().Clear();

							// REPLYTO
							using (templateXmlReader = XmlReader.Create(new StringReader(emailTemplate.ReplyToXml.OuterXml)))
								template = (TemplateConstruct)xpe.DeserializeFromXml(templateXmlReader);

							templatingContext.IteratorModels.Push(modelObject);
							template.ExpandTemplate(templatingContext);
							templatingContext.IteratorModels.Pop();

							emailMessage.ReplyTo = stringWriter.ToString();
							stringWriter.GetStringBuilder().Clear();

							// TO
							using (templateXmlReader = XmlReader.Create(new StringReader(emailTemplate.ToXml.OuterXml)))
								template = (TemplateConstruct)xpe.DeserializeFromXml(templateXmlReader);

							templatingContext.IteratorModels.Push(modelObject);
							template.ExpandTemplate(templatingContext);
							templatingContext.IteratorModels.Pop();

							emailMessage.To = stringWriter.ToString();
							stringWriter.GetStringBuilder().Clear();

							// CC
							using (templateXmlReader = XmlReader.Create(new StringReader(emailTemplate.CarbonCopyXml.OuterXml)))
								template = (TemplateConstruct)xpe.DeserializeFromXml(templateXmlReader);

							templatingContext.IteratorModels.Push(modelObject);
							template.ExpandTemplate(templatingContext);
							templatingContext.IteratorModels.Pop();

							emailMessage.CarbonCopy = stringWriter.ToString();
							stringWriter.GetStringBuilder().Clear();

							// BCC
							using (templateXmlReader = XmlReader.Create(new StringReader(emailTemplate.BlindCarbonCopyXml.OuterXml)))
								template = (TemplateConstruct)xpe.DeserializeFromXml(templateXmlReader);

							templatingContext.IteratorModels.Push(modelObject);
							template.ExpandTemplate(templatingContext);
							templatingContext.IteratorModels.Pop();

							emailMessage.BlindCarbonCopy = stringWriter.ToString();
							stringWriter.GetStringBuilder().Clear();

							// SUBJECT
							using (templateXmlReader = XmlReader.Create(new StringReader(emailTemplate.SubjectXml.OuterXml)))
								template = (TemplateConstruct)xpe.DeserializeFromXml(templateXmlReader);

							templatingContext.IteratorModels.Push(modelObject);
							template.ExpandTemplate(templatingContext);
							templatingContext.IteratorModels.Pop();

							emailMessage.Subject = stringWriter.ToString();
							stringWriter.GetStringBuilder().Clear();

							// ISBODYHTML
							emailMessage.IsBodyHtml = emailTemplate.IsBodyHtml;

							// BODY
							using (templateXmlReader = XmlReader.Create(new StringReader(emailTemplate.BodyXml.OuterXml)))
								template = (TemplateConstruct)xpe.DeserializeFromXml(templateXmlReader);

							templatingContext.IteratorModels.Push(modelObject);
							template.ExpandTemplate(templatingContext);
							templatingContext.IteratorModels.Pop();

							emailMessage.Body = stringWriter.ToString();
							stringWriter.GetStringBuilder().Clear();
						}
					}
				}
			}

			return emailMessage;
		}
Пример #14
0
		/// <summary>
		/// Provides a hosting shim between a 'tool' host and the underlying TextMetal run-time.
		/// </summary>
		/// <param name="argc"> The raw argument count passed into the host. </param>
		/// <param name="argv"> The raw arguments passed into the host. </param>
		/// <param name="args"> The parsed arguments passed into the host. </param>
		/// <param name="templateFilePath"> The file path of the input TextMetal template file to execute. </param>
		/// <param name="sourceFilePath"> The file path (or source specific URI) of the input data source to leverage. </param>
		/// <param name="baseDirectoryPath"> The root output directory path to place output arifacts (since this implementation uses file output mechanics). </param>
		/// <param name="sourceStrategyAqtn"> The assembly qualified type name for the ISourceStrategy to instantiate and execute. </param>
		/// <param name="strictMatching"> A value indicating whether to use strict matching semantics for tokens. </param>
		/// <param name="properties"> Arbitrary dictionary of string lists used to further customize the text templating process. The individual components or template files can use the properties as they see fit. </param>
		public void Host(int argc, string[] argv, IDictionary<string, object> args, string templateFilePath, string sourceFilePath, string baseDirectoryPath, string sourceStrategyAqtn, bool strictMatching, IDictionary<string, IList<string>> properties)
		{
			DateTime startUtc = DateTime.UtcNow, endUtc;
			IXmlPersistEngine xpe;
			TemplateConstruct template;
			object source;
			Dictionary<string, object> globalVariableTable;
			string toolVersion;
			Type sourceStrategyType;
			ISourceStrategy sourceStrategy;

			if ((object)templateFilePath == null)
				throw new ArgumentNullException(nameof(templateFilePath));

			if ((object)sourceFilePath == null)
				throw new ArgumentNullException(nameof(sourceFilePath));

			if ((object)baseDirectoryPath == null)
				throw new ArgumentNullException(nameof(baseDirectoryPath));

			if ((object)sourceStrategyAqtn == null)
				throw new ArgumentNullException(nameof(sourceStrategyAqtn));

			if ((object)properties == null)
				throw new ArgumentNullException(nameof(properties));

			if (SolderLegacyInstanceAccessor.DataTypeFascadeLegacyInstance.IsWhiteSpace(templateFilePath))
				throw new ArgumentOutOfRangeException(nameof(templateFilePath));

			if (SolderLegacyInstanceAccessor.DataTypeFascadeLegacyInstance.IsWhiteSpace(sourceFilePath))
				throw new ArgumentOutOfRangeException(nameof(sourceFilePath));

			if (SolderLegacyInstanceAccessor.DataTypeFascadeLegacyInstance.IsWhiteSpace(baseDirectoryPath))
				throw new ArgumentOutOfRangeException(nameof(baseDirectoryPath));

			if (SolderLegacyInstanceAccessor.DataTypeFascadeLegacyInstance.IsWhiteSpace(sourceStrategyAqtn))
				throw new ArgumentOutOfRangeException(nameof(sourceStrategyAqtn));

			toolVersion = new AssemblyInformationFascade(this.ReflectionFascade, typeof(IXmlPersistEngine).GetTypeInfo().Assembly).AssemblyVersion;
			templateFilePath = Path.GetFullPath(templateFilePath);
			baseDirectoryPath = Path.GetFullPath(baseDirectoryPath);

			sourceStrategyType = Type.GetType(sourceStrategyAqtn, false);

			if ((object)sourceStrategyType == null)
				throw new InvalidOperationException(string.Format("Failed to load source strategy from assembly qualified type name '{0}'.", sourceStrategyAqtn));

			if (!typeof(ISourceStrategy).IsAssignableFrom(sourceStrategyType))
				throw new InvalidOperationException(string.Format("Source strategy type '{0}' is not assignable to '{1}'.", sourceStrategyType, typeof(ISourceStrategy)));

			sourceStrategy = (ISourceStrategy)Activator.CreateInstance(sourceStrategyType);

			xpe = new XmlPersistEngine();
			xpe.RegisterWellKnownConstructs();

			// TODO: this was a bad idea and need to be fixed in a next version.
			using (IInputMechanism inputMechanism = new FileInputMechanism(templateFilePath, xpe, sourceStrategy)) // relative to template directory
			{
				source = inputMechanism.LoadSource(sourceFilePath, properties);

				if ((object)source == null)
					return;

				template = (TemplateConstruct)inputMechanism.LoadTemplate(templateFilePath);

				using (IOutputMechanism outputMechanism = new FileOutputMechanism(baseDirectoryPath, "#textmetal.log", Encoding.UTF8, xpe)) // relative to base directory
				{
					outputMechanism.WriteObject(template, "#template.xml");
					outputMechanism.WriteObject(source, "#source.xml");

					outputMechanism.LogTextWriter.WriteLine("['{0:O}' (UTC)]\tText templating started.", startUtc);

					using (ITemplatingContext templatingContext = new TemplatingContext(xpe, new Tokenizer(strictMatching), inputMechanism, outputMechanism, properties))
					{
						templatingContext.Tokenizer.RegisterWellKnownTokenReplacementStrategies(templatingContext);

						// globals
						globalVariableTable = new Dictionary<string, object>();

						var environment = new
										{
											ARGC = argc,
											ARGV = argv,
											ARGS = args,
											CurrentManagedThreadId = Environment.CurrentManagedThreadId,
											HasShutdownStarted = Environment.HasShutdownStarted,
											NewLine = Environment.NewLine,
											ProcessorCount = Environment.ProcessorCount,
											StackTrace = Environment.StackTrace,
											TickCount = Environment.TickCount,
											Variables = Environment.GetEnvironmentVariables()
										};
						globalVariableTable.Add("ToolVersion", toolVersion);
						globalVariableTable.Add("Environment", environment);
						globalVariableTable.Add("StartUtc", startUtc);

						// add properties to GVT
						foreach (KeyValuePair<string, IList<string>> property in properties)
						{
							if (property.Value.Count == 0)
								continue;

							if (property.Value.Count == 1)
								globalVariableTable.Add(property.Key, property.Value[0]);
							else
								globalVariableTable.Add(property.Key, property.Value);
						}

						templatingContext.VariableTables.Push(globalVariableTable);
						templatingContext.IteratorModels.Push(source);
						template.ExpandTemplate(templatingContext);
						templatingContext.IteratorModels.Pop();
						templatingContext.VariableTables.Pop();
					}

					endUtc = DateTime.UtcNow;
					outputMechanism.LogTextWriter.WriteLine("['{0:O}' (UTC)]\tText templating completed with duration: '{1}'.", endUtc, (endUtc - startUtc));
				}
			}
		}
Пример #15
0
        public EmailMessage Host(bool strictMatching, EmailTemplate emailTemplate, object modelObject)
        {
            EmailMessage emailMessage;

            XmlPersistEngine   xpe;
            TemplateConstruct  template;
            ITemplatingContext templatingContext;
            XmlTextReader      templateXmlTextReader;

            if ((object)emailTemplate == null)
            {
                throw new ArgumentNullException(nameof(emailTemplate));
            }

            emailMessage = new EmailMessage();

            xpe = new XmlPersistEngine();
            xpe.RegisterWellKnownConstructs();

            using (IInputMechanism inputMechanism = new NullInputMechanism())
            {
                using (StringWriter stringWriter = new StringWriter())
                {
                    using (IOutputMechanism outputMechanism = new TextWriterOutputMechanism(stringWriter, xpe))
                    {
                        using (templatingContext = new TemplatingContext(xpe, new Tokenizer(strictMatching), inputMechanism, outputMechanism, new Dictionary <string, IList <string> >()))
                        {
                            // FROM
                            using (templateXmlTextReader = new XmlTextReader(new StringReader(emailTemplate.FromXml.OuterXml)))
                                template = (TemplateConstruct)xpe.DeserializeFromXml(templateXmlTextReader);

                            templatingContext.IteratorModels.Push(modelObject);
                            template.ExpandTemplate(templatingContext);
                            templatingContext.IteratorModels.Pop();

                            emailMessage.From = stringWriter.ToString();
                            stringWriter.GetStringBuilder().Clear();

                            // SENDER
                            using (templateXmlTextReader = new XmlTextReader(new StringReader(emailTemplate.SenderXml.OuterXml)))
                                template = (TemplateConstruct)xpe.DeserializeFromXml(templateXmlTextReader);

                            templatingContext.IteratorModels.Push(modelObject);
                            template.ExpandTemplate(templatingContext);
                            templatingContext.IteratorModels.Pop();

                            emailMessage.Sender = stringWriter.ToString();
                            stringWriter.GetStringBuilder().Clear();

                            // REPLYTO
                            using (templateXmlTextReader = new XmlTextReader(new StringReader(emailTemplate.ReplyToXml.OuterXml)))
                                template = (TemplateConstruct)xpe.DeserializeFromXml(templateXmlTextReader);

                            templatingContext.IteratorModels.Push(modelObject);
                            template.ExpandTemplate(templatingContext);
                            templatingContext.IteratorModels.Pop();

                            emailMessage.ReplyTo = stringWriter.ToString();
                            stringWriter.GetStringBuilder().Clear();

                            // TO
                            using (templateXmlTextReader = new XmlTextReader(new StringReader(emailTemplate.ToXml.OuterXml)))
                                template = (TemplateConstruct)xpe.DeserializeFromXml(templateXmlTextReader);

                            templatingContext.IteratorModels.Push(modelObject);
                            template.ExpandTemplate(templatingContext);
                            templatingContext.IteratorModels.Pop();

                            emailMessage.To = stringWriter.ToString();
                            stringWriter.GetStringBuilder().Clear();

                            // CC
                            using (templateXmlTextReader = new XmlTextReader(new StringReader(emailTemplate.CarbonCopyXml.OuterXml)))
                                template = (TemplateConstruct)xpe.DeserializeFromXml(templateXmlTextReader);

                            templatingContext.IteratorModels.Push(modelObject);
                            template.ExpandTemplate(templatingContext);
                            templatingContext.IteratorModels.Pop();

                            emailMessage.CarbonCopy = stringWriter.ToString();
                            stringWriter.GetStringBuilder().Clear();

                            // BCC
                            using (templateXmlTextReader = new XmlTextReader(new StringReader(emailTemplate.BlindCarbonCopyXml.OuterXml)))
                                template = (TemplateConstruct)xpe.DeserializeFromXml(templateXmlTextReader);

                            templatingContext.IteratorModels.Push(modelObject);
                            template.ExpandTemplate(templatingContext);
                            templatingContext.IteratorModels.Pop();

                            emailMessage.BlindCarbonCopy = stringWriter.ToString();
                            stringWriter.GetStringBuilder().Clear();

                            // SUBJECT
                            using (templateXmlTextReader = new XmlTextReader(new StringReader(emailTemplate.SubjectXml.OuterXml)))
                                template = (TemplateConstruct)xpe.DeserializeFromXml(templateXmlTextReader);

                            templatingContext.IteratorModels.Push(modelObject);
                            template.ExpandTemplate(templatingContext);
                            templatingContext.IteratorModels.Pop();

                            emailMessage.Subject = stringWriter.ToString();
                            stringWriter.GetStringBuilder().Clear();

                            // ISBODYHTML
                            emailMessage.IsBodyHtml = emailTemplate.IsBodyHtml;

                            // BODY
                            using (templateXmlTextReader = new XmlTextReader(new StringReader(emailTemplate.BodyXml.OuterXml)))
                                template = (TemplateConstruct)xpe.DeserializeFromXml(templateXmlTextReader);

                            templatingContext.IteratorModels.Push(modelObject);
                            template.ExpandTemplate(templatingContext);
                            templatingContext.IteratorModels.Pop();

                            emailMessage.Body = stringWriter.ToString();
                            stringWriter.GetStringBuilder().Clear();
                        }
                    }
                }
            }

            return(emailMessage);
        }