public TokenizerProcessingDecorator(ITokenizer tokenizer, Preprocessor preprocessor, Postprocessor postprocessor)
        {
            this.tokenizer = tokenizer;

            this.preprocessor = preprocessor;
            this.postprocessor = postprocessor;
        }
		public void testScanner2() {
			var source = @"
class C {
}
";
			var codeErrorManager = new CodeErrorManager();
			var preprocessor = new Preprocessor(codeErrorManager, source.toCharArray());
			var scanner = new PreprocessedTextScanner(codeErrorManager, preprocessor.preprocess());
			Assert.assertEquals(LexicalUnit.NewLine, scanner.nextLexicalUnit());
			Assert.assertEquals(LexicalUnit.Keyword, scanner.nextLexicalUnit());
			RestorePoint rp = scanner.createRestorePoint();
			Assert.assertEquals(LexicalUnit.Whitespace, scanner.nextLexicalUnit());
			Assert.assertEquals(LexicalUnit.Identifier, scanner.nextLexicalUnit());
			Assert.assertEquals(LexicalUnit.Whitespace, scanner.nextLexicalUnit());
			Assert.assertEquals(LexicalUnit.OpenBrace, scanner.nextLexicalUnit());
			Assert.assertEquals(LexicalUnit.NewLine, scanner.nextLexicalUnit());
			scanner.restore(rp);
			Assert.assertEquals(LexicalUnit.Keyword, scanner.nextLexicalUnit());
			Assert.assertEquals("class", new String(scanner.Text, scanner.StartPosition, scanner.EndPosition - scanner.StartPosition));
			Assert.assertEquals(LexicalUnit.Whitespace, scanner.nextLexicalUnit());
			Assert.assertEquals(LexicalUnit.Identifier, scanner.nextLexicalUnit());
			Assert.assertEquals(LexicalUnit.Whitespace, scanner.nextLexicalUnit());
			Assert.assertEquals(LexicalUnit.OpenBrace, scanner.nextLexicalUnit());
			Assert.assertEquals(LexicalUnit.NewLine, scanner.nextLexicalUnit());
			Assert.assertEquals(LexicalUnit.CloseBrace, scanner.nextLexicalUnit());
			Assert.assertEquals(LexicalUnit.NewLine, scanner.nextLexicalUnit());
			Assert.assertEquals(LexicalUnit.EndOfStream, scanner.nextLexicalUnit());
		}
        public async Task Process()
        {
            var bytes = File.ReadAllBytes(Environment.CurrentDirectory + @"\icon.png");
            var fileName = Guid.NewGuid().ToString();
            var originalFileName = string.Format(Naming.FileNameFormat, fileName, Naming.Original, Naming.DefaultExtension);
            var contentType = "image/jpeg";

            var preProcessor = new Preprocessor(connectionString);
            await preProcessor.Process(bytes, contentType, fileName);

            //Table
            var entity = (from e in await this.table.QueryByRow<ImageEntity>(Naming.Original)
                          select e).FirstOrDefault();

            Assert.IsNotNull(entity);
            Assert.AreEqual(contentType, entity.MimeType);
            Assert.AreEqual(string.Format(Naming.PathFormat, this.container.Name, entity.FileName), entity.RelativePath);
            Assert.AreEqual(bytes.LongLength, entity.FileSize);

            //Container
            var data = await this.container.Get(entity.FileName);
            Assert.AreEqual(bytes, data);

            //Queue
            var queued = await this.queue.Get();
            Assert.IsNotNull(queued);

            var imgQueued = JsonConvert.DeserializeObject<ImageQueued>(queued.AsString);
            Assert.IsNotNull(imgQueued);
            Assert.AreEqual(Guid.Parse(entity.PartitionKey), imgQueued.Identifier);
            Assert.AreEqual(string.Format(Naming.FileNameFormat, entity.PartitionKey, "{0}", "{1}"), imgQueued.FileNameFormat);
            Assert.AreEqual(Naming.DefaultExtension, imgQueued.OriginalExtension);
        }
 public async Task ProcessFileNameNull()
 {
     var random = new Random();
     var bytes = new byte[64];
     random.NextBytes(bytes);
     
     var ip = new Preprocessor(connectionString);
     await ip.Process(bytes, Guid.NewGuid().ToString(), null);
 }
Beispiel #5
0
        public void TransformFileThrowsIfTokenValueIsNull()
        {
            // Arrange
            var processor = new Preprocessor();
            var mockProjectSystem = new Mock<MockProjectSystem>() { CallBase = true };
            var mockFile = new Mock<IPackageFile>();
            mockFile.Setup(m => m.Path).Returns("foo.bar.pp");
            mockFile.Setup(m => m.GetStream()).Returns(() => GetStream("test $token$"));

            // Act
            ExceptionAssert.Throws<InvalidOperationException>(() => processor.TransformFile(mockFile.Object, "foo.bar", mockProjectSystem.Object), "The replacement token 'token' has no value.");
        }
        public void RevertFileRemovesFileIfContentIsTheSame()
        {
            // Arrange
            var processor = new Preprocessor();
            var mockProjectSystem = new Mock<MockProjectSystem>() { CallBase = true };
            mockProjectSystem.Setup(m => m.GetPropertyValue("token")).Returns("token value");
            mockProjectSystem.Object.AddFile("foo.bar", GetStream("test token value"));
            var mockFile = new Mock<IPackageFile>();
            mockFile.Setup(m => m.Path).Returns("foo.bar.pp");
            mockFile.Setup(m => m.GetStream()).Returns(() => GetStream("test $token$"));

            // Act
            processor.RevertFile(mockFile.Object, "foo.bar", Enumerable.Empty<IPackageFile>(), mockProjectSystem.Object);

            // Assert            
            Assert.True(mockProjectSystem.Object.Deleted.Contains("foo.bar"));
        }
        public void TransformFileReplacesTokensWithValueAndReturnsModifiedStream()
        {
            // Arrange
            var processor = new Preprocessor();
            var mockProjectSystem = new Mock<MockProjectSystem>() { CallBase = true };
            mockProjectSystem.Setup(m => m.GetPropertyValue("token")).Returns("token value");
            var mockFile = new Mock<IPackageFile>();
            mockFile.Setup(m => m.Path).Returns("foo.bar.pp");
            mockFile.Setup(m => m.GetStream()).Returns(() => GetStream("test $token$"));

            // Act
            processor.TransformFile(mockFile.Object, "foo.bar", mockProjectSystem.Object);

            // Assert
            Assert.True(mockProjectSystem.Object.FileExists("foo.bar"));
            Assert.Equal("test token value", mockProjectSystem.Object.OpenFile("foo.bar").ReadToEnd());
        }
        public void TransformFileDoesNothingIfFileExists()
        {
            // Arrange
            var processor = new Preprocessor();
            var mockProjectSystem = new Mock<MockProjectSystem>() { CallBase = true };
            mockProjectSystem.Setup(m => m.GetPropertyValue("token")).Returns("token value");
            mockProjectSystem.Object.AddFile("foo.bar", GetStream("hello"));
            var mockFile = new Mock<IPackageFile>();
            mockFile.Setup(m => m.Path).Returns("foo.bar.pp");
            mockFile.Setup(m => m.GetStream()).Returns(() => GetStream("test $token$"));

            // Act
            processor.TransformFile(mockFile.Object, "foo.bar", mockProjectSystem.Object);

            // Assert            
            Assert.Equal("hello", mockProjectSystem.Object.OpenFile("foo.bar").ReadToEnd());
        }
Beispiel #9
0
        public void TransformFileGeneratedFileContainsBom()
        {
            // Arrange
            var processor = new Preprocessor();
            var mockProjectSystem = new Mock<MockProjectSystem>() { CallBase = true };
            mockProjectSystem.Setup(m => m.GetPropertyValue("token")).Returns("token value");
            var mockFile = new Mock<IPackageFile>();
            mockFile.Setup(m => m.Path).Returns("foo.bar.pp");
            mockFile.Setup(m => m.GetStream()).Returns(() => GetStream("test $token$"));

            // Act
            processor.TransformFile(mockFile.Object, "foo.bar", mockProjectSystem.Object);

            // Assert
            var bytes = mockProjectSystem.Object.OpenFile("foo.bar").ReadAllBytes();
            Assert.Equal(0xEF, bytes[0]);
            Assert.Equal(0xBB, bytes[1]);
            Assert.Equal(0xBF, bytes[2]);
        }
		public void testScanner() {
			var source = @"
class C {
}
";
			var codeErrorManager = new CodeErrorManager();
			var preprocessor = new Preprocessor(codeErrorManager, source.toCharArray());
			var scanner = new PreprocessedTextScanner(codeErrorManager, preprocessor.preprocess());
			Assert.assertEquals(LexicalUnit.NewLine, scanner.nextLexicalUnit());
			Assert.assertEquals(LexicalUnit.Keyword, scanner.nextLexicalUnit());
			Assert.assertEquals(LexicalUnit.Whitespace, scanner.nextLexicalUnit());
			Assert.assertEquals(LexicalUnit.Identifier, scanner.nextLexicalUnit());
			Assert.assertEquals(LexicalUnit.Whitespace, scanner.nextLexicalUnit());
			Assert.assertEquals(LexicalUnit.OpenBrace, scanner.nextLexicalUnit());
			Assert.assertEquals(LexicalUnit.NewLine, scanner.nextLexicalUnit());
			Assert.assertEquals(LexicalUnit.CloseBrace, scanner.nextLexicalUnit());
			Assert.assertEquals(LexicalUnit.NewLine, scanner.nextLexicalUnit());
			Assert.assertEquals(LexicalUnit.EndOfStream, scanner.nextLexicalUnit());
		}
Beispiel #11
0
        public void TransformFileOverrideIfFileExistsAndLoggerReturnsIgnore(FileConflictResolution resolution)
        {
            // Arrange
            var logger = new Mock<ILogger>();
            logger.Setup(l => l.ResolveFileConflict(It.IsAny<string>())).Returns(resolution);

            var processor = new Preprocessor();
            var mockProjectSystem = new Mock<MockProjectSystem>() { CallBase = true };
            mockProjectSystem.Setup(m => m.GetPropertyValue("token")).Returns("token value");
            mockProjectSystem.Object.AddFile("foo.bar", GetStream("hello"));
            mockProjectSystem.Setup(m => m.Logger).Returns(logger.Object);
            var mockFile = new Mock<IPackageFile>();
            mockFile.Setup(m => m.Path).Returns("foo.bar.pp");
            mockFile.Setup(m => m.GetStream()).Returns(() => GetStream("test $token$"));

            // Act
            processor.TransformFile(mockFile.Object, "foo.bar", mockProjectSystem.Object);

            // Assert            
            Assert.Equal("hello", mockProjectSystem.Object.OpenFile("foo.bar").ReadToEnd());
        }
        public void ExecuteReport(Dictionary<string, string> parameters, Preprocessor.ProcessingLibrary.Processor processor)
        {
            SmtpClient client = new SmtpClient();
            client.Port = Convert.ToInt32(parameters["port"]);
            client.Host = parameters["host"];
            client.EnableSsl = Convert.ToBoolean(parameters["enableSsl"]);
            client.Timeout = 10000;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            if (parameters.ContainsKey("user"))
            {
                client.UseDefaultCredentials = false;
                client.Credentials = new System.Net.NetworkCredential(parameters["user"], parameters["password"]);
            }

            MailMessage mm = new MailMessage();
            mm.From = new MailAddress(parameters["from"]);
            mm.Subject = parameters["subjectFormat"];
            mm.BodyEncoding = UTF8Encoding.UTF8;
            mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

            client.Send(mm);
        }
Beispiel #13
0
        /// <summary>
        /// Parses a HelpFilter element.
        /// </summary>
        /// <param name="node">Element to process.</param>
        private void ParseHelpFilterElement(XmlNode node)
        {
            SourceLineNumberCollection sourceLineNumbers = Preprocessor.GetSourceLineNumbers(node);
            string    id = null;
            string    filterDefinition = null;
            string    name             = null;
            YesNoType suppressCAs      = YesNoType.No;

            foreach (XmlAttribute attrib in node.Attributes)
            {
                if (0 == attrib.NamespaceURI.Length || attrib.NamespaceURI == this.schema.TargetNamespace)
                {
                    switch (attrib.LocalName)
                    {
                    case "Id":
                        id = this.Core.GetAttributeIdentifierValue(sourceLineNumbers, attrib);
                        break;

                    case "FilterDefinition":
                        filterDefinition = this.Core.GetAttributeValue(sourceLineNumbers, attrib);
                        break;

                    case "Name":
                        name = this.Core.GetAttributeValue(sourceLineNumbers, attrib);
                        break;

                    case "SuppressCustomActions":
                        suppressCAs = this.Core.GetAttributeYesNoValue(sourceLineNumbers, attrib);
                        break;

                    default:
                        this.Core.UnexpectedAttribute(sourceLineNumbers, attrib);
                        break;
                    }
                }
                else
                {
                    this.Core.UnsupportedExtensionAttribute(sourceLineNumbers, attrib);
                }
            }

            if (null == id)
            {
                this.Core.OnMessage(WixErrors.ExpectedAttribute(sourceLineNumbers, node.Name, "Id"));
            }

            if (null == name)
            {
                this.Core.OnMessage(WixErrors.ExpectedAttribute(sourceLineNumbers, node.Name, "Name"));
            }

            // find unexpected child elements
            foreach (XmlNode child in node.ChildNodes)
            {
                if (XmlNodeType.Element == child.NodeType)
                {
                    if (child.NamespaceURI == this.schema.TargetNamespace)
                    {
                        this.Core.UnexpectedElement(node, child);
                    }
                    else
                    {
                        this.Core.UnsupportedExtensionElement(node, child);
                    }
                }
            }

            if (!this.Core.EncounteredError)
            {
                Row row = this.Core.CreateRow(sourceLineNumbers, "HelpFilter");
                row[0] = id;
                row[1] = name;
                row[2] = filterDefinition;

                if (YesNoType.No == suppressCAs)
                {
                    this.Core.CreateWixSimpleReferenceRow(sourceLineNumbers, "CustomAction", "CA_RegisterMicrosoftHelp.3643236F_FC70_11D3_A536_0090278A1BB8");
                }
            }
        }
 protected override Preprocessor Copy(Preprocessor predecessor)
 {
     return(new FeatureIndexReduction(extractIndexes, predecessor));
 }
 protected override Preprocessor Copy(Preprocessor predecessor)
 {
     return(new MagnitudeSpectrumTransform(predecessor));
 }
Beispiel #16
0
        /// <summary>
        /// Main running method for the application.
        /// </summary>
        /// <param name="args">Commandline arguments to the application.</param>
        /// <returns>Returns the application error code.</returns>
        private int Run(string[] args)
        {
            try
            {
                FileInfo currentFile = null;

                // parse the command line
                this.ParseCommandLine(args);

                // exit if there was an error parsing the command line (otherwise the logo appears after error messages)
                if (this.messageHandler.FoundError)
                {
                    return this.messageHandler.PostProcess();
                }

                if (0 == this.sourceFiles.Count)
                {
                    this.showHelp = true;
                }
                else if (1 < this.sourceFiles.Count && null != this.outputFile)
                {
                    throw new ArgumentException("cannot specify more than one source file with single output file.  Either specify an output directory for the -out argument by ending the argument with a '\\' or remove the -out argument to have the source files compiled to the current directory.", "-out");
                }

                if (this.showLogo)
                {
                    Assembly candleAssembly = Assembly.GetExecutingAssembly();

                    Console.WriteLine("Microsoft (R) Windows Installer Xml Compiler version {0}", candleAssembly.GetName().Version.ToString());
                    Console.WriteLine("Copyright (C) Microsoft Corporation 2003. All rights reserved.");
                    Console.WriteLine();
                }
                if (this.showHelp)
                {
                    Console.WriteLine(" usage:  candle.exe [-?] [-nologo] [-out outputFile] sourceFile [sourceFile ...]");
                    Console.WriteLine();
                    Console.WriteLine("   -d<name>=<value>  define a parameter for the preprocessor");
                    Console.WriteLine("   -p<file>  preprocess to a file (or stdout if no file supplied)");
                    Console.WriteLine("   -I<dir>  add to include search path");
                    Console.WriteLine("   -nologo  skip printing candle logo information");
                    Console.WriteLine("   -out     specify output file (default: write to current directory)");
                    Console.WriteLine("   -pedantic:<level>  pedantic checks (levels: easy, heroic, legendary)");
                    Console.WriteLine("   -ss      suppress schema validation of documents (performance boost)");
                    Console.WriteLine("   -ust     use small table definitions (for backwards compatiblity)");
                    Console.WriteLine("   -trace   show source trace for errors, warnings, and verbose messages");
                    Console.WriteLine("   -ext     extension (class, assembly), should extend CompilerExtension");
                    Console.WriteLine("   -zs      only do validation of documents (no output)");
                    Console.WriteLine("   -wx      treat warnings as errors");
                    Console.WriteLine("   -w<N>    set the warning level (0: show all, 3: show none)");
                    Console.WriteLine("   -sw      suppress all warnings (same as -w3)");
                    Console.WriteLine("   -sw<N>   suppress warning with specific message ID");
                    Console.WriteLine("   -v       verbose output (same as -v2)");
                    Console.WriteLine("   -v<N>    sets the level of verbose output (0: most output, 3: none)");
                    Console.WriteLine("   -?       this help information");
                    Console.WriteLine();
                    Console.WriteLine("Common extensions:");
                    Console.WriteLine("   .wxs    - Windows installer Xml Source file");
                    Console.WriteLine("   .wxi    - Windows installer Xml Include file");
                    Console.WriteLine("   .wxl    - Windows installer Xml Localization file");
                    Console.WriteLine("   .wixobj - Windows installer Xml Object file (in XML format)");
                    Console.WriteLine("   .wixlib - Windows installer Xml Library file (in XML format)");
                    Console.WriteLine("   .wixout - Windows installer Xml Output file (in XML format)");
                    Console.WriteLine();
                    Console.WriteLine("   .msm - Windows installer Merge Module");
                    Console.WriteLine("   .msi - Windows installer Product Database");
                    Console.WriteLine("   .mst - Windows installer Transform");
                    Console.WriteLine("   .pcp - Windows installer Patch Creation Package");
                    Console.WriteLine();
                    Console.WriteLine("For more information see: http://wix.sourceforge.net");

                    return this.messageHandler.PostProcess();
                }

                // create the preprocessor and compiler
                Preprocessor preprocessor = new Preprocessor();
                preprocessor.Message += new MessageEventHandler(this.messageHandler.Display);
                for (int i = 0; i < this.includeSearchPaths.Count; ++i)
                {
                    preprocessor.IncludeSearchPaths.Add(this.includeSearchPaths[i]);
                }

                Compiler compiler = new Compiler(this.useSmallTables);
                compiler.Message += new MessageEventHandler(this.messageHandler.Display);
                compiler.PedanticLevel = this.pedanticLevel;
                compiler.SuppressValidate = this.suppressSchema;

                // load any extensions
                foreach (string extension in this.extensionList)
                {
                    Type extensionType = Type.GetType(extension);
                    if (null == extensionType)
                    {
                        throw new WixInvalidExtensionException(extension);
                    }

                    if (extensionType.IsSubclassOf(typeof(PreprocessorExtension)))
                    {
                        preprocessor.AddExtension((PreprocessorExtension)Activator.CreateInstance(extensionType));
                    }

                    if (extensionType.IsSubclassOf(typeof(CompilerExtension)))
                    {
                        CompilerExtension compilerExtensionObject = Activator.CreateInstance(extensionType) as CompilerExtension;
                        compiler.AddExtension(compilerExtensionObject);
                    }

                    if (!extensionType.IsSubclassOf(typeof(PreprocessorExtension)) && !extensionType.IsSubclassOf(typeof(CompilerExtension)))
                    {
                        throw new WixInvalidExtensionException(extension);
                    }
                }

                // preprocess then compile each source file
                foreach (FileInfo sourceFile in this.sourceFiles)
                {
                    currentFile = sourceFile; // point at the file we're working on in case a exception is thrown

                    FileInfo targetFile;
                    if (null != this.outputFile)
                    {
                        targetFile = this.outputFile;
                    }
                    else if (null != this.outputDirectory)
                    {
                        targetFile = new FileInfo(String.Concat(this.outputDirectory.FullName, Path.ChangeExtension(currentFile.Name, ".wixobj")));
                    }
                    else
                    {
                        targetFile = new FileInfo(Path.ChangeExtension(currentFile.Name, ".wixobj"));
                    }

                    // print friendly message saying what file is being compiled
                    Console.WriteLine(currentFile.Name);

                    // need to clear and re-add the commandline defines for each file
                    preprocessor.ResetParameters();
                    foreach (string param in this.parameters.Keys)
                    {
                        string name = param;
                        if (!name.StartsWith("var."))
                        {
                            name = String.Concat("var.", name);
                        }
                        preprocessor.Parameters.Add(name, (string)this.parameters[param]);
                    }

                    // preprocess the source
                    XmlDocument sourceDocument;
                    try
                    {
                        if (this.preprocessToStdout)
                        {
                            preprocessor.PreprocessOut = Console.Out;
                        }
                        else if (null != this.preprocessFile)
                        {
                            preprocessor.PreprocessOut = new StreamWriter(this.preprocessFile);
                        }

                        sourceDocument = preprocessor.Process(currentFile.FullName);
                    }
                    finally
                    {
                        if (null != preprocessor.PreprocessOut && Console.Out != preprocessor.PreprocessOut)
                        {
                            preprocessor.PreprocessOut.Close();
                        }
                    }

                    // if we're not actually going to compile anything, move on to the next file
                    if (this.schemaOnly || null == sourceDocument || this.preprocessToStdout || null != this.preprocessFile)
                    {
                        continue;
                    }

                    // and now we do what we came here to do...
                    Intermediate intermediate = compiler.Compile(sourceDocument, currentFile.FullName);

                    // save the intermediate to disk if no errors were found for this source file
                    if (null != intermediate)
                    {
                        intermediate.Save(targetFile.FullName);
                    }

                    // this file is was successful so clear the reference in case an exception gets thrown
                    currentFile = null;
                }
            }
            catch (WixException we)
            {
                // TODO: once all WixExceptions are converted to errors, this clause
                // should be a no-op that just catches WixFatalErrorException's
                this.messageHandler.Display("candle.exe", "CNDL", we);
                return 1;
            }
            catch (Exception e)
            {
                this.OnMessage(WixErrors.UnexpectedException(e.Message, e.GetType().ToString(), e.StackTrace));
                if (e is NullReferenceException || e is SEHException)
                {
                    throw;
                }
            }

            return this.messageHandler.PostProcess();
        }
