Esempio n. 1
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();
                }
            }
        }
Esempio n. 2
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;
		}
Esempio n. 3
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));
                }
            }
        }
Esempio n. 4
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));
				}
			}
		}