private static void AddTrustedDependencies(IDependencyManager dependencyManager)
        {
            IDataTypeFascade            dataTypeFascade;
            IReflectionFascade          reflectionFascade;
            IConfigurationRoot          configurationRoot;
            IAppConfigFascade           appConfigFascade;
            IAssemblyInformationFascade assemblyInformationFascade;

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

            dataTypeFascade            = new DataTypeFascade();
            reflectionFascade          = new ReflectionFascade(dataTypeFascade);
            configurationRoot          = LoadAppConfigFile(APP_CONFIG_FILE_NAME);
            appConfigFascade           = new AppConfigFascade(configurationRoot, dataTypeFascade);
            assemblyInformationFascade = new AssemblyInformationFascade(reflectionFascade, Assembly.GetEntryAssembly());

            dependencyManager.AddResolution <IConfigurationRoot>(string.Empty, false, new SingletonWrapperDependencyResolution <IConfigurationRoot>(new InstanceDependencyResolution <IConfigurationRoot>(configurationRoot)));
            dependencyManager.AddResolution <IDataTypeFascade>(string.Empty, false, new SingletonWrapperDependencyResolution <IDataTypeFascade>(new InstanceDependencyResolution <IDataTypeFascade>(dataTypeFascade)));
            dependencyManager.AddResolution <IReflectionFascade>(string.Empty, false, new SingletonWrapperDependencyResolution <IReflectionFascade>(new InstanceDependencyResolution <IReflectionFascade>(reflectionFascade)));
            dependencyManager.AddResolution <IAppConfigFascade>(string.Empty, false, new SingletonWrapperDependencyResolution <IAppConfigFascade>(new InstanceDependencyResolution <IAppConfigFascade>(appConfigFascade)));
            dependencyManager.AddResolution <IAssemblyInformationFascade>(string.Empty, false, new SingletonWrapperDependencyResolution <IAssemblyInformationFascade>(new InstanceDependencyResolution <IAssemblyInformationFascade>(assemblyInformationFascade)));
        }
        public void ShouldFailOnNullReflectionFascadeCreateTest()
        {
            AssemblyInformationFascade assemblyInformationFascade;
            MockFactory        mockFactory;
            IReflectionFascade mockReflectionFascade;
            Assembly           mockAssembly;

            mockFactory           = new MockFactory();
            mockReflectionFascade = null;
            mockAssembly          = Assembly.GetEntryAssembly();    // dummy

            assemblyInformationFascade = new AssemblyInformationFascade(mockReflectionFascade, mockAssembly);
        }
        public void ShouldFailOnNullAssemblyCreateTest()
        {
            AssemblyInformationFascade assemblyInformationFascade;
            MockFactory        mockFactory;
            IReflectionFascade mockReflectionFascade;
            Assembly           mockAssembly;

            mockFactory           = new MockFactory();
            mockReflectionFascade = mockFactory.CreateInstance <IReflectionFascade>();
            mockAssembly          = null;

            assemblyInformationFascade = new AssemblyInformationFascade(mockReflectionFascade, mockAssembly);
        }
        public void ShouldCreateTest()
        {
            AssemblyInformationFascade assemblyInformationFascade;
            MockFactory        mockFactory;
            IReflectionFascade mockReflectionFascade;
            Assembly           mockAssembly, _unusedAssembly = null;

            const string ASSEMBLY_TITLE                 = "sdfgsfdg";
            const string ASSEMBLY_DESCRIPTION           = "rthrs";
            const string ASSEMBLY_PRODUCT               = "hnfgnhfghn";
            const string ASSEMBLY_COPYRIGHT             = "bxcbx";
            const string ASSEMBLY_COMPANY               = "swergwerg";
            const string ASSEMBLY_CONFIGURATION         = "webxvxn";
            const string ASSEMBLY_FILE_VERSION          = "wegwegr";
            const string ASSEMBLY_INFORMATIONAL_VERSION = "dnxnn";
            const string ASSEMBLY_TRADEMARK             = "yjtmrum";

            mockFactory           = new MockFactory();
            mockReflectionFascade = mockFactory.CreateInstance <IReflectionFascade>();
            mockAssembly          = Assembly.GetEntryAssembly();    // dummy

            Expect.On(mockReflectionFascade).One.Method(m => m.GetOneAttribute <AssemblyTitleAttribute>(_unusedAssembly)).With(mockAssembly).WillReturn(new AssemblyTitleAttribute(ASSEMBLY_TITLE));
            Expect.On(mockReflectionFascade).One.Method(m => m.GetOneAttribute <AssemblyDescriptionAttribute>(_unusedAssembly)).With(mockAssembly).WillReturn(new AssemblyDescriptionAttribute(ASSEMBLY_DESCRIPTION));
            Expect.On(mockReflectionFascade).One.Method(m => m.GetOneAttribute <AssemblyProductAttribute>(_unusedAssembly)).With(mockAssembly).WillReturn(new AssemblyProductAttribute(ASSEMBLY_PRODUCT));
            Expect.On(mockReflectionFascade).One.Method(m => m.GetOneAttribute <AssemblyCopyrightAttribute>(_unusedAssembly)).With(mockAssembly).WillReturn(new AssemblyCopyrightAttribute(ASSEMBLY_COPYRIGHT));
            Expect.On(mockReflectionFascade).One.Method(m => m.GetOneAttribute <AssemblyCompanyAttribute>(_unusedAssembly)).With(mockAssembly).WillReturn(new AssemblyCompanyAttribute(ASSEMBLY_COMPANY));
            Expect.On(mockReflectionFascade).One.Method(m => m.GetOneAttribute <AssemblyConfigurationAttribute>(_unusedAssembly)).With(mockAssembly).WillReturn(new AssemblyConfigurationAttribute(ASSEMBLY_CONFIGURATION));
            Expect.On(mockReflectionFascade).One.Method(m => m.GetOneAttribute <AssemblyFileVersionAttribute>(_unusedAssembly)).With(mockAssembly).WillReturn(new AssemblyFileVersionAttribute(ASSEMBLY_FILE_VERSION));
            Expect.On(mockReflectionFascade).One.Method(m => m.GetOneAttribute <AssemblyInformationalVersionAttribute>(_unusedAssembly)).With(mockAssembly).WillReturn(new AssemblyInformationalVersionAttribute(ASSEMBLY_INFORMATIONAL_VERSION));
            Expect.On(mockReflectionFascade).One.Method(m => m.GetOneAttribute <AssemblyTrademarkAttribute>(_unusedAssembly)).With(mockAssembly).WillReturn(new AssemblyTrademarkAttribute(ASSEMBLY_TRADEMARK));

            assemblyInformationFascade = new AssemblyInformationFascade(mockReflectionFascade, mockAssembly);

            Assert.AreEqual(ASSEMBLY_TITLE, assemblyInformationFascade.Title);
            Assert.AreEqual(ASSEMBLY_DESCRIPTION, assemblyInformationFascade.Description);
            Assert.AreEqual(ASSEMBLY_PRODUCT, assemblyInformationFascade.Product);
            Assert.AreEqual(ASSEMBLY_COPYRIGHT, assemblyInformationFascade.Copyright);
            Assert.AreEqual(ASSEMBLY_COMPANY, assemblyInformationFascade.Company);
            Assert.AreEqual(ASSEMBLY_CONFIGURATION, assemblyInformationFascade.Configuration);
            Assert.AreEqual(ASSEMBLY_FILE_VERSION, assemblyInformationFascade.NativeFileVersion);
            Assert.AreEqual(ASSEMBLY_INFORMATIONAL_VERSION, assemblyInformationFascade.InformationalVersion);
            Assert.AreEqual(ASSEMBLY_TRADEMARK, assemblyInformationFascade.Trademark);
            Assert.AreEqual(mockAssembly.GetName().Version.ToString(), assemblyInformationFascade.AssemblyVersion);
        }
        /// <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));
                }
            }
        }