Beispiel #17
0
        /// <summary>
        /// Parses a WixStandardBootstrapperApplication element for Bundles.
        /// </summary>
        /// <param name="node">The element to parse.</param>
        private void ParseWixStandardBootstrapperApplicationElement(XmlNode node)
        {
            SourceLineNumberCollection sourceLineNumbers = Preprocessor.GetSourceLineNumbers(node);
            string    launchTarget           = null;
            string    launchTargetElevatedId = null;
            string    launchArguments        = null;
            YesNoType launchHidden           = YesNoType.NotSet;
            string    launchWorkingDir       = null;
            string    licenseFile            = null;
            string    licenseUrl             = null;
            string    logoFile                 = null;
            string    logoSideFile             = null;
            string    themeFile                = null;
            string    localizationFile         = null;
            YesNoType suppressOptionsUI        = YesNoType.NotSet;
            YesNoType suppressDowngradeFailure = YesNoType.NotSet;
            YesNoType suppressRepair           = YesNoType.NotSet;
            YesNoType showVersion              = YesNoType.NotSet;
            YesNoType supportCacheOnly         = YesNoType.NotSet;
            YesNoType showFilesInUse           = YesNoType.NotSet;

            foreach (XmlAttribute attrib in node.Attributes)
            {
                if (0 == attrib.NamespaceURI.Length || attrib.NamespaceURI == this.schema.TargetNamespace)
                {
                    switch (attrib.LocalName)
                    {
                    case "LaunchTarget":
                        launchTarget = this.Core.GetAttributeValue(sourceLineNumbers, attrib, false);
                        break;

                    case "LaunchTargetElevatedId":
                        launchTargetElevatedId = this.Core.GetAttributeIdentifierValue(sourceLineNumbers, attrib);
                        break;

                    case "LaunchArguments":
                        launchArguments = this.Core.GetAttributeValue(sourceLineNumbers, attrib, false);
                        break;

                    case "LaunchHidden":
                        launchHidden = this.Core.GetAttributeYesNoValue(sourceLineNumbers, attrib);
                        break;

                    case "LaunchWorkingFolder":
                        launchWorkingDir = this.Core.GetAttributeValue(sourceLineNumbers, attrib, false);
                        break;

                    case "LicenseFile":
                        licenseFile = this.Core.GetAttributeValue(sourceLineNumbers, attrib, false);
                        break;

                    case "LicenseUrl":
                        licenseUrl = this.Core.GetAttributeValue(sourceLineNumbers, attrib, true);
                        break;

                    case "LogoFile":
                        logoFile = this.Core.GetAttributeValue(sourceLineNumbers, attrib, false);
                        break;

                    case "LogoSideFile":
                        logoSideFile = this.Core.GetAttributeValue(sourceLineNumbers, attrib, false);
                        break;

                    case "ThemeFile":
                        themeFile = this.Core.GetAttributeValue(sourceLineNumbers, attrib, false);
                        break;

                    case "LocalizationFile":
                        localizationFile = this.Core.GetAttributeValue(sourceLineNumbers, attrib, false);
                        break;

                    case "SuppressOptionsUI":
                        suppressOptionsUI = this.Core.GetAttributeYesNoValue(sourceLineNumbers, attrib);
                        break;

                    case "SuppressDowngradeFailure":
                        suppressDowngradeFailure = this.Core.GetAttributeYesNoValue(sourceLineNumbers, attrib);
                        break;

                    case "SuppressRepair":
                        suppressRepair = this.Core.GetAttributeYesNoValue(sourceLineNumbers, attrib);
                        break;

                    case "ShowVersion":
                        showVersion = this.Core.GetAttributeYesNoValue(sourceLineNumbers, attrib);
                        break;

                    case "SupportCacheOnly":
                        supportCacheOnly = this.Core.GetAttributeYesNoValue(sourceLineNumbers, attrib);
                        break;

                    case "ShowFilesInUse":
                        showFilesInUse = this.Core.GetAttributeYesNoValue(sourceLineNumbers, attrib);
                        break;

                    default:
                        this.Core.UnexpectedAttribute(sourceLineNumbers, attrib);
                        break;
                    }
                }
                else
                {
                    this.Core.UnsupportedExtensionAttribute(sourceLineNumbers, attrib);
                }
            }

            foreach (XmlNode child in node.ChildNodes)
            {
                if (XmlNodeType.Element == child.NodeType)
                {
                    if (child.NamespaceURI == this.schema.TargetNamespace)
                    {
                        this.Core.UnexpectedElement(node, child);
                    }
                    else
                    {
                        this.Core.UnsupportedExtensionElement(node, child);
                    }
                }
            }

            if (String.IsNullOrEmpty(licenseFile) && null == licenseUrl)
            {
                this.Core.OnMessage(WixErrors.ExpectedAttribute(sourceLineNumbers, node.Name, "LicenseFile", "LicenseUrl", true));
            }

            if (!this.Core.EncounteredError)
            {
                if (!String.IsNullOrEmpty(launchTarget))
                {
                    this.Core.CreateVariableRow(sourceLineNumbers, "LaunchTarget", launchTarget, "string", false, false);
                }

                if (!String.IsNullOrEmpty(launchTargetElevatedId))
                {
                    this.Core.CreateVariableRow(sourceLineNumbers, "LaunchTargetElevatedId", launchTargetElevatedId, "string", false, false);
                }

                if (!String.IsNullOrEmpty(launchArguments))
                {
                    this.Core.CreateVariableRow(sourceLineNumbers, "LaunchArguments", launchArguments, "string", false, false);
                }

                if (YesNoType.Yes == launchHidden)
                {
                    this.Core.CreateVariableRow(sourceLineNumbers, "LaunchHidden", "yes", "string", false, false);
                }

                if (!String.IsNullOrEmpty(launchWorkingDir))
                {
                    this.Core.CreateVariableRow(sourceLineNumbers, "LaunchWorkingFolder", launchWorkingDir, "string", false, false);
                }

                if (!String.IsNullOrEmpty(licenseFile))
                {
                    this.Core.CreateWixVariableRow(sourceLineNumbers, "WixStdbaLicenseRtf", licenseFile, false);
                }

                if (null != licenseUrl)
                {
                    this.Core.CreateWixVariableRow(sourceLineNumbers, "WixStdbaLicenseUrl", licenseUrl, false);
                }

                if (!String.IsNullOrEmpty(logoFile))
                {
                    this.Core.CreateWixVariableRow(sourceLineNumbers, "WixStdbaLogo", logoFile, false);
                }

                if (!String.IsNullOrEmpty(logoSideFile))
                {
                    this.Core.CreateWixVariableRow(sourceLineNumbers, "WixStdbaLogoSide", logoSideFile, false);
                }

                if (!String.IsNullOrEmpty(themeFile))
                {
                    this.Core.CreateWixVariableRow(sourceLineNumbers, "WixStdbaThemeXml", themeFile, false);
                }

                if (!String.IsNullOrEmpty(localizationFile))
                {
                    this.Core.CreateWixVariableRow(sourceLineNumbers, "WixStdbaThemeWxl", localizationFile, false);
                }

                if (YesNoType.Yes == suppressOptionsUI || YesNoType.Yes == suppressDowngradeFailure || YesNoType.Yes == suppressRepair || YesNoType.Yes == showVersion || YesNoType.Yes == supportCacheOnly || YesNoType.Yes == showFilesInUse)
                {
                    Row row = this.Core.CreateRow(sourceLineNumbers, "WixStdbaOptions");
                    if (YesNoType.Yes == suppressOptionsUI)
                    {
                        row[0] = 1;
                    }

                    if (YesNoType.Yes == suppressDowngradeFailure)
                    {
                        row[1] = 1;
                    }

                    if (YesNoType.Yes == suppressRepair)
                    {
                        row[2] = 1;
                    }

                    if (YesNoType.Yes == showVersion)
                    {
                        row[3] = 1;
                    }

                    if (YesNoType.Yes == showFilesInUse)
                    {
                        row[4] = 1;
                    }

                    if (YesNoType.Yes == supportCacheOnly)
                    {
                        row[5] = 1;
                    }
                }
            }
        }
Beispiel #18
0
        /// <summary>
        /// Main running method for the application.
        /// </summary>
        /// <param name="args">Commandline arguments to the application.</param>
        /// <returns>Returns the application error code.</returns>
        private int Run(string[] args)
        {
            try
            {
                // parse the command line
                this.ParseCommandLine(args);

                // exit if there was an error parsing the command line (otherwise the logo appears after error messages)
                if (this.messageHandler.EncounteredError)
                {
                    return this.messageHandler.LastErrorNumber;
                }

                if (!this.fipsCompliant)
                {
                    try
                    {
                        System.Security.Cryptography.MD5.Create();
                    }
                    catch (TargetInvocationException)
                    {
                        this.messageHandler.Display(this, WixErrors.UseFipsArgument());
                        return this.messageHandler.LastErrorNumber;
                    }
                }

                if (0 == this.sourceFiles.Count)
                {
                    this.showHelp = true;
                }
                else if (1 < this.sourceFiles.Count && null != this.outputFile)
                {
                    throw new ArgumentException(CandleStrings.CannotSpecifyMoreThanOneSourceFileForSingleTargetFile, "-out");
                }

                if (this.showLogo)
                {
                    AppCommon.DisplayToolHeader();
                }

                if (this.showHelp)
                {
                    Console.WriteLine(CandleStrings.HelpMessage);
                    AppCommon.DisplayToolFooter();
                    return this.messageHandler.LastErrorNumber;
                }

                foreach (string parameter in this.invalidArgs)
                {
                    this.messageHandler.Display(this, WixWarnings.UnsupportedCommandLineArgument(parameter));
                }
                this.invalidArgs = null;

                // create the preprocessor and compiler
                Preprocessor preprocessor = new Preprocessor();
                preprocessor.Message += new MessageEventHandler(this.messageHandler.Display);
                for (int i = 0; i < this.includeSearchPaths.Count; ++i)
                {
                    preprocessor.IncludeSearchPaths.Add(this.includeSearchPaths[i]);
                }
                preprocessor.CurrentPlatform = this.platform;

                Compiler compiler = new Compiler();
                compiler.Message += new MessageEventHandler(this.messageHandler.Display);
                compiler.SuppressFilesVitalByDefault = this.suppressFilesVitalByDefault;
                compiler.ShowPedanticMessages = this.showPedanticMessages;
                compiler.SuppressValidate = this.suppressSchema;
                compiler.CurrentPlatform = this.platform;
                compiler.FipsCompliant = this.fipsCompliant;

                // load any extensions
                foreach (string extension in this.extensionList)
                {
                    WixExtension wixExtension = WixExtension.Load(extension);

                    preprocessor.AddExtension(wixExtension);
                    compiler.AddExtension(wixExtension);
                }

                // preprocess then compile each source file
                Dictionary<string, List<string>> sourcesForOutput = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);
                foreach (string sourceFileOrig in this.sourceFiles)
                {
                    string sourceFile = sourceFileOrig;
                    string targetFile = null;

                    if (this.allowPerSourceOutputSpecification)
                    {
                        string[] parts = sourceFileOrig.Split(Candle.sourceOutputSeparator, 2);
                        if (2 == parts.Length)
                        {
                            sourceFile = parts[0];
                            targetFile = parts[1];
                        }
                    }

                    string sourceFilePath = Path.GetFullPath(sourceFile);
                    string sourceFileName = Path.GetFileName(sourceFile);

                    if (null == targetFile)
                    {
                        if (null != this.outputFile)
                        {
                            targetFile = this.outputFile;
                        }
                        else if (null != this.outputDirectory)
                        {
                            targetFile = Path.Combine(this.outputDirectory, Path.ChangeExtension(sourceFileName, ".wixobj"));
                        }
                        else
                        {
                            targetFile = Path.ChangeExtension(sourceFileName, ".wixobj");
                        }
                    }
                    else if (!Path.IsPathRooted(targetFile) && null != this.outputDirectory)
                    {
                        targetFile = Path.Combine(this.outputDirectory, targetFile);
                    }

                    // print friendly message saying what file is being compiled
                    Console.WriteLine(sourceFileName);

                    // preprocess the source
                    XmlDocument sourceDocument;
                    try
                    {
                        if (this.preprocessToStdout)
                        {
                            preprocessor.PreprocessOut = Console.Out;
                        }
                        else if (null != this.preprocessFile)
                        {
                            preprocessor.PreprocessOut = new StreamWriter(this.preprocessFile);
                        }

                        sourceDocument = preprocessor.Process(sourceFilePath, this.parameters);
                    }
                    finally
                    {
                        if (null != preprocessor.PreprocessOut && Console.Out != preprocessor.PreprocessOut)
                        {
                            preprocessor.PreprocessOut.Close();
                        }
                    }

                    // if we're not actually going to compile anything, move on to the next file
                    if (null == sourceDocument || this.preprocessToStdout || null != this.preprocessFile)
                    {
                        continue;
                    }

                    // and now we do what we came here to do...
                    Intermediate intermediate = compiler.Compile(sourceDocument);

                    // save the intermediate to disk if no errors were found for this source file
                    if (null != intermediate)
                    {
                        intermediate.Save(targetFile);
                    }

                    // Track which source files result in a given output file, to ensure we aren't
                    // overwriting the output.
                    List<string> sources = null;
                    string targetPath = Path.GetFullPath(targetFile);
                    if (!sourcesForOutput.TryGetValue(targetPath, out sources))
                    {
                        sources = new List<string>();
                        sourcesForOutput.Add(targetPath, sources);
                    }
                    sources.Add(sourceFile);
                }

                // Show an error for every output file that had more than 1 source file.
                foreach (KeyValuePair<string, List<string>> outputSources in sourcesForOutput)
                {
                    if (1 < outputSources.Value.Count)
                    {
                        string sourceFiles = CompilerCore.CreateValueList(ValueListKind.None, outputSources.Value);
                        this.messageHandler.Display(this, WixErrors.DuplicateSourcesForOutput(sourceFiles, outputSources.Key));
                    }
                }

            }
            catch (WixException we)
            {
                this.messageHandler.Display(this, we.Error);
            }
            catch (Exception e)
            {
                this.messageHandler.Display(this, WixErrors.UnexpectedException(e.Message, e.GetType().ToString(), e.StackTrace));
                if (e is NullReferenceException || e is SEHException)
                {
                    throw;
                }
            }

            return this.messageHandler.LastErrorNumber;
        }
Beispiel #19
0
        private void btnSaveRun_Click(object sender, EventArgs e)
        {
            using (SaveFileDialog dlgSave = new SaveFileDialog())
            {
                dlgSave.AddExtension = true;
                dlgSave.DefaultExt = "erun";
                dlgSave.Filter = "ENFORM run file(*.erun)|*.erun";
                dlgSave.Title = "Save run file as...";
                if (dlgSave.ShowDialog() == DialogResult.OK)
                {
                    BackgroundWorker worker = new BackgroundWorker();
                    worker.WorkerReportsProgress = true;
                    worker.DoWork += new DoWorkEventHandler(worker_DoWork);
                    worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
                    worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);

                    this.Enabled = false;
                    dlgProgress = new frmProgressDialog();
                    dlgProgress.Show(this);
                    dlgProgress.Title = "Saving run file...";

                    Preprocessor preprocessor = new Preprocessor();
                    preprocessor.Bradley = chkBradley.Checked;
                    preprocessor.ContrastAdjustment = chkContrast.Checked;
                    preprocessor.ContrastStrength = numContrast.Value;
                    preprocessor.ContrastStretch = chkContastStretch.Checked;
                    preprocessor.FilterLevel = filterLevel;
                    preprocessor.Gaussian = chkGaussian.Checked;
                    preprocessor.GaussianStrength = numBlurStrength.Value;
                    preprocessor.Greyscale = chkGreyscale.Checked;
                    preprocessor.Histogram = chkHistogram.Checked;
                    preprocessor.ImageSize = new Size(Int32.Parse(txtWidth.Text), Int32.Parse(txtHeight.Text));
                    preprocessor.KeepAspectRatio = chkAspect.Checked;
                    preprocessor.ScalingMethod = (ScalingMethods)cmbScalingMethod.SelectedIndex;
                    preprocessor.Threshold = chkThreshold.Checked;
                    preprocessor.ThresholdStrength = numThreshold.Value;

                    Utils.Logger.Log("Caching all images to store in run file...");
                    if (chkEmbed.Checked)
                    {
                        //cacheAll();
                    }

                    DataAccess dataAccess = new DataAccess(dlgSave.FileName);
                    Utils.Logger.Log("Clearing database data...");
                    dataAccess.ClearFile();
                    Utils.Logger.Log("Adding input groups...");
                    for (int i = 0; i < lstInputGroups.Items.Count; i++)
                    {
                        dataAccess.AddInputGroup(i, (InputGroup)lstInputGroups.Items[i]);
                    }

                    worker.RunWorkerAsync(new object[] {dataAccess,preprocessor});

                }

            }
        }
Beispiel #20
0
        private static void Assemble(ILog log)
        {
            TextReader input;
            bool       inputIsFile;

            if (Program.RunConfig.inputFile != null)
            {
                input       = File.OpenText(Program.RunConfig.inputFile);
                inputIsFile = false;
            }
            else
            {
                input       = Console.In;
                inputIsFile = true;
            }

            using (IDirectivePreprocessor preprocessor = new Preprocessor(log)) {
                // preprocessor.AddReserved (eaCodeLanguage.GetCodeNames ());
                preprocessor.AddDefined(new string[] { "_" + Program.RunConfig.language + "_", "_EA_" });

                DependencyMakingIncludeListener depMaker = null;

                if (Program.RunConfig.ppDepEnable)
                {
                    depMaker = new DependencyMakingIncludeListener();
                    preprocessor.IncludeListener = depMaker;
                }

                using (IInputStream inputStream = new PreprocessingInputStream(input, preprocessor)) {
                    if (Program.RunConfig.ppSimulation)
                    {
                        // preprocess to null output
                        while (inputStream.ReadLine() != null)
                        {
                            ;
                        }
                    }
                    else
                    {
                        if (Program.RunConfig.outputFile == null)
                        {
                            log.AddError("No output file specified for assembly.");
                            return;
                        }

                        string outFile = Program.RunConfig.outputFile;

                        if (File.Exists(outFile) && File.GetAttributes(outFile).HasFlag((Enum)FileAttributes.ReadOnly))
                        {
                            log.AddError("File `{0}` exists and cannot be written to.", outFile);
                            return;
                        }

                        ChangeStream changeStream = new ChangeStream();

                        using (BinaryWriter output = new BinaryWriter((Stream)changeStream)) {
                            if (!Program.CodesLoaded)
                            {
                                LoadCodes(false);
                            }

                            EACodeLanguage language = Program.Languages [Program.RunConfig.language];

                            EAExpressionAssembler assembler = new EAExpressionAssembler(language.CodeStorage, new TokenParser <int> (new Func <string, int> (StringExtensions.GetValue)));
                            assembler.Assemble(inputStream, output, log);

                            if (Program.RunConfig.symbolOutputFile != null)
                            {
                                // Outputting global symbols to another file

                                try {
                                    if (File.Exists(Program.RunConfig.symbolOutputFile))
                                    {
                                        File.Delete(Program.RunConfig.symbolOutputFile);
                                    }

                                    using (FileStream fileStream = File.OpenWrite(Program.RunConfig.symbolOutputFile))
                                        using (StreamWriter symOut = new StreamWriter(fileStream))
                                            foreach (KeyValuePair <string, int> symbol in assembler.GetGlobalSymbols())
                                            {
                                                symOut.WriteLine("{0}={1}", symbol.Key, symbol.Value.ToHexString("$"));
                                            }
                                } catch (Exception e) {
                                    log.AddError(e.ToString());
                                }
                            }
                        }

                        if (log.ErrorCount == 0)
                        {
                            using (Stream stream = (Stream)File.OpenWrite(outFile))
                                changeStream.WriteToFile(stream);
                        }
                    }
                }

                if (depMaker != null)
                {
                    try {
                        depMaker.GenerateMakeDependencies(log);
                    } catch (Exception e) {
                        log.AddError(e.ToString());
                    }
                }
            }

            if (inputIsFile)
            {
                input.Close();
            }
        }
		private void doTest(String test) {
			var userDir = System.getProperty("user.dir");
			var sourcePath = PathHelper.combine(PathHelper.combine(userDir, "tests/resources/PreprocessorTest/sources"), test + ".stab.cs");
			var fileReader = new InputStreamReader(new FileInputStream((sourcePath)), Charset.forName("UTF-8"));
			var code = readToEnd(fileReader);
			var preprocessor = new Preprocessor(new CodeErrorManager(), code.toCharArray());
			var source = preprocessor.preprocess();
			var result = preprocessedTextToString(source);
			
			var generatedPath = PathHelper.combine(userDir, "tests/resources/PreprocessorTest/generated");
			var generatedDir = new File(generatedPath);
			if (!generatedDir.exists()) {
				generatedDir.mkdir();
			}
			var fileWriter = new FileWriter(PathHelper.combine(generatedPath, test + ".txt"));
			fileWriter.write(result);
			fileWriter.close();
			
			var expectedPath = PathHelper.combine(userDir, "tests/resources/PreprocessorTest/expected");
			var expectedFile = new File(PathHelper.combine(expectedPath, test + ".txt"));
			Assert.assertTrue("Expected file not found: " + expectedFile, expectedFile.exists());
			fileReader = new InputStreamReader(new FileInputStream((expectedFile)), Charset.forName("UTF-8"));
			var reference = readToEnd(fileReader);
			
			var genReader = new BufferedReader(new StringReader(result));
			var refReader = new BufferedReader(new StringReader(reference));
			for (;;) {
				var genLine = genReader.readLine();
				var refLine = refReader.readLine();
				if (genLine == null && refLine == null) {
					break;
				}
				Assert.assertEquals(refLine, genLine);
			}
		}
Beispiel #22
0
        /// <summary>
        /// Parses a UnitTest element to create Lux unit tests.
        /// </summary>
        /// <param name="node">The element to parse.</param>
        /// <param name="args">Used while parsing multi-value property tests to pass values from the parent element.</param>
        private void ParseUnitTestElement(XmlNode node, string mutation, params string[] args)
        {
            SourceLineNumberCollection sourceLineNumbers = Preprocessor.GetSourceLineNumbers(node);
            bool     multiValue   = 0 < args.Length;
            string   id           = null;
            string   action       = multiValue ? args[0] : null;
            string   property     = multiValue ? args[1] : null;
            string   op           = null;
            Operator oper         = Operator.NotSet;
            string   value        = null;
            string   expression   = null;
            string   valueSep     = multiValue ? args[2] : null;
            string   nameValueSep = multiValue ? args[3] : null;
            string   condition    = null;
            string   index        = null;

            foreach (XmlAttribute attrib in node.Attributes)
            {
                if (0 == attrib.NamespaceURI.Length || attrib.NamespaceURI == this.schema.TargetNamespace)
                {
                    switch (attrib.LocalName)
                    {
                    case "CustomAction":
                    case "Property":
                    case "Expression":
                    case "ValueSeparator":
                    case "NameValueSeparator":
                        if (multiValue)
                        {
                            this.Core.OnMessage(LuxErrors.IllegalAttributeWhenNested(sourceLineNumbers, node.LocalName, attrib.LocalName));
                        }
                        break;
                    }

                    switch (attrib.LocalName)
                    {
                    case "Id":
                        id = this.Core.GetAttributeIdentifierValue(sourceLineNumbers, attrib);
                        break;

                    case "CustomAction":
                        action = this.Core.GetAttributeIdentifierValue(sourceLineNumbers, attrib);
                        break;

                    case "Property":
                        property = this.Core.GetAttributeIdentifierValue(sourceLineNumbers, attrib);
                        break;

                    case "Operator":
                        op = this.Core.GetAttributeValue(sourceLineNumbers, attrib);
                        if (0 < op.Length)
                        {
                            switch (op)
                            {
                            case "equal":
                                oper = Operator.Equal;
                                break;

                            case "notEqual":
                                oper = Operator.NotEqual;
                                break;

                            case "caseInsensitiveEqual":
                                oper = Operator.CaseInsensitiveEqual;
                                break;

                            case "caseInsensitiveNotEqual":
                                oper = Operator.CaseInsensitiveNotEqual;
                                break;

                            default:
                                this.Core.OnMessage(WixErrors.IllegalAttributeValue(sourceLineNumbers, node.LocalName, attrib.LocalName, op, "equal", "notEqual", "caseInsensitiveEqual", "caseInsensitiveNotEqual"));
                                break;
                            }
                        }
                        break;

                    case "Value":
                        value = this.Core.GetAttributeValue(sourceLineNumbers, attrib);
                        break;

                    case "ValueSeparator":
                        valueSep = this.Core.GetAttributeValue(sourceLineNumbers, attrib);
                        break;

                    case "NameValueSeparator":
                        nameValueSep = this.Core.GetAttributeValue(sourceLineNumbers, attrib);
                        break;

                    case "Index":
                        if (!multiValue)
                        {
                            this.Core.OnMessage(LuxErrors.IllegalAttributeWhenNotNested(sourceLineNumbers, node.LocalName, attrib.LocalName));
                        }
                        index = this.Core.GetAttributeValue(sourceLineNumbers, attrib);
                        break;

                    default:
                        this.Core.UnexpectedAttribute(sourceLineNumbers, attrib);
                        break;
                    }
                }
                else
                {
                    this.Core.UnsupportedExtensionAttribute(sourceLineNumbers, attrib);
                }
            }

            bool isParent = false;

            foreach (XmlNode child in node.ChildNodes)
            {
                if (XmlNodeType.Element == child.NodeType)
                {
                    if (child.NamespaceURI == this.schema.TargetNamespace)
                    {
                        switch (child.LocalName)
                        {
                        case "Condition":
                            // the condition should not be empty
                            condition = CompilerCore.GetConditionInnerText(child);
                            if (null == condition || 0 == condition.Length)
                            {
                                condition = null;
                                this.Core.OnMessage(WixErrors.ConditionExpected(sourceLineNumbers, child.Name));
                            }
                            break;

                        case "Expression":
                            // the expression should not be empty
                            expression = CompilerCore.GetConditionInnerText(child);
                            if (null == expression || 0 == expression.Length)
                            {
                                expression = null;
                                this.Core.OnMessage(WixErrors.ConditionExpected(sourceLineNumbers, child.Name));
                            }
                            break;

                        case "UnitTest":
                            if (multiValue)
                            {
                                SourceLineNumberCollection childSourceLineNumbers = Preprocessor.GetSourceLineNumbers(node);
                                this.Core.OnMessage(LuxErrors.ElementTooDeep(childSourceLineNumbers, child.LocalName, node.LocalName));
                            }

                            this.ParseUnitTestElement(child, mutation, action, property, valueSep, nameValueSep);
                            isParent = true;
                            break;

                        default:
                            this.Core.UnexpectedElement(node, child);
                            break;
                        }
                    }
                    else
                    {
                        this.Core.UnsupportedExtensionElement(node, child);
                    }
                }
            }

            if (isParent)
            {
                if (!String.IsNullOrEmpty(value))
                {
                    this.Core.OnMessage(LuxErrors.IllegalAttributeWhenNested(sourceLineNumbers, node.LocalName, "Value"));
                }
            }
            else
            {
                // the children generate multi-value unit test rows; the parent doesn't generate anything

                if (!String.IsNullOrEmpty(property) && String.IsNullOrEmpty(value))
                {
                    this.Core.OnMessage(WixErrors.IllegalAttributeWithoutOtherAttributes(sourceLineNumbers, node.LocalName, "Property", "Value"));
                }

                if (!String.IsNullOrEmpty(property) && !String.IsNullOrEmpty(expression))
                {
                    this.Core.OnMessage(WixErrors.IllegalAttributeWithOtherAttribute(sourceLineNumbers, node.LocalName, "Property", "Expression"));
                }

                if (multiValue && String.IsNullOrEmpty(valueSep) && String.IsNullOrEmpty(nameValueSep))
                {
                    this.Core.OnMessage(LuxErrors.MissingRequiredParentAttribute(sourceLineNumbers, node.LocalName, "ValueSeparator", "NameValueSeparator"));
                }

                if (!String.IsNullOrEmpty(valueSep) && !String.IsNullOrEmpty(nameValueSep))
                {
                    this.Core.OnMessage(WixErrors.IllegalAttributeWithOtherAttribute(sourceLineNumbers, node.LocalName, "ValueSeparator", "NameValueSeparator"));
                }

                if (!this.Core.EncounteredError)
                {
                    if (String.IsNullOrEmpty(id))
                    {
                        id = this.Core.GenerateIdentifier("lux", action, property, index, condition, mutation);
                    }

                    if (Operator.NotSet == oper)
                    {
                        oper = Operator.Equal;
                    }

                    Row row = this.Core.CreateRow(sourceLineNumbers, "WixUnitTest");
                    row[0] = id;
                    row[1] = action;
                    row[2] = property;
                    row[3] = (int)oper;
                    row[4] = value;
                    row[5] = expression;
                    row[6] = condition;
                    row[7] = valueSep;
                    row[8] = nameValueSep;
                    row[9] = index;
                    if (!string.IsNullOrEmpty(mutation))
                    {
                        row[10] = mutation;
                    }

                    this.Core.CreateWixSimpleReferenceRow(sourceLineNumbers, "CustomAction", action);
                    this.Core.CreateWixSimpleReferenceRow(sourceLineNumbers, "CustomAction", "WixRunImmediateUnitTests");
                }
            }
        }
Beispiel #23
0
        /// <summary>
        /// Parses the command line arguments.
        /// </summary>
        /// <param name="args">The arguments.</param>
        /// <param name="preprocessor">The preprocessor.</param>
        /// <param name="hasErrors">If set to <c>true</c>, the command line had errors.</param>
        /// <returns>The resulting command.</returns>
        public static Command Parse(string[] args, Preprocessor preprocessor, out bool hasErrors)
        {
            // Construct a mapping of command names to commands
            List <Tuple <string, Command> > commands = Commands
                                                       .Select(x =>
            {
                string commandName = x.GetType().Name.ToLowerInvariant();
                commandName        = commandName.EndsWith("command")
                        ? commandName.Substring(0, commandName.Length - 7)
                        : commandName;
                return(Tuple.Create(commandName, x));
            })
                                                       .ToList();

            // If the first argument is not a valid command, set it to the first command as a default
            // Make sure to allow the default help flags to handle help output
            List <string> arguments = args == null ? new List <string>() : new List <string>(args);

            if (arguments.Count == 0)
            {
                arguments.Add(commands[0].Item1);
            }
            else if (arguments[0] != "-?" &&
                     !arguments[0].Equals("-h", StringComparison.OrdinalIgnoreCase) &&
                     !arguments[0].Equals("--help", StringComparison.OrdinalIgnoreCase) &&
                     commands.All(x => !x.Item1.Equals(arguments[0], StringComparison.OrdinalIgnoreCase)))
            {
                arguments.Insert(0, commands[0].Item1);
            }
            else if (arguments.Count == 1 && arguments[0].Equals("help", StringComparison.OrdinalIgnoreCase))
            {
                // Special case for the help command without any additional arguments, output global help instead
                arguments[0] = "--help";
            }

            // If the first arg is a command, convert it to lowercase
            // TODO: Add feature to upstream System.CommandLine to ignore case of commands, options, and arguments then remove this
            if (commands.Any(x => x.Item1.Equals(arguments[0], StringComparison.OrdinalIgnoreCase)))
            {
                arguments[0] = arguments[0].ToLowerInvariant();
            }

            // Parse the command line arguments
            Command        command = null;
            ArgumentSyntax parsed  = ArgumentSyntax.Parse(arguments, syntax =>
            {
                // Add all commands
                foreach (Tuple <string, Command> cmd in commands)
                {
                    syntax.DefineCommand(cmd.Item1, ref command, cmd.Item2, cmd.Item2.Description);
                    cmd.Item2.Parse(syntax, preprocessor);
                }
            });

            hasErrors = parsed.HasErrors;

            // Output help text for any directive that got used for this command
            if (parsed.IsHelpRequested() && command?.SupportedDirectives != null)
            {
                foreach (IDirective directive in preprocessor.Directives
                         .Where(x => command.SupportedDirectives.Contains(x.Name, StringComparer.OrdinalIgnoreCase)))
                {
                    string helpText = directive.GetHelpText();
                    if (!string.IsNullOrEmpty(helpText))
                    {
                        Console.WriteLine($"--{directive.Name} usage:");
                        Console.WriteLine();
                        Console.WriteLine(directive.GetHelpText());
                        Console.WriteLine();
                    }
                }
            }

            if (parsed.IsHelpRequested() || hasErrors)
            {
                return(null);
            }
            Trace.Information($"**{commands.First(x => x.Item2 == command).Item1.ToUpperInvariant()}**");
            return(command);
        }
Beispiel #24
0
 internal static BcProgram Parse(params string[] inputs)
 => Parser.Parse(Preprocessor.Preprocess(inputs.ToList()));
Beispiel #25
0
 internal static List <LineOfCode> Preprocess(string input)
 => Preprocessor.Preprocess(new List <string>()
 {
     input
 });
Beispiel #26
0
        /// <summary>
        /// Preprocesses the provided shader or effect source.
        /// </summary>
        /// <param name="shaderSource">An array of bytes containing the raw source of the shader or effect to preprocess.</param>
        /// <param name="sourceFileName">Name of the source file.</param>
        /// <param name="defines">A set of macros to define during preprocessing.</param>
        /// <param name="includeDirectories">The include directories used by the preprocessor.</param>
        /// <returns>
        /// The preprocessed shader source.
        /// </returns>
        public static string Run(string shaderSource, string sourceFileName, ShaderMacro[] defines = null, params string[] includeDirectories)
        {
            var cpp = new Preprocessor();

            cpp.addFeature(Feature.DIGRAPHS);
            cpp.addWarning(Warning.IMPORT);
            cpp.addFeature(Feature.INCLUDENEXT);
            cpp.addFeature(Feature.LINEMARKERS);

            // TODO: Handle warning and errors properly instead of relying only on exception
            // Don't setup a listener and get any errors via exceptions
            cpp.setListener(new ErrorListener());

            // Pass defines
            if (defines != null)
            {
                foreach (var define in defines)
                {
                    if (!string.IsNullOrWhiteSpace(define.Name))
                    {
                        cpp.addMacro(define.Name, define.Definition ?? string.Empty);
                    }
                }
            }

            // Setup input directories.
            var tempDirectories = new List <string>()
            {
                Path.GetDirectoryName(sourceFileName)
            };

            tempDirectories.AddRange(includeDirectories);
            cpp.setQuoteIncludePath(tempDirectories);

            var inputSource = new StringLexerSource(shaderSource, true, sourceFileName);

            cpp.addInput(inputSource);

            var textBuilder = new StringBuilder();

            var isEndOfStream = false;

            while (!isEndOfStream)
            {
                Token tok = cpp.token();
                switch (tok.getType())
                {
                case Token.EOF:
                    isEndOfStream = true;
                    break;

                case Token.CCOMMENT:
                    var strComment = tok.getText() ?? string.Empty;
                    foreach (var commentChar in strComment)
                    {
                        textBuilder.Append(commentChar == '\n' ? '\n' : ' ');
                    }
                    break;

                case Token.CPPCOMMENT:
                    break;

                default:
                    var tokenText = tok.getText();
                    if (tokenText != null)
                    {
                        textBuilder.Append(tokenText);
                    }
                    break;
                }
            }

            return(textBuilder.ToString());
        }