Ejemplo n.º 6
0
        public void Host(IDictionary <string, IList <object> > arguments,
                         IDictionary <string, IList <object> > properties)
        {
            DateTime startUtc, endUtc;

            ITextMetalTemplate textMetalTemplate;
            __ITextMetalModel  textMetalModel;
            ITextMetalOutput   textMetalOutput;

            Dictionary <string, object> arguments_;
            Dictionary <string, object> properties_;

            Dictionary <string, object> globalVariableTable;

            IAssemblyInformationFascade assemblyInformationFascade;

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

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

            startUtc = DateTime.UtcNow;

            arguments_ = arguments.ToDictionary(kvp => kvp.Key,
                                                kvp => kvp.Value.Count == 1 ? kvp.Value[0] : kvp.Value.ToArray());

            properties_ = properties.ToDictionary(kvp => kvp.Key,
                                                  kvp => kvp.Value.Count == 1 ? kvp.Value[0] : kvp.Value.ToArray());

            assemblyInformationFascade = new AssemblyInformationFascade(this.ReflectionFascade, typeof(TextMetalToolHost).GetTypeInfo().Assembly);

            Lazy <object> lazyGuid = new Lazy <object>(() => Guid.NewGuid());
            Func <object> getDate  = () => DateTime.UtcNow;

            var environment = new
            {
                Arguments              = Environment.GetCommandLineArgs(),
                Variables              = Environment.GetEnvironmentVariables(),
                NewLine                = Environment.NewLine,
                Version                = Environment.Version,
                MachineName            = Environment.MachineName,
                UserName               = Environment.UserName,
                OSVersion              = Environment.OSVersion,
                UserDomainName         = Environment.UserDomainName,
                Is64BitOperatingSystem = Environment.Is64BitOperatingSystem,
                Is64BitProcess         = Environment.Is64BitProcess,
                ProcessorCount         = Environment.ProcessorCount,
                GetDate                = getDate,
                LazyGuid               = lazyGuid
            };

            var tooling = new
            {
                AssemblyVersion      = assemblyInformationFascade.AssemblyVersion,
                InformationalVersion = assemblyInformationFascade.InformationalVersion,
                NativeFileVersion    = assemblyInformationFascade.NativeFileVersion,
                ModuleName           = assemblyInformationFascade.ModuleName,
                Company        = assemblyInformationFascade.Company,
                Configuration  = assemblyInformationFascade.Configuration,
                Copyright      = assemblyInformationFascade.Copyright,
                Description    = assemblyInformationFascade.Description,
                Product        = assemblyInformationFascade.Product,
                Title          = assemblyInformationFascade.Title,
                Trademark      = assemblyInformationFascade.Trademark,
                StartedWhenUtc = startUtc
            };

            // globals (GVT)
            globalVariableTable = new Dictionary <string, object>();
            globalVariableTable.Add("Tooling", tooling);
            globalVariableTable.Add("Environment", environment);

            globalVariableTable.Add("Properties", properties_);
            globalVariableTable.Add("Arguments", arguments_);

            // add arguments to GVT

            /*foreach (KeyValuePair<string, IList<object>> argument in arguments)
             * {
             *      if (argument.Value.Count == 0)
             *              continue;
             *
             *      globalVariableTable.Add(argument.Key,
             *              argument.Value.Count == 1 ? argument.Value[0] : argument.Value);
             * }*/

            // add properties to GVT

            /*foreach (KeyValuePair<string, IList<object>> property in properties)
             * {
             *      if (property.Value.Count == 0)
             *              continue;
             *
             *      globalVariableTable.Add(property.Key,
             *              property.Value.Count == 1 ? property.Value[0] : property.Value);
             * }*/

            // do the deal...
            using (ITextMetalTemplateFactory textMetalTemplateFactory = NewObjectFromType <ITextMetalTemplateFactory>(this.Configuration.GetTemplateFactoryType()))
            {
                //textMetalTemplateFactory.Configuration = ...
                textMetalTemplateFactory.Create();

                textMetalTemplate = textMetalTemplateFactory.GetTemplateObject(new Uri("urn:null"), properties_);

                using (ITextMetalModelFactory textMetalModelFactory = NewObjectFromType <ITextMetalModelFactory>(this.Configuration.GetModelFactoryType()))
                {
                    //textMetalModelFactory.Configuration = ...
                    textMetalModelFactory.Create();

                    textMetalModel = textMetalModelFactory.GetModelObject(properties_);

                    using (ITextMetalOutputFactory textMetalOutputFactory = NewObjectFromType <ITextMetalOutputFactory>(this.Configuration.GetOutputFactoryType()))
                    {
                        //textMetalOutputFactory.Configuration = ...
                        textMetalOutputFactory.Create();

                        textMetalOutput = textMetalOutputFactory.GetOutputObject(new Uri("urn:null"), properties_);

                        //textMetalOutput.TextWriter.WriteLine("xxx");

                        using (ITextMetalContext textMetalContext = this.CreateContext())
                        {
                            //textMetalContext.Configuration = ...
                            textMetalContext.Create();

                            //textMetalContext.DiagnosticOutput.WriteObject(textMetalTemplate, "#template.xml");
                            //textMetalContext.DiagnosticOutput.WriteObject(textMetalModel, "#model.xml");

                            textMetalContext.DiagnosticOutput.TextWriter.WriteLine("['{0:O}' (UTC)]\tText templating started.", tooling.StartedWhenUtc);

                            textMetalContext.VariableTables.Push(globalVariableTable);
                            textMetalContext.IteratorModels.Push(textMetalModel);

                            textMetalTemplate.ExpandTemplate(textMetalContext);

                            textMetalContext.IteratorModels.Pop();
                            textMetalContext.VariableTables.Pop();

                            endUtc = DateTime.UtcNow;
                            textMetalContext.DiagnosticOutput.TextWriter.WriteLine("['{0:O}' (UTC)]\tText templating completed with duration: '{1}'.", endUtc, (endUtc - startUtc));
                        }
                    }
                }
            }
        }