Beispiel #27
0
        /// <summary>
        /// Parses a VsixPackage element.
        /// </summary>
        /// <param name="node">Element to process.</param>
        /// <param name="componentId">Identifier of the parent Component element.</param>
        /// <param name="fileId">Identifier of the parent File element.</param>
        private void ParseVsixPackageElement(XmlNode node, string componentId, string fileId)
        {
            SourceLineNumberCollection sourceLineNumbers = Preprocessor.GetSourceLineNumbers(node);
            string    propertyId    = "VS_VSIX_INSTALLER_PATH";
            string    packageId     = null;
            YesNoType permanent     = YesNoType.NotSet;
            string    target        = null;
            string    targetVersion = null;
            YesNoType vital         = YesNoType.NotSet;

            foreach (XmlAttribute attrib in node.Attributes)
            {
                if (0 == attrib.NamespaceURI.Length || attrib.NamespaceURI == this.schema.TargetNamespace)
                {
                    switch (attrib.LocalName)
                    {
                    case "File":
                        if (String.IsNullOrEmpty(fileId))
                        {
                            fileId = this.Core.GetAttributeIdentifierValue(sourceLineNumbers, attrib);
                        }
                        else
                        {
                            this.Core.OnMessage(WixErrors.IllegalAttributeWhenNested(sourceLineNumbers, node.Name, "File", "File"));
                        }
                        break;

                    case "PackageId":
                        packageId = this.Core.GetAttributeValue(sourceLineNumbers, attrib);
                        break;

                    case "Permanent":
                        permanent = this.Core.GetAttributeYesNoValue(sourceLineNumbers, attrib);
                        break;

                    case "Target":
                        target = this.Core.GetAttributeValue(sourceLineNumbers, attrib);
                        switch (target.ToLowerInvariant())
                        {
                        case "integrated":
                        case "integratedshell":
                            target = "IntegratedShell";
                            break;

                        case "professional":
                            target = "Pro";
                            break;

                        case "premium":
                            target = "Premium";
                            break;

                        case "ultimate":
                            target = "Ultimate";
                            break;

                        case "vbexpress":
                            target = "VBExpress";
                            break;

                        case "vcexpress":
                            target = "VCExpress";
                            break;

                        case "vcsexpress":
                            target = "VCSExpress";
                            break;

                        case "vwdexpress":
                            target = "VWDExpress";
                            break;
                        }
                        break;

                    case "TargetVersion":
                        targetVersion = this.Core.GetAttributeVersionValue(sourceLineNumbers, attrib, true);
                        break;

                    case "Vital":
                        vital = this.Core.GetAttributeYesNoValue(sourceLineNumbers, attrib);
                        break;

                    case "VsixInstallerPathProperty":
                        propertyId = this.Core.GetAttributeIdentifierValue(sourceLineNumbers, attrib);
                        break;

                    default:
                        this.Core.UnexpectedAttribute(sourceLineNumbers, attrib);
                        break;
                    }
                }
                else
                {
                    this.Core.ParseExtensionAttribute(sourceLineNumbers, (XmlElement)node, attrib);
                }
            }

            if (String.IsNullOrEmpty(fileId))
            {
                this.Core.OnMessage(WixErrors.ExpectedAttribute(sourceLineNumbers, node.Name, "File"));
            }

            if (String.IsNullOrEmpty(packageId))
            {
                this.Core.OnMessage(WixErrors.ExpectedAttribute(sourceLineNumbers, node.Name, "PackageId"));
            }

            if (!String.IsNullOrEmpty(target) && String.IsNullOrEmpty(targetVersion))
            {
                this.Core.OnMessage(WixErrors.ExpectedAttribute(sourceLineNumbers, node.Name, "TargetVersion", "Target"));
            }
            else if (String.IsNullOrEmpty(target) && !String.IsNullOrEmpty(targetVersion))
            {
                this.Core.OnMessage(WixErrors.ExpectedAttribute(sourceLineNumbers, node.Name, "Target", "TargetVersion"));
            }

            // find unexpected child elements
            foreach (XmlNode child in node.ChildNodes)
            {
                if (XmlNodeType.Element == child.NodeType)
                {
                    if (child.NamespaceURI == this.schema.TargetNamespace)
                    {
                        this.Core.UnexpectedElement(node, child);
                    }
                    else
                    {
                        this.Core.UnsupportedExtensionElement(node, child);
                    }
                }
            }

            if (!this.Core.EncounteredError)
            {
                // Ensure there is a reference to the AppSearch Property that will find the VsixInstaller.exe.
                this.Core.CreateWixSimpleReferenceRow(sourceLineNumbers, "Property", propertyId);

                // Ensure there is a reference to the package file (even if we are a child under it).
                this.Core.CreateWixSimpleReferenceRow(sourceLineNumbers, "File", fileId);

                string cmdlinePrefix = "/q ";

                if (!String.IsNullOrEmpty(target))
                {
                    cmdlinePrefix = String.Format("{0} /skuName:{1} /skuVersion:{2}", cmdlinePrefix, target, targetVersion);
                }

                string installAfter     = "WriteRegistryValues"; // by default, come after the registry key registration.
                int    installExtraBits = VSCompiler.MsidbCustomActionTypeInScript;

                // If the package is not vital, mark the install action as continue.
                if (vital == YesNoType.No)
                {
                    installExtraBits |= VSCompiler.MsidbCustomActionTypeContinue;
                }
                else // the package is vital so ensure there is a rollback action scheduled.
                {
                    string rollbackNamePerUser         = this.Core.GenerateIdentifier("vru", componentId, fileId, "per-user", target ?? String.Empty, targetVersion ?? String.Empty);
                    string rollbackNamePerMachine      = this.Core.GenerateIdentifier("vrm", componentId, fileId, "per-machine", target ?? String.Empty, targetVersion ?? String.Empty);
                    string rollbackCmdLinePerUser      = String.Concat(cmdlinePrefix, " /u:\"", packageId, "\"");
                    string rollbackCmdLinePerMachine   = String.Concat(rollbackCmdLinePerUser, " /admin");
                    int    rollbackExtraBitsPerUser    = VSCompiler.MsidbCustomActionTypeContinue | VSCompiler.MsidbCustomActionTypeRollback | VSCompiler.MsidbCustomActionTypeInScript;
                    int    rollbackExtraBitsPerMachine = rollbackExtraBitsPerUser | VSCompiler.MsidbCustomActionTypeNoImpersonate;
                    string rollbackConditionPerUser    = String.Format("NOT ALLUSERS AND NOT Installed AND ${0}=2 AND ?{0}>2", componentId); // NOT Installed && Component being installed but not installed already.
                    string rollbackConditionPerMachine = String.Format("ALLUSERS AND NOT Installed AND ${0}=2 AND ?{0}>2", componentId);     // NOT Installed && Component being installed but not installed already.

                    this.SchedulePropertyExeAction(sourceLineNumbers, rollbackNamePerUser, propertyId, rollbackCmdLinePerUser, rollbackExtraBitsPerUser, rollbackConditionPerUser, null, installAfter);
                    this.SchedulePropertyExeAction(sourceLineNumbers, rollbackNamePerMachine, propertyId, rollbackCmdLinePerMachine, rollbackExtraBitsPerMachine, rollbackConditionPerMachine, null, rollbackNamePerUser);

                    installAfter = rollbackNamePerMachine;
                }

                string installNamePerUser         = this.Core.GenerateIdentifier("viu", componentId, fileId, "per-user", target ?? String.Empty, targetVersion ?? String.Empty);
                string installNamePerMachine      = this.Core.GenerateIdentifier("vim", componentId, fileId, "per-machine", target ?? String.Empty, targetVersion ?? String.Empty);
                string installCmdLinePerUser      = String.Format("{0} \"[#{1}]\"", cmdlinePrefix, fileId);
                string installCmdLinePerMachine   = String.Concat(installCmdLinePerUser, " /admin");
                string installConditionPerUser    = String.Format("NOT ALLUSERS AND ${0}=3", componentId); // only execute if the Component being installed.
                string installConditionPerMachine = String.Format("ALLUSERS AND ${0}=3", componentId);     // only execute if the Component being installed.

                this.SchedulePropertyExeAction(sourceLineNumbers, installNamePerUser, propertyId, installCmdLinePerUser, installExtraBits, installConditionPerUser, null, installAfter);
                this.SchedulePropertyExeAction(sourceLineNumbers, installNamePerMachine, propertyId, installCmdLinePerMachine, installExtraBits | VSCompiler.MsidbCustomActionTypeNoImpersonate, installConditionPerMachine, null, installNamePerUser);

                // If not permanent, schedule the uninstall custom action.
                if (permanent != YesNoType.Yes)
                {
                    string uninstallNamePerUser         = this.Core.GenerateIdentifier("vuu", componentId, fileId, "per-user", target ?? String.Empty, targetVersion ?? String.Empty);
                    string uninstallNamePerMachine      = this.Core.GenerateIdentifier("vum", componentId, fileId, "per-machine", target ?? String.Empty, targetVersion ?? String.Empty);
                    string uninstallCmdLinePerUser      = String.Concat(cmdlinePrefix, " /u:\"", packageId, "\"");
                    string uninstallCmdLinePerMachine   = String.Concat(uninstallCmdLinePerUser, " /admin");
                    int    uninstallExtraBitsPerUser    = VSCompiler.MsidbCustomActionTypeContinue | VSCompiler.MsidbCustomActionTypeInScript;
                    int    uninstallExtraBitsPerMachine = uninstallExtraBitsPerUser | VSCompiler.MsidbCustomActionTypeNoImpersonate;
                    string uninstallConditionPerUser    = String.Format("NOT ALLUSERS AND ${0}=2 AND ?{0}>2", componentId); // Only execute if component is being uninstalled.
                    string uninstallConditionPerMachine = String.Format("ALLUSERS AND ${0}=2 AND ?{0}>2", componentId);     // Only execute if component is being uninstalled.

                    this.SchedulePropertyExeAction(sourceLineNumbers, uninstallNamePerUser, propertyId, uninstallCmdLinePerUser, uninstallExtraBitsPerUser, uninstallConditionPerUser, "InstallFinalize", null);
                    this.SchedulePropertyExeAction(sourceLineNumbers, uninstallNamePerMachine, propertyId, uninstallCmdLinePerMachine, uninstallExtraBitsPerMachine, uninstallConditionPerMachine, "InstallFinalize", null);
                }
            }
        }
Beispiel #28
0
        public void AddExpressionSpecialTestCodeGenerator()
        {
            Lexer lexer           = new Lexer(File.ReadAllText(AppContext.BaseDirectory + "/../../../../../docs/tang.tokens.json"));
            var   tokens          = lexer.Analyse("int8 a = 1 + 2 + 3");
            var   tokenEnumerator = tokens.Select(t => new Parsing.Data.Token()
            {
                Name = t.Name, Value = t.Value
            }).GetEnumerator();

            tokenEnumerator.MoveNext();
            Preprocessor preprocessor = new Preprocessor();

            tokens = preprocessor.Process(lexer, null, tokens);
            ProgramParser parser        = new ProgramParser();
            var           parseTree     = parser.ParseProgram(tokenEnumerator);
            var           astTranslator = new Translation.ProgramToAST.ProgramToASTTranslator();

            AST.Data.AST ast         = astTranslator.TranslatetoAST(parseTree) as AST.Data.AST;
            var          cTranslator = new Translation.ASTToC.ASTToCTranslator();

            C.Data.C c = cTranslator.Translate(ast) as C.Data.C;

            // c is the autogenerated tree, we have to manually create one and assert their equality

            var cExpected = new C.Data.C(true)
            {
                new C.Data.Declaration(true)
                {
                    new C.Data.CompoundDeclaration(true)
                    {
                        new C.Data.Declaration(true)
                        {
                            new C.Data.CompoundDeclaration(true)
                            {
                                new C.Data.Declaration(true)
                                {
                                    new C.Data.Token()
                                    {
                                        Name = "EPSILON"
                                    }
                                },
                                new C.Data.Declaration(true)
                                {
                                    new C.Data.IntegerDeclaration(true)
                                    {
                                        new C.Data.IntType(true)
                                        {
                                            new C.Data.Token()
                                            {
                                                Name = "signed"
                                            },
                                            new C.Data.Token()
                                            {
                                                Name = "char"
                                            }
                                        },
                                        new C.Data.Token()
                                        {
                                            Name = "identifier"
                                        }
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = ";"
                                    }
                                }
                            }
                        },
                        new C.Data.Declaration(true)
                        {
                            new C.Data.CompoundDeclaration(true)
                            {
                                new C.Data.Declaration(true)
                                {
                                    new C.Data.FunctionPrototype(true)
                                    {
                                        new C.Data.Token()
                                        {
                                            Name = "signed"
                                        },
                                        new C.Data.Token()
                                        {
                                            Name = "long"
                                        },
                                        new C.Data.Token()
                                        {
                                            Name = "Pow"
                                        },
                                        new C.Data.Token()
                                        {
                                            Name = "("
                                        },
                                        new C.Data.Token()
                                        {
                                            Name = "signed"
                                        },
                                        new C.Data.Token()
                                        {
                                            Name = "long"
                                        },
                                        new C.Data.Token()
                                        {
                                            Name = "a"
                                        },
                                        new C.Data.Token()
                                        {
                                            Name = ","
                                        },
                                        new C.Data.Token()
                                        {
                                            Name = "signed"
                                        },
                                        new C.Data.Token()
                                        {
                                            Name = "long"
                                        },
                                        new C.Data.Token()
                                        {
                                            Name = "b"
                                        },
                                        new C.Data.Token()
                                        {
                                            Name = ")"
                                        }
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = ";"
                                    }
                                },
                                new C.Data.Declaration(true)
                                {
                                    new C.Data.FunctionPrototype(true)
                                    {
                                        new C.Data.Type(true)
                                        {
                                            new C.Data.Token()
                                            {
                                                Name = "void"
                                            }
                                        },
                                        new C.Data.Token()
                                        {
                                            Name = "main"
                                        },
                                        new C.Data.Token()
                                        {
                                            Name = "("
                                        },
                                        new C.Data.Token()
                                        {
                                            Name = ")"
                                        }
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = ";"
                                    }
                                }
                            }
                        }
                    }
                },
                new C.Data.Function(true)
                {
                    new C.Data.CompoundFunction(true)
                    {
                        new C.Data.Function(true)
                        {
                            new C.Data.CompoundFunction(true)
                            {
                                new C.Data.Function(true)
                                {
                                    new C.Data.Token()
                                    {
                                        Name = "signed"
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = "long"
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = "Pow"
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = "("
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = "signed"
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = "long"
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = "a"
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = ","
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = "signed"
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = "long"
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = "b"
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = ")"
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = "{"
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = "signed"
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = "long"
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = "r"
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = "="
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = "1"
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = ","
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = "i"
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = ";"
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = "for"
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = "("
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = "i"
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = "="
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = "0"
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = ";"
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = "i"
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = "<"
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = "b"
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = ";"
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = "i"
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = "++"
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = ")"
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = "{"
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = "r"
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = "*="
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = "a"
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = ";"
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = "}"
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = "return"
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = "r"
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = ";"
                                    },
                                    new C.Data.Token()
                                    {
                                        Name = "}"
                                    }
                                },
                                new C.Data.Function(true)
                                {
                                    new C.Data.Token()
                                    {
                                        Name = "EPSILON"
                                    }
                                }
                            }
                        },
                        new C.Data.Function(true)
                        {
                            new C.Data.Type(true)
                            {
                                new C.Data.Token()
                                {
                                    Name = "void"
                                }
                            },
                            new C.Data.Token()
                            {
                                Name = "main"
                            },
                            new C.Data.Token()
                            {
                                Name = "("
                            },
                            new C.Data.Token()
                            {
                                Name = ")"
                            },
                            new C.Data.Token()
                            {
                                Name = "{"
                            },
                            new C.Data.Declaration(true)
                            {
                                new C.Data.Token()
                                {
                                    Name = "EPSILON"
                                }
                            },
                            new C.Data.Statement(true)
                            {
                                new C.Data.CompoundStatement(true)
                                {
                                    new C.Data.Statement(true)
                                    {
                                        new C.Data.Token()
                                        {
                                            Name = "EPSILON"
                                        }
                                    },
                                    new C.Data.Statement(true)
                                    {
                                        new C.Data.IntegerAssignment(true)
                                        {
                                            new C.Data.Token()
                                            {
                                                Name = "identifier"
                                            },
                                            new C.Data.Token()
                                            {
                                                Name = "="
                                            },
                                            new C.Data.IntegerExpression(true)
                                            {
                                                new C.Data.AddExpression(true)
                                                {
                                                    new C.Data.Token()
                                                    {
                                                        Name = "("
                                                    },
                                                    new C.Data.IntegerExpression(true)
                                                    {
                                                        new C.Data.AddExpression(true)
                                                        {
                                                            new C.Data.Token()
                                                            {
                                                                Name = "("
                                                            },
                                                            new C.Data.IntegerExpression(true)
                                                            {
                                                                new C.Data.Token()
                                                                {
                                                                    Name = "numeral"
                                                                }
                                                            },
                                                            new C.Data.Token()
                                                            {
                                                                Name = "+"
                                                            },
                                                            new C.Data.IntegerExpression(true)
                                                            {
                                                                new C.Data.Token()
                                                                {
                                                                    Name = "numeral"
                                                                }
                                                            },
                                                            new C.Data.Token()
                                                            {
                                                                Name = ")"
                                                            }
                                                        }
                                                    },
                                                    new C.Data.Token()
                                                    {
                                                        Name = "+"
                                                    },
                                                    new C.Data.IntegerExpression(true)
                                                    {
                                                        new C.Data.Token()
                                                        {
                                                            Name = "numeral"
                                                        }
                                                    },
                                                    new C.Data.Token()
                                                    {
                                                        Name = ")"
                                                    }
                                                }
                                            }
                                        },
                                        new C.Data.Token()
                                        {
                                            Name = ";"
                                        }
                                    }
                                }
                            },
                            new C.Data.Token()
                            {
                                Name = "}"
                            }
                        }
                    }
                }
            };


            // Use this to print the actual tree
            //var CCC = c.Accept(new C.Visitors.TreePrintVisitor());
            //foreach (var line in CCC)
            //{
            //    Debug.WriteLine(line);
            //}

            // Call a method to walk the tree's nodes and test if their names are equal
            TreeAsserter(c, cExpected);
        }
 //
 // Appends data preprocessor
 //
 // input p
 //            preprocessor
 // see Preprocessor
 //
 public void appendPreprocessor(Preprocessor p)
 {
     preprocessors.Add(p);
 }
Beispiel #30
0
        protected override ExitCode RunCommand(Preprocessor preprocessor)
        {
            // Make sure we actually got a recipe value
            if (preprocessor.Values.All(x => x.Name != "recipe"))
            {
                Trace.Critical("A recipe must be specified");
                return ExitCode.CommandLineError;
            }

            // Fix the root folder and other files
            DirectoryPath currentDirectory = Environment.CurrentDirectory;
            _configOptions.RootPath = _configOptions.RootPath == null ? currentDirectory : currentDirectory.Combine(_configOptions.RootPath);
            _configOptions.ConfigFilePath = _configOptions.RootPath.CombineFile(_configOptions.ConfigFilePath ?? "config.wyam");
            _inputPath = _inputPath ?? "input";

            // Get the engine and configurator
            using (EngineManager engineManager = EngineManager.Get(preprocessor, _configOptions))
            {
                if (engineManager == null)
                {
                    return ExitCode.CommandLineError;
                }

                // Check to make sure the directory is empty (and provide option to clear it)
                IDirectory inputDirectory = engineManager.Engine.FileSystem.GetRootDirectory(_inputPath);
                if (inputDirectory.Exists)
                {
                    Console.WriteLine($"Input directory {inputDirectory.Path.FullPath} exists, are you sure you want to clear it [y|N]?");
                    char inputChar = Console.ReadKey(true).KeyChar;
                    if (inputChar != 'y' && inputChar != 'Y')
                    {
                        Trace.Information($"Input directory will not be cleared");
                        return ExitCode.Normal;
                    }
                    Trace.Information($"Input directory will be cleared");
                }
                else
                {
                    Trace.Information($"Input directory {inputDirectory.Path.FullPath} does not exist and will be created");
                }
                if (inputDirectory.Exists)
                {
                    inputDirectory.Delete(true);
                }
                inputDirectory.Create();

                // Check the config file (and provide option to clear it)
                IFile configFile = engineManager.Engine.FileSystem.GetRootFile(_configOptions.ConfigFilePath);
                if (configFile.Exists)
                {
                    Console.WriteLine($"Configuration file {configFile.Path.FullPath} exists, are you sure you want to potentially overwrite it [y|N]?");
                    char inputChar = Console.ReadKey(true).KeyChar;
                    if (inputChar != 'y' && inputChar != 'Y')
                    {
                        Trace.Information($"Configuration file will not be overwritten");
                        configFile = null;
                    }
                    else
                    {
                        Trace.Information($"Configuration file may be overwritten");
                    }
                }
                else
                {
                    Trace.Information($"Configuration file {configFile.Path.FullPath} does not exist and may be created");
                }

                // We can ignore theme packages since we don't care about the theme for scaffolding
                engineManager.Configurator.IgnoreKnownThemePackages = true;

                // Configure everything (primarily to get the recipe)
                try
                {
                    engineManager.Configurator.Configure(null);
                }
                catch (Exception ex)
                {
                    Trace.Critical("Error while configuring engine: {0}", ex.Message);
                    return ExitCode.ConfigurationError;
                }

                // Scaffold the recipe
                engineManager.Configurator.Recipe.Scaffold(configFile, inputDirectory);
            }

            return ExitCode.Normal;
        }
        public CompilerResults compileFromFiles(CompilerParameters parameters, File[] files) {
            var results = new CompilerResults();
            this.context = new CompilerContext(parameters, results);
            this.statementValidator = new StatementValidator(this.context);
            this.expressionValidator = new ExpressionValidator(this.context);
            this.statementValidator.ExpressionValidator = this.expressionValidator;
            this.expressionValidator.StatementValidator = this.statementValidator;
            this.reachabilityChecker = new ReachabilityChecker(context);
            this.assignmentChecker = new AssignmentChecker(context);
            this.bytecodeGenerator = new BytecodeGenerator(context);
            bool tragicError = false;
			
            var buffer = new char[4096];
            var sb = new StringBuilder();
            var parser = new Parser();
            
            foreach (var file in files) {
                sb.setLength(0);
                InputStreamReader reader = null;
                try {
                    reader = new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8"));
                    int read;
                    while ((read = reader.read(buffer)) != -1) {
                        sb.append(buffer, 0, read);
                    }
                    
                    var text = new char[sb.length()];
                    sb.getChars(0, sizeof(text), text, 0);
                    if (sizeof(text) > 0) {
                        if (text[sizeof(text) - 1] == '\u001a') {
                            text[sizeof(text) - 1] = ' ';
                        }
                    }
                    var preprocessor = new Preprocessor(results.codeErrorManager, text);
                    preprocessor.Filename = file.getAbsolutePath();
					preprocessor.Symbols.addAll(parameters.Symbols);
                    
                    var scanner = new PreprocessedTextScanner(results.codeErrorManager, preprocessor.preprocess());
                    scanner.Filename = file.getAbsolutePath();
                    var compilationUnit = parser.parseCompilationUnit(scanner);
                    
                    if (compilationUnit != null) {
                        compilationUnit.Symbols = preprocessor.Symbols;
                        context.CompilationUnits.add(compilationUnit);
                    }
                } catch (CodeErrorException) {
				} catch (Exception e) {
					e.printStackTrace();
					tragicError = true;
					break;
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException) {
                        }
                    }
                }
            }
            if (!tragicError) {
				if (!context.HasErrors) {
					if (parameters.ProgressTracker != null) {
						parameters.ProgressTracker.compilationStageFinished(CompilationStage.Parsing);
					}
					doCompile();
				}
			}
            this.context = null;
            this.statementValidator = null;
            this.expressionValidator = null;
            this.reachabilityChecker = null;
            this.assignmentChecker = null;
            this.queryTranslator = null;
            this.documentationBuilder = null;
			
			if (parameters.ProgressTracker != null) {
				parameters.ProgressTracker.compilationFinished();
			}
            return results;
        }
        /// <summary>
        /// Parses a RemoveFolderEx element.
        /// </summary>
        /// <param name="node">Element to parse.</param>
        /// <param name="componentId">Identifier of parent component.</param>
        /// <param name="parentDirectory">Identifier of parent component's directory.</param>
        private void ParseJsonFileElement(XmlNode node, string componentId, string parentDirectory)
        {
            SourceLineNumberCollection sourceLineNumbers = Preprocessor.GetSourceLineNumbers(node);
            string id                = null;
            string file              = null;
            string elementPath       = null;
            string value             = null;
            int    on                = CompilerCore.IntegerNotSet;
            int    flags             = 0;
            int    action            = CompilerCore.IntegerNotSet;
            int?   sequence          = 1;
            int    selectionLanguage = CompilerCore.IntegerNotSet;
            string verifyPath        = null;

            if (node.Attributes != null)
            {
                foreach (XmlAttribute attribute in node.Attributes)
                {
                    if (0 == attribute.NamespaceURI.Length || attribute.NamespaceURI == Schema.TargetNamespace)
                    {
                        switch (attribute.LocalName)
                        {
                        case "Id":
                            // Identifier for json file modification
                            id = Core.GetAttributeIdentifierValue(sourceLineNumbers, attribute);
                            break;

                        case "File":
                            // Path of the .json file to modify.
                            file = Core.GetAttributeValue(sourceLineNumbers, attribute);
                            break;

                        case "ElementPath":
                            // The path to the parent element of the element to be modified. The semantic can be either JSON Path or JSON Pointer language, as specified in the
                            // SelectionLanguage attribute. Note that this is a formatted field and therefore, square brackets in the path must be escaped. In addition, JSON Path
                            // and Pointer allow backslashes to be used to escape characters, so if you intend to include literal backslashes, you must escape them as well by doubling
                            // them in this attribute. The string is formatted by MSI first, and the result is consumed as the JSON Path or Pointer.
                            elementPath = Core.GetAttributeValue(sourceLineNumbers, attribute);
                            break;

                        case "Value":
                            // The value to set. May be one of the simple JSON types, or a JSON-formatted object. See the
                            // <html:a href="http://msdn.microsoft.com/library/aa368609(VS.85).aspx" target="_blank">Formatted topic</html:a> for information how to escape square brackets in the value.
                            value = Core.GetAttributeValue(sourceLineNumbers, attribute);
                            break;

                        case "Action":
                            // The type of modification to be made to the JSON file when the component is installed or uninstalled.
                            action = ValidateAction(node, sourceLineNumbers, attribute, ref flags);
                            break;

                        case "On":
                            // Defines when the specified changes to the JSON file are to be done.
                            on = ValidateOn(node, sourceLineNumbers, attribute, ref flags);
                            break;

                        case "PreserveModifiedDate":
                            // Specifies whether or not the modification should preserve the modified date of the file.  Preserving the modified date will allow
                            // the file to be patched if no other modifications have been made.
                            flags = ValidatePreserveModifiedDate(node, sourceLineNumbers, attribute, flags);
                            break;

                        case "Sequence":
                            // Specifies the order in which the modification is to be attempted on the JSON file.  It is important to ensure that new elements are created before you attempt to modify them.
                            sequence = ToNullableInt(Core.GetAttributeValue(sourceLineNumbers, attribute));
                            break;

                        case "SelectionLanguage":
                            // Specify whether the JSON object should use JSON Path (default) or JSON Pointer as the query language for ElementPath.
                            selectionLanguage = ValidateSelectionLanguage(node, sourceLineNumbers, attribute, ref flags);
                            break;

                        case "VerifyPath":
                            // The path to the element being modified. This is required for 'delete' actions. For 'set' actions, VerifyPath is used to decide if the element already exists.
                            // The semantic can be either JSON Path or JSON Pointer language, as specified in the SelectionLanguage attribute. Note that this is a formatted field and therefore,
                            // square brackets in the path must be escaped. In addition, JSON Path and Pointer allow backslashes to be used to escape characters, so if you intend to include literal
                            // backslashes, you must escape them as well by doubling them in this attribute. The string is formatted by MSI first, and the result is consumed as the JSON Path or Pointer.
                            verifyPath = Core.GetAttributeValue(sourceLineNumbers, attribute);
                            break;

                        default:
                            Core.UnexpectedAttribute(sourceLineNumbers, attribute);
                            break;
                        }
                    }
                    else
                    {
                        Core.UnsupportedExtensionAttribute(sourceLineNumbers, attribute);
                    }
                }
            }

            if (CompilerCore.IntegerNotSet == action)
            {
                // default is set value
                flags |= 2;
            }

            foreach (XmlNode child in node.ChildNodes)
            {
                if (XmlNodeType.Element != child.NodeType)
                {
                    continue;
                }

                if (child.NamespaceURI == Schema.TargetNamespace)
                {
                    Core.UnexpectedElement(node, child);
                }
                else
                {
                    Core.UnsupportedExtensionElement(node, child);
                }
            }

            if (Core.EncounteredError)
            {
                return;
            }

            Row row    = Core.CreateRow(sourceLineNumbers, "JsonFile");
            int rowIdx = 0;

            row[rowIdx++] = id;
            row[rowIdx++] = file;
            row[rowIdx++] = elementPath;
            row[rowIdx++] = verifyPath;
            row[rowIdx++] = value;
            row[rowIdx++] = flags;
            row[rowIdx++] = componentId;
            row[rowIdx]   = sequence;

            Core.CreateWixSimpleReferenceRow(sourceLineNumbers, "CustomAction", "JsonFile");
        }
Beispiel #33
0
        private double calculateFitness()
        {
            DataAccess dataAccess = new DataAccess(currentRunFile);
            if (currentRunFile != "" && currentSource != null && lstRuns.SelectedItems.Count > 0)
            {

                int width = Convert.ToInt32(dataAccess.GetParameter("Master_Width"));
                int height = Convert.ToInt32(dataAccess.GetParameter("Master_Height"));
                bool aspect = Convert.ToBoolean(dataAccess.GetParameter("Master_Aspect"));
                int scalingMethod = Convert.ToInt32(dataAccess.GetParameter("Master_Resize"));

                chkContastStretch.Checked = Convert.ToBoolean(dataAccess.GetParameter("Filter_Stretch"));
                chkHistogram.Checked = Convert.ToBoolean(dataAccess.GetParameter("Filter_Histo"));
                chkGaussian.Checked = Convert.ToBoolean(dataAccess.GetParameter("Filter_Gaussian"));
                numBlurStrength.Value = Convert.ToInt32(dataAccess.GetParameter("Filter_BlurStr"));
                chkContrast.Checked = Convert.ToBoolean(dataAccess.GetParameter("Filter_Contrast"));
                numContrast.Value = Convert.ToDecimal(dataAccess.GetParameter("Filter_ContrastStr"));
                chkGreyscale.Checked = Convert.ToBoolean(dataAccess.GetParameter("Filter_Greyscale"));
                chkBradley.Checked = Convert.ToBoolean(dataAccess.GetParameter("Filter_Bradley"));
                chkThreshold.Checked = Convert.ToBoolean(dataAccess.GetParameter("Filter_Threshold"));
                numThreshold.Value = Convert.ToDecimal(dataAccess.GetParameter("Filter_ThresholdStr"));

                Preprocessor preprocessor = new Preprocessor();
                preprocessor.Bradley = chkBradley.Checked;
                preprocessor.ContrastAdjustment = chkContrast.Checked;
                preprocessor.ContrastStrength = numContrast.Value;
                preprocessor.ContrastStretch = chkContastStretch.Checked;
                preprocessor.FilterLevel = 1;
                preprocessor.Gaussian = chkGaussian.Checked;
                preprocessor.GaussianStrength = numBlurStrength.Value;
                preprocessor.Greyscale = chkGreyscale.Checked;
                preprocessor.Histogram = chkHistogram.Checked;
                preprocessor.ImageSize = new Size(width, height);
                preprocessor.KeepAspectRatio = aspect;
                preprocessor.ScalingMethod = (ScalingMethods)scalingMethod;
                preprocessor.Threshold = chkThreshold.Checked;
                preprocessor.ThresholdStrength = numThreshold.Value;

                Network network = dataAccess.GetNetwork(int.Parse(lstRuns.SelectedItems[0].SubItems[5].Text));
                currentSource.Preprocessor = preprocessor;
                Bitmap b = (Bitmap)currentSource.InternalImage;
                double[] result = network.Run(Utils.getImageWeights(b, (InputGroup[])lstInputGroups.Items.Cast<InputGroup>().ToArray<InputGroup>()));
                b.Dispose();
                lblFitness.Text = "Fitness: " + result[0].ToString();
                return result[0];
            }
            return -1.0 ;
        }
        /// <summary>
        /// Parses a Tag element for Software Id Tag registration under a Product element.
        /// </summary>
        /// <param name="node">The element to parse.</param>
        private void ParseProductTagElement(XElement node)
        {
            SourceLineNumber sourceLineNumbers = Preprocessor.GetSourceLineNumbers(node);
            string           name     = null;
            string           regid    = null;
            string           feature  = "WixSwidTag";
            YesNoType        licensed = YesNoType.NotSet;
            string           type     = null;

            foreach (XAttribute attrib in node.Attributes())
            {
                if (String.IsNullOrEmpty(attrib.Name.NamespaceName) || this.Namespace == attrib.Name.Namespace)
                {
                    switch (attrib.Name.LocalName)
                    {
                    case "Name":
                        name = this.Core.GetAttributeLongFilename(sourceLineNumbers, attrib, false);
                        break;

                    case "Regid":
                        regid = this.Core.GetAttributeValue(sourceLineNumbers, attrib);
                        break;

                    case "Feature":
                        feature = this.Core.GetAttributeIdentifierValue(sourceLineNumbers, attrib);
                        break;

                    case "Licensed":
                        licensed = this.Core.GetAttributeYesNoValue(sourceLineNumbers, attrib);
                        break;

                    case "Type":
                        type = this.ParseTagTypeAttribute(sourceLineNumbers, node, attrib);
                        break;

                    default:
                        this.Core.UnexpectedAttribute(node, attrib);
                        break;
                    }
                }
                else
                {
                    this.Core.ParseExtensionAttribute(node, attrib);
                }
            }

            this.Core.ParseForExtensionElements(node);

            if (String.IsNullOrEmpty(name))
            {
                XAttribute productNameAttribute = node.Parent.Attribute("Name");
                if (null != productNameAttribute)
                {
                    name = productNameAttribute.Value;
                }
                else
                {
                    this.Core.OnMessage(WixErrors.ExpectedAttribute(sourceLineNumbers, node.Name.LocalName, "Name"));
                }
            }

            if (!String.IsNullOrEmpty(name) && !this.Core.IsValidLongFilename(name, false))
            {
                this.Core.OnMessage(TagErrors.IllegalName(sourceLineNumbers, node.Parent.Name.LocalName, name));
            }

            if (String.IsNullOrEmpty(regid))
            {
                this.Core.OnMessage(WixErrors.ExpectedAttribute(sourceLineNumbers, node.Name.LocalName, "Regid"));
            }

            if (!this.Core.EncounteredError)
            {
                string     directoryId = "WixTagRegidFolder";
                Identifier fileId      = this.Core.CreateIdentifier("tag", regid, ".product.tag");
                string     fileName    = String.Concat(regid, " ", name, ".swidtag");
                string     shortName   = this.Core.CreateShortName(fileName, false, false);

                this.Core.CreateSimpleReference(sourceLineNumbers, "Directory", directoryId);

                ComponentRow componentRow = (ComponentRow)this.Core.CreateRow(sourceLineNumbers, "Component", fileId);
                componentRow.Guid        = "*";
                componentRow[3]          = 0;
                componentRow.Directory   = directoryId;
                componentRow.IsLocalOnly = true;
                componentRow.KeyPath     = fileId.Id;

                this.Core.CreateSimpleReference(sourceLineNumbers, "Feature", feature);
                this.Core.CreateComplexReference(sourceLineNumbers, ComplexReferenceParentType.Feature, feature, null, ComplexReferenceChildType.Component, fileId.Id, true);

                FileRow fileRow = (FileRow)this.Core.CreateRow(sourceLineNumbers, "File", fileId);
                fileRow.Component = fileId.Id;
                fileRow.FileName  = String.Concat(shortName, "|", fileName);

                WixFileRow wixFileRow = (WixFileRow)this.Core.CreateRow(sourceLineNumbers, "WixFile");
                wixFileRow.Directory  = directoryId;
                wixFileRow.File       = fileId.Id;
                wixFileRow.DiskId     = 1;
                wixFileRow.Attributes = 1;
                wixFileRow.Source     = String.Concat("%TEMP%\\", fileName);

                this.Core.EnsureTable(sourceLineNumbers, "SoftwareIdentificationTag");
                Row row = this.Core.CreateRow(sourceLineNumbers, "WixProductTag");
                row[0] = fileId.Id;
                row[1] = regid;
                row[2] = name;
                if (YesNoType.Yes == licensed)
                {
                    row[3] = 1;
                }
                row[4] = type;

                this.Core.CreateSimpleReference(sourceLineNumbers, "File", fileId.Id);
            }
        }
Beispiel #35
0
        public void CommandLinePropertiesOverrideAssemblyMetadataForPreprocessor()
        {
            // Arrange
            using (var workingDirectory = TestDirectory.Create())
            {
                var          testAssembly = Assembly.GetExecutingAssembly();
                const string inputSpec    = @"<?xml version=""1.0""?>
	<package>
	    <metadata>
	        <id>$id$</id>
	        <version>$version$</version>
	        <description>$description$</description>
	        <authors>$owner$</authors>
	        <copyright>$copyright$</copyright>
	        <licenseUrl>https://github.com/NuGet/NuGet.Client/blob/master/LICENSE.txt</licenseUrl>
	        <projectUrl>https://github.com/NuGet/NuGet.Client</projectUrl>
	        <tags>nuget</tags>
	    </metadata>
	</package>"    ;
                var          projectXml   = @"<?xml version=""1.0"" encoding=""utf-8""?>
	<Project ToolsVersion=""4.0"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
	    <PropertyGroup>
	        <ProjectGuid>{F879F274-EFA0-4157-8404-33A19B4E6AEC}</ProjectGuid>
	        <OutputType>Library</OutputType>
	        <RootNamespace>NuGet.Test</RootNamespace>
	        <AssemblyName>"     + testAssembly.GetName().Name + @"</AssemblyName>
	        <TargetFrameworkProfile Condition="" '$(TargetFrameworkVersion)' == 'v4.0' "">Client</TargetFrameworkProfile>    
	        <OutputPath>.</OutputPath> <!-- Force it to look for the assembly in the base path -->
	        <TargetPath>"     + testAssembly.ManifestModule.FullyQualifiedName + @"</TargetPath>
	    </PropertyGroup>
	    
	    <ItemGroup>
	        <Compile Include=""..\..\Dummy.cs"">
	          <Link>Dummy.cs</Link>
	        </Compile>
	    </ItemGroup>
	 
	    <Import Project=""$(MSBuildToolsPath)\Microsoft.CSharp.targets"" />
	</Project>"    ;

                // Set base path to the currently assembly's folder so that it will find the test assembly
                var basePath          = Path.GetDirectoryName(testAssembly.CodeBase);
                var cmdLineProperties = new Dictionary <string, string>
                {
                    { "owner", "overriden" }
                };
                var projectPath = Path.Combine(workingDirectory, "test.csproj");
                File.WriteAllText(projectPath, projectXml);

                var msbuildPath = Util.GetMsbuildPathOnWindows();
                if (RuntimeEnvironmentHelper.IsMono && Util.IsRunningOnMac())
                {
                    msbuildPath = @"/Library/Frameworks/Mono.framework/Versions/Current/lib/mono/msbuild/15.0/bin/";
                }
                var factory = new ProjectFactory(msbuildPath, projectPath, cmdLineProperties)
                {
                    Build = false
                };
                // Cmdline properties are added to the factory, see PackCommand.cs(351)
                factory.ProjectProperties["owner"] = "overriden";

                // Act
                var packageBuilder = factory.CreateBuilder(basePath, null, null, true);
                var actual         = Preprocessor.Process(inputSpec.AsStream(), factory, false);

                var xdoc = XDocument.Load(new StringReader(actual));
                Assert.Equal(testAssembly.GetName().Name, xdoc.XPathSelectElement("/package/metadata/id").Value);
                Assert.Equal(testAssembly.GetCustomAttribute <AssemblyInformationalVersionAttribute>().InformationalVersion, xdoc.XPathSelectElement("/package/metadata/version").Value);
                Assert.Equal("NuGet client library.", xdoc.XPathSelectElement("/package/metadata/description").Value);
                Assert.Equal(testAssembly.GetCustomAttribute <AssemblyCopyrightAttribute>().Copyright, xdoc.XPathSelectElement("/package/metadata/copyright").Value);
                Assert.Equal(
                    cmdLineProperties["owner"],
                    xdoc.XPathSelectElement("/package/metadata/authors").Value);
            }
        }
        /// <summary>
        /// Parses a Tag element for Software Id Tag registration under a Bundle element.
        /// </summary>
        /// <param name="node">The element to parse.</param>
        private void ParseBundleTagElement(XElement node)
        {
            SourceLineNumber sourceLineNumbers = Preprocessor.GetSourceLineNumbers(node);
            string           name     = null;
            string           regid    = null;
            YesNoType        licensed = YesNoType.NotSet;
            string           type     = null;

            foreach (XAttribute attrib in node.Attributes())
            {
                if (String.IsNullOrEmpty(attrib.Name.NamespaceName) || this.Namespace == attrib.Name.Namespace)
                {
                    switch (attrib.Name.LocalName)
                    {
                    case "Name":
                        name = this.Core.GetAttributeLongFilename(sourceLineNumbers, attrib, false);
                        break;

                    case "Regid":
                        regid = this.Core.GetAttributeValue(sourceLineNumbers, attrib);
                        break;

                    case "Licensed":
                        licensed = this.Core.GetAttributeYesNoValue(sourceLineNumbers, attrib);
                        break;

                    case "Type":
                        type = this.ParseTagTypeAttribute(sourceLineNumbers, node, attrib);
                        break;

                    default:
                        this.Core.UnexpectedAttribute(node, attrib);
                        break;
                    }
                }
                else
                {
                    this.Core.ParseExtensionAttribute(node, attrib);
                }
            }

            this.Core.ParseForExtensionElements(node);

            if (String.IsNullOrEmpty(name))
            {
                XAttribute productNameAttribute = node.Parent.Attribute("Name");
                if (null != productNameAttribute)
                {
                    name = productNameAttribute.Value;
                }
                else
                {
                    this.Core.OnMessage(WixErrors.ExpectedAttribute(sourceLineNumbers, node.Name.LocalName, "Name"));
                }
            }

            if (!String.IsNullOrEmpty(name) && !this.Core.IsValidLongFilename(name, false))
            {
                this.Core.OnMessage(TagErrors.IllegalName(sourceLineNumbers, node.Parent.Name.LocalName, name));
            }

            if (String.IsNullOrEmpty(regid))
            {
                this.Core.OnMessage(WixErrors.ExpectedAttribute(sourceLineNumbers, node.Name.LocalName, "Regid"));
            }

            if (!this.Core.EncounteredError)
            {
                string fileName = String.Concat(regid, " ", name, ".swidtag");

                Row tagRow = this.Core.CreateRow(sourceLineNumbers, "WixBundleTag");
                tagRow[0] = fileName;
                tagRow[1] = regid;
                tagRow[2] = name;
                if (YesNoType.Yes == licensed)
                {
                    tagRow[3] = 1;
                }
                // field 4 is the TagXml set by the binder.
                tagRow[5] = type;
            }
        }
Beispiel #37
0
        /// <summary>
        /// Parses a WixManagedBootstrapperApplicationHost element for Bundles.
        /// </summary>
        /// <param name="node">The element to parse.</param>
        private void ParseWixManagedBootstrapperApplicationHostElement(XmlNode node)
        {
            SourceLineNumberCollection sourceLineNumbers = Preprocessor.GetSourceLineNumbers(node);
            string licenseFile      = null;
            string licenseUrl       = null;
            string logoFile         = null;
            string themeFile        = null;
            string localizationFile = null;
            string netFxPackageId   = null;

            foreach (XmlAttribute attrib in node.Attributes)
            {
                if (0 == attrib.NamespaceURI.Length || attrib.NamespaceURI == this.schema.TargetNamespace)
                {
                    switch (attrib.LocalName)
                    {
                    case "LicenseFile":
                        licenseFile = this.Core.GetAttributeValue(sourceLineNumbers, attrib, false);
                        break;

                    case "LicenseUrl":
                        licenseUrl = this.Core.GetAttributeValue(sourceLineNumbers, attrib, false);
                        break;

                    case "LogoFile":
                        logoFile = this.Core.GetAttributeValue(sourceLineNumbers, attrib, false);
                        break;

                    case "ThemeFile":
                        themeFile = this.Core.GetAttributeValue(sourceLineNumbers, attrib, false);
                        break;

                    case "LocalizationFile":
                        localizationFile = this.Core.GetAttributeValue(sourceLineNumbers, attrib, false);
                        break;

                    case "NetFxPackageId":
                        netFxPackageId = this.Core.GetAttributeValue(sourceLineNumbers, attrib, false);
                        break;

                    default:
                        this.Core.UnexpectedAttribute(sourceLineNumbers, attrib);
                        break;
                    }
                }
                else
                {
                    this.Core.UnsupportedExtensionAttribute(sourceLineNumbers, attrib);
                }
            }

            foreach (XmlNode child in node.ChildNodes)
            {
                if (XmlNodeType.Element == child.NodeType)
                {
                    if (child.NamespaceURI == this.schema.TargetNamespace)
                    {
                        this.Core.UnexpectedElement(node, child);
                    }
                    else
                    {
                        this.Core.UnsupportedExtensionElement(node, child);
                    }
                }
            }

            if (String.IsNullOrEmpty(licenseFile) == String.IsNullOrEmpty(licenseUrl))
            {
                this.Core.OnMessage(WixErrors.ExpectedAttribute(sourceLineNumbers, node.Name, "LicenseFile", "LicenseUrl", true));
            }

            if (!this.Core.EncounteredError)
            {
                if (!String.IsNullOrEmpty(licenseFile))
                {
                    this.Core.CreateWixVariableRow(sourceLineNumbers, "WixMbaPrereqLicenseRtf", licenseFile, false);
                }

                if (!String.IsNullOrEmpty(licenseUrl))
                {
                    this.Core.CreateWixVariableRow(sourceLineNumbers, "WixMbaPrereqLicenseUrl", licenseUrl, false);
                }

                if (!String.IsNullOrEmpty(logoFile))
                {
                    this.Core.CreateWixVariableRow(sourceLineNumbers, "PreqbaLogo", logoFile, false);
                }

                if (!String.IsNullOrEmpty(themeFile))
                {
                    this.Core.CreateWixVariableRow(sourceLineNumbers, "PreqbaThemeXml", themeFile, false);
                }

                if (!String.IsNullOrEmpty(localizationFile))
                {
                    this.Core.CreateWixVariableRow(sourceLineNumbers, "PreqbaThemeWxl", localizationFile, false);
                }

                if (!String.IsNullOrEmpty(netFxPackageId))
                {
                    this.Core.CreateWixVariableRow(sourceLineNumbers, "WixMbaPrereqPackageId", netFxPackageId, false);
                }
            }
        }
        protected void AddToTable(XmlSchemaObjectTable table, XmlQualifiedName qname, XmlSchemaObject item)
        {
            if (qname.Name.Length == 0)
            {
                return;
            }
            XmlSchemaObject?existingObject = (XmlSchemaObject?)table[qname];

            if (existingObject != null)
            {
                if (existingObject == item)
                {
                    return;
                }
                string code = SR.Sch_DupGlobalElement;
                if (item is XmlSchemaAttributeGroup)
                {
                    string ns = _nameTable.Add(qname.Namespace);
                    if (Ref.Equal(ns, _nsXml))
                    { //Check for xml namespace
                        XmlSchema       schemaForXmlNS        = Preprocessor.GetBuildInSchema();
                        XmlSchemaObject?builtInAttributeGroup = schemaForXmlNS.AttributeGroups[qname];
                        if ((object)existingObject == (object?)builtInAttributeGroup)
                        {
                            table.Insert(qname, item);
                            return;
                        }
                        else if ((object)item == (object?)builtInAttributeGroup)
                        { //trying to overwrite customer's component with built-in, ignore built-in
                            return;
                        }
                    }
                    else if (IsValidAttributeGroupRedefine(existingObject, item, table))
                    { //check for redefines
                        return;
                    }
                    code = SR.Sch_DupAttributeGroup;
                }
                else if (item is XmlSchemaAttribute)
                {
                    string ns = _nameTable.Add(qname.Namespace);
                    if (Ref.Equal(ns, _nsXml))
                    {
                        XmlSchema       schemaForXmlNS   = Preprocessor.GetBuildInSchema();
                        XmlSchemaObject?builtInAttribute = schemaForXmlNS.Attributes[qname];
                        if ((object)existingObject == (object?)builtInAttribute)
                        { //replace built-in one
                            table.Insert(qname, item);
                            return;
                        }
                        else if ((object)item == (object?)builtInAttribute)
                        { //trying to overwrite customer's component with built-in, ignore built-in
                            return;
                        }
                    }
                    code = SR.Sch_DupGlobalAttribute;
                }
                else if (item is XmlSchemaSimpleType)
                {
                    if (IsValidTypeRedefine(existingObject, item, table))
                    {
                        return;
                    }
                    code = SR.Sch_DupSimpleType;
                }
                else if (item is XmlSchemaComplexType)
                {
                    if (IsValidTypeRedefine(existingObject, item, table))
                    {
                        return;
                    }
                    code = SR.Sch_DupComplexType;
                }
                else if (item is XmlSchemaGroup)
                {
                    if (IsValidGroupRedefine(existingObject, item, table))
                    { //check for redefines
                        return;
                    }
                    code = SR.Sch_DupGroup;
                }
                else if (item is XmlSchemaNotation)
                {
                    code = SR.Sch_DupNotation;
                }
                else if (item is XmlSchemaIdentityConstraint)
                {
                    code = SR.Sch_DupIdentityConstraint;
                }
                else
                {
                    Debug.Assert(item is XmlSchemaElement);
                }
                SendValidationEvent(code, qname.ToString(), item);
            }
            else
            {
                table.Add(qname, item);
            }
        }
 protected MagnitudeSpectrumTransform(Preprocessor predecessor) : base(predecessor)
 {
 }
Beispiel #40
0
 public ConditionChecker(Evaluator evaluator, Preprocessor preprocessor)
 {
     _evaluator = evaluator;
     _preprocessor = preprocessor;
 }
Beispiel #41
0
        /// <summary>
        /// Parses a HelpFile element.
        /// </summary>
        /// <param name="node">Element to process.</param>
        /// <param name="fileId">Identifier of the parent file element.</param>
        private void ParseHelpFileElement(XmlNode node, string fileId)
        {
            SourceLineNumberCollection sourceLineNumbers = Preprocessor.GetSourceLineNumbers(node);
            string    id          = null;
            string    name        = null;
            int       language    = CompilerCore.IntegerNotSet;
            string    hxi         = null;
            string    hxq         = null;
            string    hxr         = null;
            string    samples     = null;
            YesNoType suppressCAs = YesNoType.No;

            foreach (XmlAttribute attrib in node.Attributes)
            {
                if (0 == attrib.NamespaceURI.Length || attrib.NamespaceURI == this.schema.TargetNamespace)
                {
                    switch (attrib.LocalName)
                    {
                    case "Id":
                        id = this.Core.GetAttributeIdentifierValue(sourceLineNumbers, attrib);
                        break;

                    case "AttributeIndex":
                        hxr = this.Core.GetAttributeIdentifierValue(sourceLineNumbers, attrib);
                        this.Core.CreateWixSimpleReferenceRow(sourceLineNumbers, "File", hxr);
                        break;

                    case "Index":
                        hxi = this.Core.GetAttributeIdentifierValue(sourceLineNumbers, attrib);
                        this.Core.CreateWixSimpleReferenceRow(sourceLineNumbers, "File", hxi);
                        break;

                    case "Language":
                        language = this.Core.GetAttributeIntegerValue(sourceLineNumbers, attrib, 0, short.MaxValue);
                        break;

                    case "Name":
                        name = this.Core.GetAttributeValue(sourceLineNumbers, attrib);
                        break;

                    case "SampleLocation":
                        samples = this.Core.GetAttributeIdentifierValue(sourceLineNumbers, attrib);
                        this.Core.CreateWixSimpleReferenceRow(sourceLineNumbers, "File", samples);
                        break;

                    case "Search":
                        hxq = this.Core.GetAttributeIdentifierValue(sourceLineNumbers, attrib);
                        this.Core.CreateWixSimpleReferenceRow(sourceLineNumbers, "File", hxq);
                        break;

                    case "SuppressCustomActions":
                        suppressCAs = this.Core.GetAttributeYesNoValue(sourceLineNumbers, attrib);
                        break;

                    default:
                        this.Core.UnexpectedAttribute(sourceLineNumbers, attrib);
                        break;
                    }
                }
                else
                {
                    this.Core.UnsupportedExtensionAttribute(sourceLineNumbers, attrib);
                }
            }

            if (null == id)
            {
                this.Core.OnMessage(WixErrors.ExpectedAttribute(sourceLineNumbers, node.Name, "Id"));
            }

            if (null == name)
            {
                this.Core.OnMessage(WixErrors.ExpectedAttribute(sourceLineNumbers, node.Name, "Name"));
            }

            //uninstall will always fail silently, leaving file registered, if Language is not set
            if (CompilerCore.IntegerNotSet == language)
            {
                this.Core.OnMessage(WixErrors.ExpectedAttribute(sourceLineNumbers, node.Name, "Language"));
            }

            // find unexpected child elements
            foreach (XmlNode child in node.ChildNodes)
            {
                if (XmlNodeType.Element == child.NodeType)
                {
                    if (child.NamespaceURI == this.schema.TargetNamespace)
                    {
                        this.Core.UnexpectedElement(node, child);
                    }
                    else
                    {
                        this.Core.UnsupportedExtensionElement(node, child);
                    }
                }
            }

            if (!this.Core.EncounteredError)
            {
                Row row = this.Core.CreateRow(sourceLineNumbers, "HelpFile");
                row[0] = id;
                row[1] = name;
                row[2] = language;
                row[3] = fileId;
                row[4] = hxi;
                row[5] = hxq;
                row[6] = hxr;
                row[7] = samples;

                if (YesNoType.No == suppressCAs)
                {
                    this.Core.CreateWixSimpleReferenceRow(sourceLineNumbers, "CustomAction", "CA_RegisterMicrosoftHelp.3643236F_FC70_11D3_A536_0090278A1BB8");
                }
            }
        }
Beispiel #42
0
        /// <summary>
        /// Parses a HelpFile element.
        /// </summary>
        /// <param name="node">Element to process.</param>
        /// <param name="fileId">Identifier of the parent file element.</param>
        private void ParseHelpFileElement(XmlNode node, string fileId)
        {
            SourceLineNumberCollection sourceLineNumbers = Preprocessor.GetSourceLineNumbers(node);
            string id       = null;
            string name     = null;
            int    language = CompilerCore.IntegerNotSet;
            string hxi      = null;
            string hxq      = null;
            string hxr      = null;
            string samples  = null;

            foreach (XmlAttribute attrib in node.Attributes)
            {
                if (0 == attrib.NamespaceURI.Length || attrib.NamespaceURI == this.schema.TargetNamespace)
                {
                    switch (attrib.LocalName)
                    {
                    case "Id":
                        id = this.Core.GetAttributeIdentifierValue(sourceLineNumbers, attrib);
                        break;

                    case "AttributeIndex":
                        hxr = this.Core.GetAttributeIdentifierValue(sourceLineNumbers, attrib);
                        this.Core.CreateWixSimpleReferenceRow(sourceLineNumbers, "File", hxr);
                        break;

                    case "Index":
                        hxi = this.Core.GetAttributeIdentifierValue(sourceLineNumbers, attrib);
                        this.Core.CreateWixSimpleReferenceRow(sourceLineNumbers, "File", hxi);
                        break;

                    case "Language":
                        language = this.Core.GetAttributeIntegerValue(sourceLineNumbers, attrib, 0, short.MaxValue);
                        break;

                    case "Name":
                        name = this.Core.GetAttributeValue(sourceLineNumbers, attrib);
                        break;

                    case "SampleLocation":
                        samples = this.Core.GetAttributeIdentifierValue(sourceLineNumbers, attrib);
                        this.Core.CreateWixSimpleReferenceRow(sourceLineNumbers, "File", samples);
                        break;

                    case "Search":
                        hxq = this.Core.GetAttributeIdentifierValue(sourceLineNumbers, attrib);
                        this.Core.CreateWixSimpleReferenceRow(sourceLineNumbers, "File", hxq);
                        break;

                    default:
                        this.Core.UnexpectedAttribute(sourceLineNumbers, attrib);
                        break;
                    }
                }
                else
                {
                    this.Core.UnsupportedExtensionAttribute(sourceLineNumbers, attrib);
                }
            }

            if (null == id)
            {
                this.Core.OnMessage(WixErrors.ExpectedAttribute(sourceLineNumbers, node.Name, "Id"));
            }

            if (null == name)
            {
                this.Core.OnMessage(WixErrors.ExpectedAttribute(sourceLineNumbers, node.Name, "Name"));
            }

            // find unexpected child elements
            foreach (XmlNode child in node.ChildNodes)
            {
                if (XmlNodeType.Element == child.NodeType)
                {
                    if (child.NamespaceURI == this.schema.TargetNamespace)
                    {
                        this.Core.UnexpectedElement(node, child);
                    }
                    else
                    {
                        this.Core.UnsupportedExtensionElement(node, child);
                    }
                }
            }

            if (!this.Core.EncounteredError)
            {
                Row row = this.Core.CreateRow(sourceLineNumbers, "HelpFile");
                row[0] = id;
                row[1] = name;
                if (CompilerCore.IntegerNotSet != language)
                {
                    row[2] = language;
                }
                row[3] = fileId;
                row[4] = hxi;
                row[5] = hxq;
                row[6] = hxr;
                row[7] = samples;
            }
        }
Beispiel #43
0
        /// <summary>
        /// Parses a PlugCollectionInto element.
        /// </summary>
        /// <param name="node">Element to process.</param>
        /// <param name="parentId">Identifier of the parent help collection.</param>
        private void ParsePlugCollectionIntoElement(XmlNode node, string parentId)
        {
            SourceLineNumberCollection sourceLineNumbers = Preprocessor.GetSourceLineNumbers(node);
            string    hxa                        = null;
            string    hxt                        = null;
            string    hxtParent                  = null;
            string    namespaceParent            = null;
            string    feature                    = null;
            YesNoType suppressExternalNamespaces = YesNoType.No;
            bool      pluginVS05                 = false;
            bool      pluginVS08                 = false;

            foreach (XmlAttribute attrib in node.Attributes)
            {
                if (0 == attrib.NamespaceURI.Length || attrib.NamespaceURI == this.schema.TargetNamespace)
                {
                    switch (attrib.LocalName)
                    {
                    case "Attributes":
                        hxa = this.Core.GetAttributeIdentifierValue(sourceLineNumbers, attrib);
                        break;

                    case "TableOfContents":
                        hxt = this.Core.GetAttributeIdentifierValue(sourceLineNumbers, attrib);
                        break;

                    case "TargetCollection":
                        namespaceParent = this.Core.GetAttributeIdentifierValue(sourceLineNumbers, attrib);
                        break;

                    case "TargetTableOfContents":
                        hxtParent = this.Core.GetAttributeIdentifierValue(sourceLineNumbers, attrib);
                        break;

                    case "TargetFeature":
                        feature = this.Core.GetAttributeIdentifierValue(sourceLineNumbers, attrib);
                        break;

                    case "SuppressExternalNamespaces":
                        suppressExternalNamespaces = this.Core.GetAttributeYesNoValue(sourceLineNumbers, attrib);
                        break;

                    default:
                        this.Core.UnexpectedAttribute(sourceLineNumbers, attrib);
                        break;
                    }
                }
                else
                {
                    this.Core.UnsupportedExtensionAttribute(sourceLineNumbers, attrib);
                }
            }

            pluginVS05 = namespaceParent.Equals("MS_VSIPCC_v80", StringComparison.Ordinal);
            pluginVS08 = namespaceParent.Equals("MS.VSIPCC.v90", StringComparison.Ordinal);

            if (null == namespaceParent)
            {
                this.Core.OnMessage(WixErrors.ExpectedAttribute(sourceLineNumbers, node.Name, "TargetCollection"));
            }

            if (null == feature && (pluginVS05 || pluginVS08) && YesNoType.No == suppressExternalNamespaces)
            {
                this.Core.OnMessage(WixErrors.ExpectedAttribute(sourceLineNumbers, node.Name, "TargetFeature"));
            }

            // find unexpected child elements
            foreach (XmlNode child in node.ChildNodes)
            {
                if (XmlNodeType.Element == child.NodeType)
                {
                    if (child.NamespaceURI == this.schema.TargetNamespace)
                    {
                        this.Core.UnexpectedElement(node, child);
                    }
                    else
                    {
                        this.Core.UnsupportedExtensionElement(node, child);
                    }
                }
            }

            if (!this.Core.EncounteredError)
            {
                Row row = this.Core.CreateRow(sourceLineNumbers, "HelpPlugin");
                row[0] = parentId;
                row[1] = namespaceParent;
                row[2] = hxt;
                row[3] = hxa;
                row[4] = hxtParent;

                if (pluginVS05)
                {
                    if (YesNoType.No == suppressExternalNamespaces)
                    {
                        // Bring in the help 2 base namespace components for VS 2005
                        this.Core.CreateComplexReference(sourceLineNumbers, ComplexReferenceParentType.Feature, feature, String.Empty,
                                                         ComplexReferenceChildType.ComponentGroup, "Help2_VS2005_Namespace_Components", false);
                        // Reference CustomAction since nothing will happen without it
                        this.Core.CreateWixSimpleReferenceRow(sourceLineNumbers, "CustomAction",
                                                              "CA_HxMerge_VSIPCC_VSCC");
                    }
                }
                else if (pluginVS08)
                {
                    if (YesNoType.No == suppressExternalNamespaces)
                    {
                        // Bring in the help 2 base namespace components for VS 2008
                        this.Core.CreateComplexReference(sourceLineNumbers, ComplexReferenceParentType.Feature, feature, String.Empty,
                                                         ComplexReferenceChildType.ComponentGroup, "Help2_VS2008_Namespace_Components", false);
                        // Reference CustomAction since nothing will happen without it
                        this.Core.CreateWixSimpleReferenceRow(sourceLineNumbers, "CustomAction",
                                                              "CA_ScheduleExtHelpPlugin_VSCC_VSIPCC");
                    }
                }
                else
                {
                    // Reference the parent namespace to enforce the foreign key relationship
                    this.Core.CreateWixSimpleReferenceRow(sourceLineNumbers, "HelpNamespace",
                                                          namespaceParent);
                }
            }
        }
Beispiel #44
0
 public virtual int add_preprocessor(Preprocessor p) {
   int ret = modshogunPINVOKE.Features_add_preprocessor(swigCPtr, Preprocessor.getCPtr(p));
   if (modshogunPINVOKE.SWIGPendingException.Pending) throw modshogunPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
 //
 // Removes preprocessor
 //
 // input p
 //            preprocessor to be removed
 // return {true} if preprocessor existed and was removed, {false} otherwise
 //
 public bool removePreprocessor(Preprocessor p)
 {
     return preprocessors.Remove(p);
 }
Beispiel #46
0
 public void Initialize()
 {
     IPreprocessorFactory factory = new PreprocessorFactory();
     _preprocessor = (Preprocessor) factory.GetIPreprocessor();
 }
 //
 // Inserts preprocessor
 //
 // param p
 //           preprocessor
 // param index
 //           where it should be placed in preprocessors queue
 // see Preprocessor
 //
 public void insertPreprocessor(Preprocessor p, int index)
 {
     preprocessors.Insert(index, p);
 }
Beispiel #48
0
        public void Compile(ValidationEventHandler?handler, bool fullCompile)
        {
            if (_isCompiled)
            {
                return;
            }

            foreach (XmlSchema s in delayedSchemas.Values)
            {
                Merge(s);
            }
            delayedSchemas.Clear();

            if (fullCompile)
            {
                _schemaSet                         = new XmlSchemaSet();
                _schemaSet.XmlResolver             = null;
                _schemaSet.ValidationEventHandler += handler;

                foreach (XmlSchema s in References.Values)
                {
                    _schemaSet.Add(s);
                }
                int schemaCount = _schemaSet.Count;

                foreach (XmlSchema s in List)
                {
                    if (!SchemaSet.Contains(s))
                    {
                        _schemaSet.Add(s);
                        schemaCount++;
                    }
                }

                if (!SchemaSet.Contains(XmlSchema.Namespace))
                {
                    AddReference(XsdSchema);
                    _schemaSet.Add(XsdSchema);
                    schemaCount++;
                }

                if (!SchemaSet.Contains(XmlReservedNs.NsXml))
                {
                    AddReference(XmlSchema);
                    _schemaSet.Add(XmlSchema);
                    schemaCount++;
                }
                _schemaSet.Compile();
                _schemaSet.ValidationEventHandler -= handler;
                _isCompiled = _schemaSet.IsCompiled && schemaCount == _schemaSet.Count;
            }
            else
            {
                try
                {
                    XmlNameTable nameTable = new System.Xml.NameTable();
                    Preprocessor prep      = new Preprocessor(nameTable, new SchemaNames(nameTable), null);
                    prep.XmlResolver      = null;
                    prep.SchemaLocations  = new Hashtable();
                    prep.ChameleonSchemas = new Hashtable();
                    foreach (XmlSchema schema in SchemaSet.Schemas())
                    {
                        prep.Execute(schema, schema.TargetNamespace, true);
                    }
                }
                catch (XmlSchemaException e)
                {
                    throw CreateValidationException(e, e.Message);
                }
            }
        }
Beispiel #49
0
        void redrawPipeline()
        {
            if (currentSource == null)
            {
                return;
            }

            Preprocessor preprocessor = new Preprocessor();
            preprocessor.Bradley = chkBradley.Checked;
            preprocessor.ContrastAdjustment = chkContrast.Checked;
            preprocessor.ContrastStrength = numContrast.Value;
            preprocessor.ContrastStretch = chkContastStretch.Checked;
            preprocessor.FilterLevel = filterLevel;
            preprocessor.Gaussian = chkGaussian.Checked;
            preprocessor.GaussianStrength = numBlurStrength.Value;
            preprocessor.Greyscale = chkGreyscale.Checked;
            preprocessor.Histogram = chkHistogram.Checked;
            preprocessor.ImageSize = new Size(Int32.Parse(txtWidth.Text), Int32.Parse(txtHeight.Text));
            preprocessor.KeepAspectRatio = chkAspect.Checked;
            preprocessor.ScalingMethod = (ScalingMethods)cmbScalingMethod.SelectedIndex;
            preprocessor.Threshold = chkThreshold.Checked;
            preprocessor.ThresholdStrength = numThreshold.Value;

            currentSource.Preprocessor = preprocessor;

            imageViewer1.LoadImage(currentSource.InternalImage);

            if (filterLevel >= 2)
            {
                if (lstInputGroups.SelectedItem != null)
                {
                    InputGroup inputGroup = (InputGroup) lstInputGroups.SelectedItem;
                    imageViewer1.DrawInputGroupOverlay(inputGroup.InputGroupType, inputGroup.Segments);
                }
            }
        }
Beispiel #50
0
        /// <summary>
        /// Parses a Driver element.
        /// </summary>
        /// <param name="node">Element to parse.</param>
        /// <param name="componentId">Identifier for parent component.</param>
        private void ParseDriverElement(XmlNode node, string componentId)
        {
            SourceLineNumberCollection sourceLineNumbers = Preprocessor.GetSourceLineNumbers(node);
            int attributes = 0;
            int sequence   = CompilerCore.IntegerNotSet;

            // check the number of times a Driver element has been nested under this Component element
            if (null != componentId)
            {
                if (this.components.Contains(componentId))
                {
                    this.Core.OnMessage(WixErrors.TooManyElements(sourceLineNumbers, "Component", node.Name, 1));
                }
                else
                {
                    this.components.Add(componentId, null);
                }
            }

            foreach (XmlAttribute attrib in node.Attributes)
            {
                switch (attrib.LocalName)
                {
                case "AddRemovePrograms":
                    if (YesNoType.No == this.Core.GetAttributeYesNoValue(sourceLineNumbers, attrib))
                    {
                        attributes |= 0x4;
                    }
                    break;

                case "DeleteFiles":
                    if (YesNoType.Yes == this.Core.GetAttributeYesNoValue(sourceLineNumbers, attrib))
                    {
                        attributes |= 0x10;
                    }
                    break;

                case "ForceInstall":
                    if (YesNoType.Yes == this.Core.GetAttributeYesNoValue(sourceLineNumbers, attrib))
                    {
                        attributes |= 0x1;
                    }
                    break;

                case "Legacy":
                    if (YesNoType.Yes == this.Core.GetAttributeYesNoValue(sourceLineNumbers, attrib))
                    {
                        attributes |= 0x8;
                    }
                    break;

                case "PlugAndPlayPrompt":
                    if (YesNoType.No == this.Core.GetAttributeYesNoValue(sourceLineNumbers, attrib))
                    {
                        attributes |= 0x2;
                    }
                    break;

                case "Sequence":
                    sequence = this.Core.GetAttributeIntegerValue(sourceLineNumbers, attrib, 0, int.MaxValue);
                    break;

                default:
                    this.Core.UnexpectedAttribute(sourceLineNumbers, attrib);
                    break;
                }
            }

            if (!this.Core.EncounteredError)
            {
                Row row = this.Core.CreateRow(sourceLineNumbers, "MsiDriverPackages");
                row[0] = componentId;
                row[1] = attributes;
                if (CompilerCore.IntegerNotSet != sequence)
                {
                    row[2] = sequence;
                }

                this.Core.CreateWixSimpleReferenceRow(sourceLineNumbers, "CustomAction", "MsiProcessDrivers");
            }
        }
 public TokenizerProcessingDecorator(ITokenizer tokenizer, Preprocessor preprocessor)
     : this(tokenizer, preprocessor, new Postprocessor())
 {
 }
Beispiel #52
0
        public void StartEncoding(int mic, MMDevice speakers, string guid, InputDeviceManager inputManager,
                                  IPAddress ipAddress, int port, MMDevice micOutput, VOIPConnectCallback voipConnectCallback)
        {
            _stop = false;


            try
            {
                _micInputQueue.Clear();

                InitMixers();

                InitAudioBuffers();

                //Audio manager should start / stop and cleanup based on connection successfull and disconnect
                //Should use listeners to synchronise all the state

                _waveOut = new WasapiOut(speakers, AudioClientShareMode.Shared, true, 40, windowsN);

                //add final volume boost to all mixed audio
                _volumeSampleProvider = new VolumeSampleProviderWithPeak(_clientAudioMixer,
                                                                         (peak => SpeakerMax = (float)VolumeConversionHelper.ConvertFloatToDB(peak)));
                _volumeSampleProvider.Volume = SpeakerBoost;

                if (speakers.AudioClient.MixFormat.Channels == 1)
                {
                    if (_volumeSampleProvider.WaveFormat.Channels == 2)
                    {
                        _waveOut.Init(_volumeSampleProvider.ToMono());
                    }
                    else
                    {
                        //already mono
                        _waveOut.Init(_volumeSampleProvider);
                    }
                }
                else
                {
                    if (_volumeSampleProvider.WaveFormat.Channels == 1)
                    {
                        _waveOut.Init(_volumeSampleProvider.ToStereo());
                    }
                    else
                    {
                        //already stereo
                        _waveOut.Init(_volumeSampleProvider);
                    }
                }
                _waveOut.Play();

                //opus
                _encoder = OpusEncoder.Create(INPUT_SAMPLE_RATE, 1, Application.Voip);
                _encoder.ForwardErrorCorrection = false;
                _decoder = OpusDecoder.Create(INPUT_SAMPLE_RATE, 1);
                _decoder.ForwardErrorCorrection = false;

                //speex
                _speex = new Preprocessor(AudioManager.SEGMENT_FRAMES, AudioManager.INPUT_SAMPLE_RATE);
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "Error starting audio Output - Quitting! " + ex.Message);


                ShowOutputError("Problem Initialising Audio Output!");


                Environment.Exit(1);
            }

            if (micOutput != null) // && micOutput !=speakers
            {
                //TODO handle case when they're the same?

                try
                {
                    _micWaveOut = new WasapiOut(micOutput, AudioClientShareMode.Shared, true, 40, windowsN);

                    _micWaveOutBuffer           = new BufferedWaveProvider(new WaveFormat(AudioManager.INPUT_SAMPLE_RATE, 16, 1));
                    _micWaveOutBuffer.ReadFully = true;
                    _micWaveOutBuffer.DiscardOnBufferOverflow = true;

                    var sampleProvider = _micWaveOutBuffer.ToSampleProvider();

                    if (micOutput.AudioClient.MixFormat.Channels == 1)
                    {
                        if (sampleProvider.WaveFormat.Channels == 2)
                        {
                            _micWaveOut.Init(new RadioFilter(sampleProvider.ToMono()));
                        }
                        else
                        {
                            //already mono
                            _micWaveOut.Init(new RadioFilter(sampleProvider));
                        }
                    }
                    else
                    {
                        if (sampleProvider.WaveFormat.Channels == 1)
                        {
                            _micWaveOut.Init(new RadioFilter(sampleProvider.ToStereo()));
                        }
                        else
                        {
                            //already stereo
                            _micWaveOut.Init(new RadioFilter(sampleProvider));
                        }
                    }

                    _micWaveOut.Play();
                }
                catch (Exception ex)
                {
                    Logger.Error(ex, "Error starting mic audio Output - Quitting! " + ex.Message);

                    ShowOutputError("Problem Initialising Mic Audio Output!");


                    Environment.Exit(1);
                }
            }


            if (_clientStateSingleton.MicrophoneAvailable)
            {
                try
                {
                    _waveIn = new WaveIn(WaveCallbackInfo.FunctionCallback())
                    {
                        BufferMilliseconds = INPUT_AUDIO_LENGTH_MS,
                        DeviceNumber       = mic,
                    };

                    _waveIn.NumberOfBuffers = 2;
                    _waveIn.DataAvailable  += _waveIn_DataAvailable;
                    _waveIn.WaveFormat      = new WaveFormat(INPUT_SAMPLE_RATE, 16, 1);

                    _udpVoiceHandler =
                        new UdpVoiceHandler(_clientsList, guid, ipAddress, port, _decoder, this, inputManager, voipConnectCallback);
                    var voiceSenderThread = new Thread(_udpVoiceHandler.Listen);

                    voiceSenderThread.Start();

                    _waveIn.StartRecording();


                    MessageHub.Instance.Subscribe <SRClient>(RemoveClientBuffer);
                }
                catch (Exception ex)
                {
                    Logger.Error(ex, "Error starting audio Input - Quitting! " + ex.Message);

                    ShowInputError("Problem initialising Audio Input!");

                    Environment.Exit(1);
                }
            }
            else
            {
                //no mic....
                _udpVoiceHandler =
                    new UdpVoiceHandler(_clientsList, guid, ipAddress, port, _decoder, this, inputManager, voipConnectCallback);
                MessageHub.Instance.Subscribe <SRClient>(RemoveClientBuffer);
                var voiceSenderThread = new Thread(_udpVoiceHandler.Listen);
                voiceSenderThread.Start();
            }
        }
Beispiel #53
0
 public static MemoryStream PreprocessStream(Stream stmContent, Stream stmInclude)
 {
     Preprocessor pp = new Preprocessor(stmInclude);
     return pp.Preprocess(stmContent);
 }
Beispiel #54
0
        public void StartEncoding(string guid, InputDeviceManager inputManager,
                                  IPAddress ipAddress, int port)
        {
            MMDevice speakers = null;

            if (_audioOutputSingleton.SelectedAudioOutput.Value == null)
            {
                speakers = WasapiOut.GetDefaultAudioEndpoint();
            }
            else
            {
                speakers = (MMDevice)_audioOutputSingleton.SelectedAudioOutput.Value;
            }

            MMDevice micOutput = null;

            if (_audioOutputSingleton.SelectedMicAudioOutput.Value != null)
            {
                micOutput = (MMDevice)_audioOutputSingleton.SelectedMicAudioOutput.Value;
            }

            try
            {
                _micInputQueue.Clear();

                InitMixers();

                InitAudioBuffers();

                //Audio manager should start / stop and cleanup based on connection successfull and disconnect
                //Should use listeners to synchronise all the state

                _waveOut = new WasapiOut(speakers, AudioClientShareMode.Shared, true, 40, windowsN);

                //add final volume boost to all mixed audio
                _volumeSampleProvider = new VolumeSampleProviderWithPeak(_clientAudioMixer,
                                                                         (peak => SpeakerMax = (float)VolumeConversionHelper.ConvertFloatToDB(peak)));
                _volumeSampleProvider.Volume = SpeakerBoost;

                if (speakers.AudioClient.MixFormat.Channels == 1)
                {
                    if (_volumeSampleProvider.WaveFormat.Channels == 2)
                    {
                        _waveOut.Init(_volumeSampleProvider.ToMono());
                    }
                    else
                    {
                        //already mono
                        _waveOut.Init(_volumeSampleProvider);
                    }
                }
                else
                {
                    if (_volumeSampleProvider.WaveFormat.Channels == 1)
                    {
                        _waveOut.Init(_volumeSampleProvider.ToStereo());
                    }
                    else
                    {
                        //already stereo
                        _waveOut.Init(_volumeSampleProvider);
                    }
                }
                _waveOut.Play();

                //opus
                _encoder = OpusEncoder.Create(INPUT_SAMPLE_RATE, 1, Application.Voip);
                _encoder.ForwardErrorCorrection = false;

                //speex
                _speex = new Preprocessor(AudioManager.SEGMENT_FRAMES, AudioManager.INPUT_SAMPLE_RATE);
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "Error starting audio Output - Quitting! " + ex.Message);


                ShowOutputError("Problem Initialising Audio Output!");


                Environment.Exit(1);
            }

            if (micOutput != null) // && micOutput !=speakers
            {
                //TODO handle case when they're the same?

                try
                {
                    _micWaveOut = new WasapiOut(micOutput, AudioClientShareMode.Shared, true, 40, windowsN);

                    _micWaveOutBuffer           = new BufferedWaveProvider(new WaveFormat(AudioManager.INPUT_SAMPLE_RATE, 16, 1));
                    _micWaveOutBuffer.ReadFully = true;
                    _micWaveOutBuffer.DiscardOnBufferOverflow = true;

                    var sampleProvider = _micWaveOutBuffer.ToSampleProvider();

                    if (micOutput.AudioClient.MixFormat.Channels == 1)
                    {
                        if (sampleProvider.WaveFormat.Channels == 2)
                        {
                            _micWaveOut.Init(new RadioFilter(sampleProvider.ToMono()));
                        }
                        else
                        {
                            //already mono
                            _micWaveOut.Init(new RadioFilter(sampleProvider));
                        }
                    }
                    else
                    {
                        if (sampleProvider.WaveFormat.Channels == 1)
                        {
                            _micWaveOut.Init(new RadioFilter(sampleProvider.ToStereo()));
                        }
                        else
                        {
                            //already stereo
                            _micWaveOut.Init(new RadioFilter(sampleProvider));
                        }
                    }

                    _micWaveOut.Play();
                }
                catch (Exception ex)
                {
                    Logger.Error(ex, "Error starting mic audio Output - Quitting! " + ex.Message);

                    ShowOutputError("Problem Initialising Mic Audio Output!");


                    Environment.Exit(1);
                }
            }

            if (_audioInputSingleton.MicrophoneAvailable)
            {
                try
                {
                    var device = (MMDevice)_audioInputSingleton.SelectedAudioInput.Value;

                    if (device == null)
                    {
                        device = WasapiCapture.GetDefaultCaptureDevice();
                    }

                    device.AudioEndpointVolume.Mute = false;

                    _wasapiCapture                   = new WasapiCapture(device, true);
                    _wasapiCapture.ShareMode         = AudioClientShareMode.Shared;
                    _wasapiCapture.DataAvailable    += WasapiCaptureOnDataAvailable;
                    _wasapiCapture.RecordingStopped += WasapiCaptureOnRecordingStopped;

                    _udpVoiceHandler =
                        new UdpVoiceHandler(guid, ipAddress, port, this, inputManager);
                    var voiceSenderThread = new Thread(_udpVoiceHandler.Listen);

                    voiceSenderThread.Start();

                    _wasapiCapture.StartRecording();

                    MessageHub.Instance.Subscribe <SRClient>(RemoveClientBuffer);
                }
                catch (Exception ex)
                {
                    Logger.Error(ex, "Error starting audio Input - Quitting! " + ex.Message);

                    ShowInputError("Problem initialising Audio Input!");

                    Environment.Exit(1);
                }
            }
            else
            {
                //no mic....
                _udpVoiceHandler =
                    new UdpVoiceHandler(guid, ipAddress, port, this, inputManager);
                MessageHub.Instance.Subscribe <SRClient>(RemoveClientBuffer);
                var voiceSenderThread = new Thread(_udpVoiceHandler.Listen);
                voiceSenderThread.Start();
            }
        }
Beispiel #55
0
        private void redrawPipeline()
        {
            if (currentRunFile != "" && currentSource != null)
            {

                DataAccess dataAccess = new DataAccess(currentRunFile);

                int width = Convert.ToInt32(dataAccess.GetParameter("Master_Width"));
                int height = Convert.ToInt32(dataAccess.GetParameter("Master_Height"));
                bool aspect = Convert.ToBoolean(dataAccess.GetParameter("Master_Aspect"));
                int scalingMethod = Convert.ToInt32(dataAccess.GetParameter("Master_Resize"));

                chkContastStretch.Checked = Convert.ToBoolean(dataAccess.GetParameter("Filter_Stretch"));
                chkHistogram.Checked = Convert.ToBoolean(dataAccess.GetParameter("Filter_Histo"));
                chkGaussian.Checked = Convert.ToBoolean(dataAccess.GetParameter("Filter_Gaussian"));
                numBlurStrength.Value = Convert.ToInt32(dataAccess.GetParameter("Filter_BlurStr"));
                chkContrast.Checked = Convert.ToBoolean(dataAccess.GetParameter("Filter_Contrast"));
                numContrast.Value = Convert.ToDecimal(dataAccess.GetParameter("Filter_ContrastStr"));
                chkGreyscale.Checked = Convert.ToBoolean(dataAccess.GetParameter("Filter_Greyscale"));
                chkBradley.Checked = Convert.ToBoolean(dataAccess.GetParameter("Filter_Bradley"));
                chkThreshold.Checked = Convert.ToBoolean(dataAccess.GetParameter("Filter_Threshold"));
                numThreshold.Value = Convert.ToDecimal(dataAccess.GetParameter("Filter_ThresholdStr"));

                Preprocessor preprocessor = new Preprocessor();
                preprocessor.Bradley = chkBradley.Checked;
                preprocessor.ContrastAdjustment = chkContrast.Checked;
                preprocessor.ContrastStrength = numContrast.Value;
                preprocessor.ContrastStretch = chkContastStretch.Checked;
                preprocessor.FilterLevel = 1;
                preprocessor.Gaussian = chkGaussian.Checked;
                preprocessor.GaussianStrength = numBlurStrength.Value;
                preprocessor.Greyscale = chkGreyscale.Checked;
                preprocessor.Histogram = chkHistogram.Checked;
                preprocessor.ImageSize = new Size(width, height);
                preprocessor.KeepAspectRatio = aspect;
                preprocessor.ScalingMethod = (ScalingMethods)scalingMethod;
                preprocessor.Threshold = chkThreshold.Checked;
                preprocessor.ThresholdStrength = numThreshold.Value;
                imgTestImage.LoadImage(preprocessor.Process((Bitmap)currentSource.InternalImage));
            }
        }
Beispiel #56
0
        /// <summary>
        /// Parses a Condition element for Bundles.
        /// </summary>
        /// <param name="node">The element to parse.</param>
        private void ParseConditionElement(XmlNode node)
        {
            SourceLineNumberCollection sourceLineNumbers = Preprocessor.GetSourceLineNumbers(node);
            string condition = CompilerCore.GetConditionInnerText(node); // condition is the inner text of the element.
            string message   = null;

            foreach (XmlAttribute attrib in node.Attributes)
            {
                if (0 == attrib.NamespaceURI.Length || attrib.NamespaceURI == this.schema.TargetNamespace)
                {
                    switch (attrib.LocalName)
                    {
                    case "Message":
                        message = this.Core.GetAttributeValue(sourceLineNumbers, attrib, false);
                        break;

                    default:
                        this.Core.UnexpectedAttribute(sourceLineNumbers, attrib);
                        break;
                    }
                }
                else
                {
                    this.Core.UnsupportedExtensionAttribute(sourceLineNumbers, attrib);
                }
            }

            foreach (XmlNode child in node.ChildNodes)
            {
                if (XmlNodeType.Element == child.NodeType)
                {
                    if (child.NamespaceURI == this.schema.TargetNamespace)
                    {
                        this.Core.UnexpectedElement(node, child);
                    }
                    else
                    {
                        this.Core.UnsupportedExtensionElement(node, child);
                    }
                }
            }

            // Error check the values.
            if (String.IsNullOrEmpty(condition))
            {
                this.Core.OnMessage(WixErrors.ConditionExpected(sourceLineNumbers, node.Name));
            }

            if (null == message)
            {
                this.Core.OnMessage(WixErrors.ExpectedAttribute(sourceLineNumbers, node.Name, "Message"));
            }

            if (!this.Core.EncounteredError)
            {
                Row row = this.Core.CreateRow(sourceLineNumbers, "WixBalCondition");
                row[0] = condition;
                row[1] = message;

                if (null == this.addedConditionLineNumber)
                {
                    this.addedConditionLineNumber = sourceLineNumbers;
                }
            }
        }
Beispiel #57
0
        /// <summary>
        /// Parses a HelpFilter element.
        /// </summary>
        /// <param name="node">Element to process.</param>
        private void ParseHelpFilterElement(XmlNode node)
        {
            SourceLineNumberCollection sourceLineNumbers = Preprocessor.GetSourceLineNumbers(node);
            string id = null;
            string filterDefinition = null;
            string name             = null;

            foreach (XmlAttribute attrib in node.Attributes)
            {
                if (0 == attrib.NamespaceURI.Length || attrib.NamespaceURI == this.schema.TargetNamespace)
                {
                    switch (attrib.LocalName)
                    {
                    case "Id":
                        id = this.Core.GetAttributeIdentifierValue(sourceLineNumbers, attrib);
                        break;

                    case "FilterDefinition":
                        filterDefinition = this.Core.GetAttributeValue(sourceLineNumbers, attrib);
                        break;

                    case "Name":
                        name = this.Core.GetAttributeValue(sourceLineNumbers, attrib);
                        break;

                    default:
                        this.Core.UnexpectedAttribute(sourceLineNumbers, attrib);
                        break;
                    }
                }
                else
                {
                    this.Core.UnsupportedExtensionAttribute(sourceLineNumbers, attrib);
                }
            }

            if (null == id)
            {
                this.Core.OnMessage(WixErrors.ExpectedAttribute(sourceLineNumbers, node.Name, "Id"));
            }

            if (null == name)
            {
                this.Core.OnMessage(WixErrors.ExpectedAttribute(sourceLineNumbers, node.Name, "Name"));
            }

            // find unexpected child elements
            foreach (XmlNode child in node.ChildNodes)
            {
                if (XmlNodeType.Element == child.NodeType)
                {
                    if (child.NamespaceURI == this.schema.TargetNamespace)
                    {
                        this.Core.UnexpectedElement(node, child);
                    }
                    else
                    {
                        this.Core.UnsupportedExtensionElement(node, child);
                    }
                }
            }

            if (!this.Core.EncounteredError)
            {
                Row row = this.Core.CreateRow(sourceLineNumbers, "HelpFilter");
                row[0] = id;
                row[1] = name;
                row[2] = filterDefinition;
            }
        }
Beispiel #58
0
 public Evaluator(IExpressionService expressionService, Preprocessor preprocessor)
 {
     _expressionService = expressionService;
     _preprocessor = preprocessor;
 }
Beispiel #59
0
        public Optimiser(string filename)
        {
            Utils.Logger.Log("Loading stopwatch... ");
            stopWatch = new Stopwatch();
            ResultCounter = new Stopwatch();

            this.filename = filename;
            Utils.Logger.Log("Loading preprocessor parameters from " + filename);
            dataAccess = new DataAccess(filename);
            preprocessor = new Preprocessor();

            preprocessor.ImageSize = new Size(Convert.ToInt32(dataAccess.GetParameter("Master_Width")), Convert.ToInt32(dataAccess.GetParameter("Master_Height")));
            preprocessor.KeepAspectRatio = Convert.ToBoolean(dataAccess.GetParameter("Master_Aspect"));
            preprocessor.ScalingMethod = (ScalingMethods)Convert.ToInt32(dataAccess.GetParameter("Master_Resize"));
            preprocessor.ContrastStretch = Convert.ToBoolean(dataAccess.GetParameter("Filter_Stretch"));
            preprocessor.Histogram = Convert.ToBoolean(dataAccess.GetParameter("Filter_Histo"));
            preprocessor.Gaussian = Convert.ToBoolean(dataAccess.GetParameter("Filter_Gaussian"));
            preprocessor.GaussianStrength = Convert.ToInt32(dataAccess.GetParameter("Filter_BlurStr"));
            preprocessor.ContrastAdjustment = Convert.ToBoolean(dataAccess.GetParameter("Filter_Contrast"));
            preprocessor.ContrastStrength = Convert.ToDecimal(dataAccess.GetParameter("Filter_ContrastStr"));
            preprocessor.Greyscale = Convert.ToBoolean(dataAccess.GetParameter("Filter_Greyscale"));
            preprocessor.Bradley = Convert.ToBoolean(dataAccess.GetParameter("Filter_Bradley"));
            preprocessor.Threshold = Convert.ToBoolean(dataAccess.GetParameter("Filter_Threshold"));
            preprocessor.ThresholdStrength = Convert.ToDecimal(dataAccess.GetParameter("Filter_ThresholdStr"));

            /*
            dataAccess.SetParameter("Opt_Bp_LearningType", cmbLearningRateType.SelectedItem.ToString());
            dataAccess.SetParameter("Opt_Bp_InitialLearnRate", txtInitialRate.Text);
            dataAccess.SetParameter("Opt_Bp_FinalLearnRate", txtFinalRate.Text);
            dataAccess.SetParameter("Opt_Bp_JitterEpoch", txtJitterEpoch.Text);
            dataAccess.SetParameter("Opt_Bp_JitterNoiseLimit", txtJitterNoiseLimit.Text);
            dataAccess.SetParameter("Opt_Bp_MaxIterations", txtMaxIterations.Text);
            dataAccess.SetParameter("Opt_Bp_MinError", txtMinimumError.Text);
            */
            bool usePSO = false;
            bool useBP = false;
            try
            {
                useBP = Convert.ToBoolean(dataAccess.GetParameter("Opt_Bp_Enabled"));
            }
            catch (Exception)
            {
                Utils.Logger.Log("Warning unable to read BP params");
            }
            try
            {
                usePSO = Convert.ToBoolean(dataAccess.GetParameter("Opt_Pso_Enabled"));
            }
            catch (Exception)
            {
                Utils.Logger.Log("Warning unable to read PSO params");
            }

            if (usePSO && useBP)
            {
                throw new NotImplementedException("At this current time you cannot use both BP and PSO");

            }

            InputGroup[] inputGroups = dataAccess.GetInputGroups();
            SourceItem[] sourceItems = dataAccess.GetSourceItems();

            /*
            Utils.Logger.Log("Preprocessing images...");
            foreach (SourceItem item in sourceItems)
            {
                Utils.Logger.Log("Preprocessing item {0} ", item.Filename);
                item.InternalImage = preprocessor.Process((Bitmap)item.InternalImage);
            }
             */

            int total = 0;
            foreach (InputGroup inputGroup in inputGroups)
            {
                if (inputGroup.InputGroupType == InputGroupType.Grid)
                {
                    total += (inputGroup.Segments) * (inputGroup.Segments);
                }
                else
                {
                    total += inputGroup.Segments;
                }

            }

            maxIterations = Convert.ToInt32(dataAccess.GetParameter("Opt_Global_MaxIterations"));
            minError = Convert.ToDouble(dataAccess.GetParameter("Opt_Global_MinError"));
            maxTime = Convert.ToInt32(dataAccess.GetParameter("Opt_Global_MaxTime"));
            results = new float[Convert.ToInt32(dataAccess.GetParameter("Opt_Global_BufferSize"))];

            if (useBP)
            {

                int learningRateFunction = Convert.ToInt32(dataAccess.GetParameter("Opt_Bp_LearningType"));
                double initialLR = Convert.ToDouble(dataAccess.GetParameter("Opt_Bp_InitialLearnRate"));
                double finalLR = Convert.ToDouble(dataAccess.GetParameter("Opt_Bp_FinalLearnRate"));
                int jitterEpoch = Convert.ToInt32(dataAccess.GetParameter("Opt_Bp_JitterEpoch"));
                double jitterNoiseLimit = Convert.ToDouble(dataAccess.GetParameter("Opt_Bp_JitterNoiseLimit"));

                NeuronDotNet.Core.Backpropagation.LinearLayer inputLayer = new NeuronDotNet.Core.Backpropagation.LinearLayer(preprocessor.ImageSize.Width * preprocessor.ImageSize.Height);
                NeuronDotNet.Core.Backpropagation.SigmoidLayer hiddenLayer = new NeuronDotNet.Core.Backpropagation.SigmoidLayer(total);
                hiddenLayer.InputGroups = inputGroups.Length;
                NeuronDotNet.Core.Backpropagation.SigmoidLayer outputLayer = new NeuronDotNet.Core.Backpropagation.SigmoidLayer(1);

                hiddenLayer.Initializer = new NguyenWidrowFunction();

                new BackpropagationConnector(
                    inputLayer,
                    hiddenLayer,
                    inputGroups,
                    preprocessor.ImageSize.Width,
                    preprocessor.ImageSize.Height
                    );

                new BackpropagationConnector(hiddenLayer, outputLayer);

                network = new BackpropagationNetwork(inputLayer, outputLayer);

                switch (learningRateFunction)
                {
                    case 0:
                        network.SetLearningRate(initialLR);
                        break;
                    case 1:
                        network.SetLearningRate(new NeuronDotNet.Core.LearningRateFunctions.ExponentialFunction(initialLR, finalLR));//exp
                        break;
                    case 2:
                        network.SetLearningRate(new NeuronDotNet.Core.LearningRateFunctions.HyperbolicFunction(initialLR, finalLR));//hyp
                        break;
                    case 3:
                        network.SetLearningRate(new NeuronDotNet.Core.LearningRateFunctions.LinearFunction(initialLR, finalLR));//lin
                        break;

                    default:
                        throw new ArgumentOutOfRangeException("The learning rate index is out of range.\n");
                }
                network.JitterEpoch = jitterEpoch;
                network.JitterNoiseLimit = jitterNoiseLimit;

            }

            if (usePSO)
            {
                double minP = Convert.ToDouble(dataAccess.GetParameter("Opt_Pso_MinP"));
                double maxP = Convert.ToDouble(dataAccess.GetParameter("Opt_Pso_MaxP"));
                double minI = Convert.ToDouble(dataAccess.GetParameter("Opt_Pso_MinI"));
                double maxI = Convert.ToDouble(dataAccess.GetParameter("Opt_Pso_MaxI"));
                double quant = Convert.ToDouble(dataAccess.GetParameter("Opt_Pso_Quant"));
                double vMax = Convert.ToDouble(dataAccess.GetParameter("Opt_Pso_vMax"));

                int clamping = Convert.ToInt32(dataAccess.GetParameter("Opt_Pso_Clamping"));
                int initLinks = Convert.ToInt32(dataAccess.GetParameter("Opt_Pso_InitLinks"));
                int randomness = Convert.ToInt32(dataAccess.GetParameter("Opt_Pso_Randomness"));
                int randOrder = Convert.ToInt32(dataAccess.GetParameter("Opt_Pso_ParticleOrder"));
                int rotation = Convert.ToInt32(dataAccess.GetParameter("Opt_Pso_Rotation"));

                int dimensions = Convert.ToInt32(dataAccess.GetParameter("Opt_Pso_Dimensions"));
                int swarmSize = Convert.ToInt32(dataAccess.GetParameter("Opt_Pso_Particles"));
                double k = Convert.ToDouble(dataAccess.GetParameter("Opt_Pso_k"));
                double p = Convert.ToDouble(dataAccess.GetParameter("Opt_Pso_p"));
                double w = Convert.ToDouble(dataAccess.GetParameter("Opt_Pso_w"));
                double c = Convert.ToDouble(dataAccess.GetParameter("Opt_Pso_c"));

                Parameters param = new Parameters();
                param.vMax = vMax;

                param.clamping = clamping;
                // 0 => no clamping AND no evaluation. WARNING: the program
                // 				may NEVER stop (in particular with option move 20 (jumps)) 1
                // *1 => classical. Set to bounds, and velocity to zero

                param.initLink = initLinks; // 0 => re-init links after each unsuccessful iteration
                // 1 => re-init links after each successful iteration

                param.rand = randomness; // 0 => Use KISS as random number generator.
                // Any other value => use the system one

                param.randOrder = randOrder; // 0 => at each iteration, particles are modified
                //     always according to the same order 0..S-1
                //*1 => at each iteration, particles numbers are
                //		randomly permutated
                param.rotation = rotation;
                // WARNING. Experimental code, completely valid only for dimension 2
                // 0 =>  sensitive to rotation of the system of coordinates
                // 1 => non sensitive (except side effects),
                // 			by using a rotated hypercube for the probability distribution
                //			WARNING. Quite time consuming!

                param.stop = 0;	// Stop criterion
                // 0 => error < pb.epsilon
                // 1 => eval >= pb.evalMax
                // 2 => ||x-solution|| < pb.epsilon

                // ===========================================================
                // RUNs

                // Initialize some objects
                //pb = new Problem(function);

                // You may "manipulate" S, p, w and c
                // but here are the suggested values
                param.S = swarmSize;
                if (param.S > 910) param.S = 910;

                param.K = (int)k;
                param.p = p;
                // (to simulate the global best PSO, set param.p=1)
                //param.p=1;

                param.w = w;
                param.c = c;

                NeuronDotNet.Core.PSO.LinearLayer inputLayer = new NeuronDotNet.Core.PSO.LinearLayer(preprocessor.ImageSize.Width * preprocessor.ImageSize.Height);
                NeuronDotNet.Core.PSO.SigmoidLayer hiddenLayer = new NeuronDotNet.Core.PSO.SigmoidLayer(total);
                hiddenLayer.InputGroups = inputGroups.Length;
                NeuronDotNet.Core.PSO.SigmoidLayer outputLayer = new NeuronDotNet.Core.PSO.SigmoidLayer(1);

                hiddenLayer.Initializer = new NguyenWidrowFunction();

                new PSOConnector(
                    inputLayer,
                    hiddenLayer,
                    inputGroups,
                    preprocessor.ImageSize.Width,
                    preprocessor.ImageSize.Height
                    );

                new PSOConnector(hiddenLayer, outputLayer);

                PSONetwork n = new PSONetwork(inputLayer, outputLayer);

                n.PsoParameters = param;
                n.PsoProblem.MaxI = maxI;
                n.PsoProblem.MinI = minI;
                n.PsoProblem.MaxP = maxP;
                n.PsoProblem.MinP = minP;
                n.PsoProblem.Quantisation = quant;
                network = n;

            }

            set = new TrainingSet(preprocessor.ImageSize.Width * preprocessor.ImageSize.Height, 1);
            foreach (SourceItem item in sourceItems)
            {

                double[] weights = Utils.getImageWeights(item.InternalImage, inputGroups);
                set.Add(new TrainingSample(weights, new double[] { (double)item.SampleType }));

            }
            network.EndEpochEvent += new TrainingEpochEventHandler(network_EndEpochEvent);
            network.Initialize();
        }
Beispiel #60
0
        /// <summary>
        /// Parses a PlugCollectionInto element.
        /// </summary>
        /// <param name="node">Element to process.</param>
        /// <param name="parentId">Identifier of the parent help collection.</param>
        private void ParsePlugCollectionIntoElement(XmlNode node, string parentId)
        {
            SourceLineNumberCollection sourceLineNumbers = Preprocessor.GetSourceLineNumbers(node);
            string hxa             = null;
            string hxt             = null;
            string hxtParent       = null;
            string namespaceParent = null;

            foreach (XmlAttribute attrib in node.Attributes)
            {
                if (0 == attrib.NamespaceURI.Length || attrib.NamespaceURI == this.schema.TargetNamespace)
                {
                    switch (attrib.LocalName)
                    {
                    case "Attributes":
                        hxa = this.Core.GetAttributeIdentifierValue(sourceLineNumbers, attrib);
                        break;

                    case "TableOfContents":
                        hxt = this.Core.GetAttributeIdentifierValue(sourceLineNumbers, attrib);
                        break;

                    case "TargetCollection":
                        namespaceParent = this.Core.GetAttributeIdentifierValue(sourceLineNumbers, attrib);
                        break;

                    case "TargetTableOfContents":
                        hxtParent = this.Core.GetAttributeIdentifierValue(sourceLineNumbers, attrib);
                        break;

                    default:
                        this.Core.UnexpectedAttribute(sourceLineNumbers, attrib);
                        break;
                    }
                }
                else
                {
                    this.Core.UnsupportedExtensionAttribute(sourceLineNumbers, attrib);
                }
            }

            if (null == namespaceParent)
            {
                this.Core.OnMessage(WixErrors.ExpectedAttribute(sourceLineNumbers, node.Name, "TargetCollection"));
            }

            // find unexpected child elements
            foreach (XmlNode child in node.ChildNodes)
            {
                if (XmlNodeType.Element == child.NodeType)
                {
                    if (child.NamespaceURI == this.schema.TargetNamespace)
                    {
                        this.Core.UnexpectedElement(node, child);
                    }
                    else
                    {
                        this.Core.UnsupportedExtensionElement(node, child);
                    }
                }
            }

            if (!this.Core.EncounteredError)
            {
                Row row = this.Core.CreateRow(sourceLineNumbers, "HelpPlugin");
                row[0] = parentId;
                row[1] = namespaceParent;
                row[2] = hxt;
                row[3] = hxa;
                row[4] = hxtParent;
            }
        }