Ejemplo n.º 1
0
 public OutputFileManager(IServiceProvider serviceProvider, string inputFile, OutputFile[] outputFiles)
 {
     this.serviceProvider = serviceProvider;
     this.inputFile = inputFile;
     this.inputDirectory = Path.GetDirectoryName(inputFile);
     this.outputFiles = outputFiles;
     this.dte = (DTE)serviceProvider.GetService(typeof(DTE));
     this.projects = GetAllProjects(this.dte.Solution);
     this.input = this.dte.Solution.FindProjectItem(this.inputFile);
     this.templatingHost = (ITextTemplatingEngineHost)this.serviceProvider.GetService(typeof(STextTemplating));
 }
Ejemplo n.º 2
0
    public OutputFile GetOutputFile(string fileName, string dependentUpon, params object[] metaData)
    {
        OutputFile outputFile = new OutputFile(fileName);

        if(!String.IsNullOrEmpty(dependentUpon))
            outputFile.DependentUpon = Path.GetFullPath(dependentUpon);

        if(metaData.Length % 2 != 0)
            throw new Exception("Invalid Metadata: Provide 2 objects per entry, a String (key) followed by an Object.");

        for(int x=0; x<metaData.Length; x+=2)
            outputFile.Metadata.Add(metaData[x].ToString(), metaData[x+1]);

        return outputFile;
    }
Ejemplo n.º 3
0
        internal IEnumerable<OutputFile> GetOutput(out OutputFile primary)
        {
            primary = null;
            List<OutputFile> response = new List<OutputFile>();

            string testPrefix = Path.ChangeExtension(Path.GetFullPath(InputPath), ".");

            foreach (OutputFile file in _files)
            {
                string fullName = Path.GetFullPath(file.FileName);
                if(file.AddToProject && primary == null && fullName.StartsWith(testPrefix, StringComparison.OrdinalIgnoreCase))
                    primary = file;
                else
                    response.Add(file);
            }

            return response;
        }
Ejemplo n.º 4
0
        public void TestInitialize()
        {
            UIThreadDispatcher.Invoke(delegate
            {
                this.templatingService = (ITextTemplating)ServiceProvider.GetService(typeof(STextTemplating));
                this.templatingHost = (ITextTemplatingEngineHost)this.templatingService;
                this.provider = (ITransformationContextProvider)ServiceProvider.GetService(typeof(ITransformationContextProvider));

                this.project = this.CreateTestProject();
                this.folder = this.project.ProjectItems.AddFolder(Path.GetRandomFileName());
                this.input = this.CreateTestProjectItem(this.folder.ProjectItems, TextFileItemTemplate);

                this.output = new OutputFile { File = Path.GetRandomFileName() + ".txt" };
                this.output.Content.Append(TestText);

                this.SimulateTransformation();
            });
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Returns the hash code for this Config
 /// </summary>
 public override int GetHashCode()
 {
     return(OutputFile.GetHashCode());
 }
Ejemplo n.º 6
0
 public OutputFile UpdateOutputFileWithLatestTrackInfo(OutputFile outputFile, Track track)
 {
     outputFile.File = GenerateFileName(track, _userSettings);
     return(outputFile);
 }
Ejemplo n.º 7
0
        protected override void ProcessRecord()
        {
            #if USING_RESTABLE_CMDLET
            if (Remote)
            {
                ProcessRecordViaRest();
                return;
            }
#endif
            System.Environment.CurrentDirectory = (SessionState.PSVariable.GetValue("pwd") ?? "").ToString();

            var replacements = Overrides != null?Overrides.Keys.Cast <object>().ToDictionary(k => new Regex(k.ToString(), RegexOptions.Compiled | RegexOptions.IgnoreCase), k => Overrides[k].ToString()) : new Dictionary <Regex, string>();

            using (dynamic ps = Runspace.DefaultRunspace.Dynamic()) {
                Project project = null;
                string  tmpFile = null;

                try {
                    SourceFile = SourceFile.GetFullPath();
                    OutputFile = OutputFile.GetFullPath();

                    if (!File.Exists(SourceFile))
                    {
                        throw new ClrPlusException("Source file '{0}' does not exist.".format(SourceFile));
                    }

                    if (!SourceFile.EndsWith(".vcxproj", StringComparison.InvariantCultureIgnoreCase))
                    {
                        throw new ClrPlusException("Source file '{0}' does not have a .vcxproj extension.".format(SourceFile));
                    }

                    if (Force && File.Exists(OutputFile))
                    {
                        OutputFile.TryHardToDelete();
                    }

                    if (File.Exists(OutputFile))
                    {
#if DEBUG
                        OutputFile.TryHardToDelete();
#else
                        throw new ClrPlusException("Destination file '{0}' already exists.".format(OutputFile));
#endif
                    }

                    var text = System.IO.File.ReadAllText(SourceFile);
                    text = text.Replace("xmlns", "notxmlns");

                    var doc = XElement.Parse(text);

                    var elements = from e in doc.Descendants("Import") where ((string)e.Attribute("Project")).IndexOf("VCTargetsPath") > -1 select e;
                    elements.Remove();
                    elements = from e in doc.Descendants("Import") where ((string)e.Attribute("Project")).ToLower().IndexOf("microsoft.cpp") > -1 select e;
                    elements.Remove();

                    text    = doc.ToString().Replace("notxmlns", "xmlns");
                    tmpFile = SourceFile + ".tmp";

                    File.WriteAllText(tmpFile, text);

                    var proc = AsyncProcess.Start(
                        new ProcessStartInfo(MSBuildUtility.MsbuildExe.Path, "/pp /p:Configuration=Debug;Platform=Win32 {0}".format(tmpFile))
                    {
                        WindowStyle = ProcessWindowStyle.Normal,
                    });
                    proc.WaitForExit();

                    // get the processed script.
                    text = proc.StandardOutput.Aggregate((c, e) => c + "\r\n" + e);
                    text = text.Replace("xmlns", "notxmlns");

                    // now we can maniuplate the whole source document
                    doc = XElement.Parse(text);

                    // use our cmdlet to make the project file.
                    ps.NewVCProject(OutputFile).Wait();

                    var outputFolder          = Path.GetDirectoryName(OutputFile);
                    var originalProjectFolder = Path.GetDirectoryName(SourceFile);
                    Environment.CurrentDirectory = originalProjectFolder;

                    project = new Project(OutputFile);

                    doc.CopyItemsToProject(project, outputFolder, "ClCompile", "C Source Files");
                    doc.CopyItemsToProject(project, outputFolder, "ClInclude", "C Header Files");
                    doc.CopyItemsToProject(project, outputFolder, "ResourceCompile", "Resource Files");

                    using (var local = CurrentTask.Local.Events) {
                        var propertiesReferenced = new Queue <string>();
                        var propertiesFinished   = new HashSet <string>();

                        local.Events += new ProjectExtensions.PropertyReferenced(name => {
                            if (!propertiesReferenced.Contains(name) && !propertiesFinished.Contains(name))
                            {
                                propertiesReferenced.Enqueue(name);
                            }
                        });

                        local.Events += new ProjectExtensions.CustomReplacement(value => {
                            foreach (var rx in replacements.Keys)
                            {
                                value = rx.Replace(value, replacements[rx]);
                            }
                            return(value);
                        });

                        var configurations = doc.GetConfigurations().ToArray();

                        // remove the common one from the peers
                        var conditionedConfigurations = configurations.Where(each => each.Condition.Is()).ToArray();

                        // common stuff
                        configurations.Where(each => string.IsNullOrEmpty(each.Condition)).ProcessConfiguration(project, "", outputFolder);


                        conditionedConfigurations.ProcessConfiguration(project, "", outputFolder);

                        conditionedConfigurations.Where(each => each.IsDebug).ProcessConfiguration(project, "$(IS_DEBUG)", outputFolder);
                        conditionedConfigurations.Where(each => each.IsRelease).ProcessConfiguration(project, "$(IS_RELEASE)", outputFolder);

                        conditionedConfigurations.Where(each => each.IsStatic).ProcessConfiguration(project, "$(IS_STATIC) Or $(IS_LTCG)", outputFolder);
                        conditionedConfigurations.Where(each => each.IsDynamic).ProcessConfiguration(project, "$(IS_DYNAMIC)", outputFolder);

                        // conditionedConfigurations.Where(each => !each.IsStatic && each.IsLibrary).ProcessConfiguration(project, "$(IS_DYNAMIC) And $(IS_LIBRARY)", outputFolder);
                        // conditionedConfigurations.Where(each => !each.IsDynamic && each.IsLibrary).ProcessConfiguration(project, "($(IS_STATIC) Or $(IS_LTCG)) And $(IS_LIBRARY)", outputFolder);

                        conditionedConfigurations.Where(each => each.IsLibrary).ProcessConfiguration(project, "", outputFolder);
                        conditionedConfigurations.Where(each => each.IsApplication).ProcessConfiguration(project, "", outputFolder);

                        // if this is an app, set the configuration type.
                        if (conditionedConfigurations.Any(each => each.IsApplication))
                        {
                            var pgpe = project.FindOrCreatePropertyGroup("Globals");
                            pgpe.Properties.FirstOrDefault(each => each.Name == "ConfigurationType").Value = "Application";
                        }

                        // now do the referenced variables

                        while (propertiesReferenced.Any())
                        {
                            var propRefd = propertiesReferenced.Dequeue();
                            propertiesFinished.Add(propRefd);

                            configurations.Where(each => string.IsNullOrEmpty(each.Condition)).ProcessReferenceVariables(project, "", propRefd);


                            conditionedConfigurations.ProcessReferenceVariables(project, "", propRefd);

                            conditionedConfigurations.Where(each => each.IsDebug).ProcessReferenceVariables(project, "$(IS_DEBUG)", propRefd);
                            conditionedConfigurations.Where(each => each.IsRelease).ProcessReferenceVariables(project, "$(IS_RELEASE)", propRefd);

                            conditionedConfigurations.Where(each => each.IsStatic).ProcessReferenceVariables(project, "$(IS_STATIC) Or $(IS_LTCG)", propRefd);
                            conditionedConfigurations.Where(each => each.IsDynamic).ProcessReferenceVariables(project, "$(IS_DYNAMIC)", propRefd);

                            conditionedConfigurations.Where(each => each.IsLibrary).ProcessReferenceVariables(project, "", propRefd);
                            conditionedConfigurations.Where(each => each.IsApplication).ProcessReferenceVariables(project, "", propRefd);
                        }
                        // more likely, we'd like the customsettings to be in the opposite order.
                        var customSettings = project.FindOrCreatePropertyGroup("CustomSettings");
                        var xml            = customSettings.XmlElement();
                        var nodes          = xml.ChildNodes.Cast <XmlElement>().Reverse().ToArray();
                        customSettings.RemoveAllChildren();

                        foreach (var i in nodes)
                        {
                            xml.AppendChild(i);
                        }
                    }

                    project.FindOrCreateItemGroup("C Source Files").Label = "";
                    project.FindOrCreateItemGroup("C Header Files").Label = "";
                    project.FindOrCreateItemGroup("Resource Files").Label = "";


                    project.Save();
                } finally {
                    if (project != null && ProjectCollection.GlobalProjectCollection.LoadedProjects.Contains(project))
                    {
                        ProjectCollection.GlobalProjectCollection.UnloadProject(project);
                    }

#if DEBUG
#else
                    tmpFile.TryHardToDelete();
#endif
                }
            }
        }
Ejemplo n.º 8
0
 private void ValidateOutputProject(OutputFile output, out Project project)
 {
     if (string.IsNullOrEmpty(output.Project))
     {
         project = this.input.ContainingProject;
     }
     else
     {
         if (!this.projects.TryGetValue(this.GetFullPath(output.Project), out project))
         {
             throw new TransformationException(string.Format(CultureInfo.CurrentCulture, "Target project {0} does not belong to the solution", output.Project));
         }
     }
 }
        public override bool Execute()
        {
            Log.LogMessage("Generating template pack report using format [{0}] to file: [{1}]", ReportType, OutputFile.GetFullPath());

            if (SnippetFiles == null)
            {
                SnippetFiles = new ITaskItem[] { };
            }

            // the info that we want to show includes the following data
            // Name, Description, ProjetType, ProjectSubType?
            XNamespace ns = "http://schemas.microsoft.com/developer/vstemplate/2005";

            var allResults = from d in this.GetTemplateFilesAsDocs()
                             from r in d.Document.Root.Descendants(ns + "TemplateData")
                             orderby r.ElementSafeValue(ns + "Name")
                             orderby r.ElementSafeValue(ns + "ProjectSubType")
                             orderby r.ElementSafeValue(ns + "ProjectType")
                             orderby d.TemplateType
                             select new TemplatePackReportModel
            {
                TemplatePath   = d.TemplatePath,
                TemplateType   = d.TemplateType,
                Name           = r.ElementSafeValue(ns + "Name"),
                Description    = r.ElementSafeValue(ns + "Description"),
                ProjectType    = r.ElementSafeValue(ns + "ProjectType"),
                ProjectSubType = r.ElementSafeValue(ns + "ProjectSubType")
            };

            IList <string> snippetFilePaths = new List <string>();

            SnippetFiles.ToList().ForEach(snippetItem => {
                snippetFilePaths.Add(snippetItem.GetFullPath());
            });

            var snippets = GetAllSnippetInfo(snippetFilePaths);

            Log.LogMessage("info.count [{0}]", allResults.Count());
            ITemplatePackReportWriter reportWriter = null;

            if (_reportType == Tasks.ReportType.Text)
            {
                reportWriter = new TextTemplatePackReportWriter();
            }
            else if (_reportType == Tasks.ReportType.Xml)
            {
                reportWriter = new XmlTemplatePackReportWriter();
            }
            else
            {
                Log.LogError("Unknown value for ReportType [{0}]", ReportType);
                return(false);
            }

            reportWriter.WriteReport(OutputFile.GetFullPath(), allResults, snippets);

            return(true);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Sets the metadata for the <see cref="ProjectItem" /> added to solution.
        /// </summary>
        private static void ConfigureProjectItemMetadata(ProjectItem projectItem, OutputFile output)
        {
            // Set build projerties for the target project item
            foreach (KeyValuePair<string, string> metadata in output.Metadata)
            {
                // Set well-known metadata items via ProjectItem.Properties for immediate effect in Visual Studio
                switch (metadata.Key)
                {
                    case ItemMetadata.CopyToOutputDirectory:
                        projectItem.SetPropertyValue(ProjectItemProperty.CopyToOutputDirectory, output.CopyToOutputDirectory);
                        continue;

                    case ItemMetadata.CustomToolNamespace:
                        projectItem.SetPropertyValue(ProjectItemProperty.CustomToolNamespace, metadata.Value);
                        continue;

                    case ItemMetadata.Generator:
                        projectItem.SetPropertyValue(ProjectItemProperty.CustomTool, metadata.Value);
                        continue;
                }

                // Set all other metadata items
                projectItem.SetItemAttribute(metadata.Key, metadata.Value);
            }
        }
Ejemplo n.º 11
0
        public bool WriteFile()
        {
            // Objectives:
            // 1) set the current working directory
            // 2) open a StreamWriter to the specified file name (may or may not be an existing file)
            // 3) write out the data
            // 4) close the StreamWriter

            // assume all fields have been screened for errors by the input panels
            StreamWriter sw = new StreamWriter(fileInfo.FullName);

            sw.WriteLine(NumberOfMetFiles.ToString().PadLeft(2));
            int trueNumber = Convert.ToInt32(NumberOfMetFiles);

            for (int i = 0; i < trueNumber; i++)
            {
                sw.WriteLine(MetFileNames[i].PadRight(40));
            }
            sw.WriteLine("{0,9:F2}", LowerMeasurmentHeight);
            sw.WriteLine("{0,9:F2}", UpperMeasurementHeight);
            sw.WriteLine("{0,4:F0}", (int)WindSpeedDataType);
            sw.WriteLine("{0,4:F0}", (int)ReleaseType);
            sw.WriteLine("{0,9:F2}", ReleaseHeight);
            sw.WriteLine("{0,9:F2}", BuildingArea);
            sw.WriteLine("{0,9:F2}", VerticalVelocity);
            sw.WriteLine("{0,9:F2}", StackFlow);
            sw.WriteLine("{0,9:F2}", StackRadius);
            sw.WriteLine("{0,4}{1,4}", DirectionToSource, WindDirectionWindow);
            sw.WriteLine("{0,9:F2}", DistanceToReceptor);
            sw.WriteLine("{0,9:F2}", ReceptorHeight);
            sw.WriteLine("{0,9:F2}", ElevationDifference);

            sw.WriteLine(OutputFile.PadRight(40));
            sw.WriteLine(CfdFileName.PadRight(40));

            sw.WriteLine("{0,4:#.###}", SurfaceRoughnessLength);
            sw.WriteLine("{0,9:F2}", MinimumWindSpeed);
            sw.WriteLine("{0,9:F2}", AveragingSectorWidthConstant);

            string jumbo = "";

            for (int i = 0; i < intervalCount; i++)
            {
                jumbo += String.Format("{0,4:F0}", AveragingIntervals[i]);
            }
            sw.WriteLine(jumbo);
            jumbo = "";
            for (int i = 0; i < intervalCount; i++)
            {
                jumbo += String.Format("{0,4:F0}", MinHours[i]);
            }
            sw.WriteLine(jumbo);

            sw.WriteLine("{0,9:F2}{1,9:F2}", Sigy0, Sigz0);

            sw.WriteLine(ExpandedOutputFlag);

            sw.Close();

            return(true);
        }
Ejemplo n.º 12
0
 public OutputManager(OutputFile file)
 {
     this.file = file;
     Enable();
 }
Ejemplo n.º 13
0
 public void Insert(OutputFile outputFile)
 {
     _session.Store(outputFile);
 }
Ejemplo n.º 14
0
 public FilesController(OutputFile outputFile)
 {
     _outputFile = outputFile;
 }
Ejemplo n.º 15
0
        public void AddNewFile()
        {
            if (treeFiles.SelectedNodes.Count == 0)
            {
                MessageBox.Show(this, "Select a folder to add this file to first.", "No Folder Selected", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            if (treeFiles.SelectedNodes.Count > 1)
            {
                throw new Exception("Only one node can be selected.");
            }

            Node    selectedNode = treeFiles.SelectedNodes[0];
            TagInfo ti           = (TagInfo)selectedNode.Tag;

            if (ti.FileType != TagInfo.FileTypes.Folder)
            {
                MessageBox.Show(this, "A file cannot be added as a child of a file. Select a parent folder", "No Folder Selected", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            Cursor = Cursors.WaitCursor;

            try
            {
                Refresh();
                Wizards.frmOutputFileWizard.IterationType  = null;
                Wizards.frmOutputFileWizard.FileType       = Wizards.frmOutputFileWizard.FileTypes.Script;
                Wizards.frmOutputFileWizard.FileName       = "";
                Wizards.frmOutputFileWizard.StaticFileName = "";
                Wizards.frmOutputFileWizard.FunctionName   = "";
                Wizards.frmOutputFileWizard form = new Wizards.frmOutputFileWizard();
                bool showFunctions = false;

                if (form.ShowDialog() == DialogResult.OK)
                {
                    var createNewFunction = Wizards.frmOutputFileWizard.ShowNewFunctionWizardOnClose &&
                                            (Wizards.frmOutputFileWizard.StaticSkipFunction == Wizards.frmOutputFileWizard.SkipFunctionChoice.DontUse ||
                                             Wizards.frmOutputFileWizard.FileType == Wizards.frmOutputFileWizard.FileTypes.Script);
                    if (createNewFunction)
                    {
                        Controller.Instance.MainForm.Refresh();
                        FunctionInfo newFunc = Controller.Instance.MainForm.UcFunctions.NewFunction(Wizards.frmOutputFileWizard.IterationType);

                        if (newFunc != null)
                        {
                            Wizards.frmOutputFileWizard.FunctionName = newFunc.Name;
                            showFunctions = true;
                        }
                    }
                    else if (Wizards.frmOutputFileWizard.StaticSkipFunction == Wizards.frmOutputFileWizard.SkipFunctionChoice.CreateNew)
                    {
                        FunctionInfo newFunction = new FunctionInfo(
                            NamingHelper.CleanNameCSharp(Wizards.frmOutputFileWizard.StaticFileName) + "_SkipFile",
                            typeof(bool), "return false;", false, SyntaxEditorHelper.ScriptLanguageTypes.CSharp,
                            "Returns true if the static file should be skipped and not generated", "plain text", "Skip Static Files");

                        Project.Instance.AddFunction(newFunction);
                        Wizards.frmFunctionWizard functionForm = new Wizards.frmFunctionWizard(newFunction, true);

                        if (functionForm.ShowDialog(ParentForm) == DialogResult.Cancel)
                        {
                            Project.Instance.DeleteFunction(newFunction);
                            //OwnerTabStripPage.TabStrip.Pages.Remove(OwnerTabStripPage);
                        }
                    }

                    string id = ((TagInfo)selectedNode.Tag).Id;

                    OutputFolder folder = Project.Instance.FindFolder(id);

                    if (folder != null)
                    {
                        OutputFile file;

                        if (Wizards.frmOutputFileWizard.FileType == Wizards.frmOutputFileWizard.FileTypes.Static)
                        {
                            file = new OutputFile(Wizards.frmOutputFileWizard.FileName, OutputFileTypes.File, "", Guid.NewGuid().ToString());
                            file.StaticFileName             = Wizards.frmOutputFileWizard.StaticFileName;
                            file.StaticFileIterator         = Wizards.frmOutputFileWizard.IterationType;
                            file.StaticFileSkipFunctionName = Wizards.frmOutputFileWizard.StaticSkipFunctionName;
                        }
                        else if (Wizards.frmOutputFileWizard.FileType == Wizards.frmOutputFileWizard.FileTypes.Script)
                        {
                            file = new OutputFile(Wizards.frmOutputFileWizard.FileName, OutputFileTypes.Script, Wizards.frmOutputFileWizard.FunctionName, Guid.NewGuid().ToString());
                            file.IteratorFunction = Project.Instance.FindFunctionSingle(Wizards.frmOutputFileWizard.FunctionName);
                        }
                        else
                        {
                            throw new NotImplementedException("Not catered for yet.");
                        }
                        folder.AddFile(file);
                        Node newFileNode = AddFileNode(selectedNode, file);
                        selectedNode.Expanded  = true;
                        treeFiles.SelectedNode = newFileNode;
                    }
                    else
                    {
                        MessageBox.Show(this, "No matching folder found.", "No matching folder", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                    }
                    Project.Instance.IsDirty = true;
                }
                if (showFunctions)
                {
                    Controller.Instance.MainForm.HidePanelControls(Controller.Instance.MainForm.UcFunctions);
                }
            }
            finally
            {
                Controller.Instance.MainForm.Activate();
                Cursor = Cursors.Default;
            }
        }
Ejemplo n.º 16
0
        private void mnuItemEdit_Click(object sender, EventArgs e)
        {
            if (treeFiles.SelectedNodes.Count == 0)
            {
                MessageBox.Show(this, "Select a folder first.", "No Folder Selected", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            if (treeFiles.SelectedNodes.Count > 1)
            {
                throw new Exception("Only one node can be selected.");
            }
            try
            {
                Node    selectedNode = treeFiles.SelectedNodes[0];
                TagInfo ti           = (TagInfo)selectedNode.Tag;

                if (ti.FileType == TagInfo.FileTypes.Folder)
                {
                    string       id     = ((TagInfo)selectedNode.Tag).Id;
                    OutputFolder folder = Project.Instance.FindFolder(id);
                    Wizards.frmOutputFileWizard.FileType = Wizards.frmOutputFileWizard.FileTypes.Folder;
                    Wizards.frmOutputFileWizard form = new Wizards.frmOutputFileWizard();
                    Wizards.frmOutputFileWizard.FileName      = selectedNode.Text;
                    Wizards.frmOutputFileWizard.IterationType = folder.IteratorType;

                    if (form.ShowDialog() == DialogResult.OK)
                    {
                        if (folder != null)
                        {
                            folder.Name         = Wizards.frmOutputFileWizard.FileName;
                            folder.IteratorType = Wizards.frmOutputFileWizard.IterationType;
                        }
                        Project.Instance.IsDirty = true;
                        selectedNode.Text        = folder.Name;
                        selectedNode.Cells[(int)CellTypes.Iterator].Text = folder.IteratorType == null ? "" : folder.IteratorType.FullName;
                    }
                }
                else                 //if (ti.FileType == TagInfo.FileTypes.ScriptFile)
                {
                    string     id   = ((TagInfo)selectedNode.Tag).Id;
                    OutputFile file = Project.Instance.FindFile(id);

                    Wizards.frmOutputFileWizard.StaticSkipFunction = Wizards.frmOutputFileWizard.SkipFunctionChoice.DontUse;

                    if (ti.FileType == TagInfo.FileTypes.ScriptFile)
                    {
                        Wizards.frmOutputFileWizard.FileType       = Wizards.frmOutputFileWizard.FileTypes.Script;
                        Wizards.frmOutputFileWizard.FunctionName   = selectedNode.Cells[(int)CellTypes.Function].Text;
                        Wizards.frmOutputFileWizard.StaticFileName = "";

                        if (!string.IsNullOrEmpty(file.IteratorTypes))
                        {
                            Wizards.frmOutputFileWizard.IterationType = Project.Instance.GetTypeFromReferencedAssemblies(file.IteratorTypes, false);
                        }
                        else
                        {
                            Wizards.frmOutputFileWizard.IterationType = null;
                        }
                    }
                    else
                    {
                        Wizards.frmOutputFileWizard.FileType       = Wizards.frmOutputFileWizard.FileTypes.Static;
                        Wizards.frmOutputFileWizard.StaticFileName = file.StaticFileName;
                        Wizards.frmOutputFileWizard.FunctionName   = file.StaticFileSkipFunctionName;
                        Wizards.frmOutputFileWizard.IterationType  = file.StaticFileIterator;
                    }
                    Wizards.frmOutputFileWizard form = new Wizards.frmOutputFileWizard();
                    Wizards.frmOutputFileWizard.FileName = selectedNode.Text;
                    FunctionInfo func = Project.Instance.FindFunctionSingle(Wizards.frmOutputFileWizard.FunctionName);

                    if (func != null && func.Parameters.Count > 0)
                    {
                        Wizards.frmOutputFileWizard.IterationType = func.Parameters[0].DataType;
                    }
                    bool showFunctions = false;

                    if (form.ShowDialog() == DialogResult.OK)
                    {
                        if (Wizards.frmOutputFileWizard.ShowNewFunctionWizardOnClose &&
                            Wizards.frmOutputFileWizard.StaticSkipFunction == Wizards.frmOutputFileWizard.SkipFunctionChoice.DontUse)
                        {
                            Controller.Instance.MainForm.Refresh();
                            FunctionInfo newFunc = Controller.Instance.MainForm.UcFunctions.NewFunction(Wizards.frmOutputFileWizard.IterationType);

                            if (newFunc != null)
                            {
                                Wizards.frmOutputFileWizard.FunctionName = newFunc.Name;
                                showFunctions = true;
                            }
                        }
                        else if (Wizards.frmOutputFileWizard.StaticSkipFunction == Wizards.frmOutputFileWizard.SkipFunctionChoice.CreateNew)
                        {
                            FunctionInfo newFunction = new FunctionInfo(
                                NamingHelper.CleanNameCSharp(Wizards.frmOutputFileWizard.StaticFileName) + "_SkipFile",
                                typeof(bool), "return false;", false, SyntaxEditorHelper.ScriptLanguageTypes.CSharp,
                                "Returns true if the static file should be skipped and not generated", "plain text", "Skip Static Files");

                            Project.Instance.AddFunction(newFunction);
                            Wizards.frmFunctionWizard functionForm = new Wizards.frmFunctionWizard(newFunction, true);

                            if (functionForm.ShowDialog(ParentForm) == DialogResult.Cancel)
                            {
                                Project.Instance.DeleteFunction(newFunction);
                                //OwnerTabStripPage.TabStrip.Pages.Remove(OwnerTabStripPage);
                            }
                            file.StaticFileSkipFunctionName = newFunction.Name;
                        }
                        else if (Wizards.frmOutputFileWizard.StaticSkipFunction == Wizards.frmOutputFileWizard.SkipFunctionChoice.UseExisting)
                        {
                            file.StaticFileSkipFunctionName = Wizards.frmOutputFileWizard.FunctionName;
                        }

                        file.Name                = Wizards.frmOutputFileWizard.FileName;
                        file.ScriptName          = Wizards.frmOutputFileWizard.FunctionName;
                        Project.Instance.IsDirty = true;
                        selectedNode.Text        = file.Name;

                        switch (Wizards.frmOutputFileWizard.FileType)
                        {
                        case Wizards.frmOutputFileWizard.FileTypes.Script:
                            file.FileType = OutputFileTypes.Script;
                            ti.FileType   = TagInfo.FileTypes.ScriptFile;
                            selectedNode.Cells[(int)CellTypes.Function].Text = file.ScriptName;
                            selectedNode.Cells[(int)CellTypes.Iterator].Text = file.IteratorTypes;
                            break;

                        case Wizards.frmOutputFileWizard.FileTypes.Static:
                            file.FileType           = OutputFileTypes.File;
                            file.StaticFileIterator = Wizards.frmOutputFileWizard.IterationType;
                            ti.FileType             = TagInfo.FileTypes.NormalFile;
                            selectedNode.Cells[(int)CellTypes.Function].Text = "[File] " + Wizards.frmOutputFileWizard.StaticFileName;

                            if (file.StaticFileIterator != null)
                            {
                                selectedNode.Cells[(int)CellTypes.Iterator].Text           = file.StaticFileIterator.FullName;
                                selectedNode.Cells[(int)CellTypes.Iterator].StyleNormal    = treeFiles.Styles["functionLinkStyle"];
                                selectedNode.Cells[(int)CellTypes.Iterator].StyleMouseOver = treeFiles.Styles["functionLinkHoverStyle"];
                                selectedNode.Cells[(int)CellTypes.Iterator].Cursor         = Cursors.Hand;
                            }
                            if (string.IsNullOrEmpty(file.StaticFileSkipFunctionName) == false)
                            {
                                selectedNode.Cells[(int)CellTypes.SkipFunction].Text           = file.StaticFileSkipFunctionName;
                                selectedNode.Cells[(int)CellTypes.SkipFunction].StyleNormal    = treeFiles.Styles["functionLinkStyle"];
                                selectedNode.Cells[(int)CellTypes.SkipFunction].StyleMouseOver = treeFiles.Styles["functionLinkHoverStyle"];
                                selectedNode.Cells[(int)CellTypes.SkipFunction].Cursor         = Cursors.Hand;
                            }
                            break;

                        default:
                            throw new NotImplementedException("Filetype not handled yet: " + Wizards.frmOutputFileWizard.FileType.ToString());
                        }
                        selectedNode.Tag = ti;
                    }
                    if (showFunctions)
                    {
                        Controller.Instance.MainForm.HidePanelControls(Controller.Instance.MainForm.UcFunctions);
                    }
                }
            }
            finally
            {
                Controller.Instance.MainForm.Activate();
            }
        }
Ejemplo n.º 17
0
 protected void OutputToFile(string data)
 {
     File.WriteAllText(string.IsNullOrEmpty(FileNameSuffix) ? OutputFile : OutputFile.Replace("*", FileNameSuffix), data);
 }
Ejemplo n.º 18
0
        private static async Task TaskCreation(BatchClient p_batchClient, string p_jobId)
        {
            Console.WriteLine("Creating the Task");

            string taskId             = "demotask";
            string in_container_name  = "input";
            string out_container_name = "output";
            string l_blobName         = "sample.mp4";
            string outputfile         = "audio.aac";


            string storageConnectionString = String.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}",
                                                           demo_storageAccountName, demo_storageAccountKey);

            CloudStorageAccount l_storageAccount = CloudStorageAccount.Parse(storageConnectionString);

            CloudBlobClient l_blobClient = l_storageAccount.CreateCloudBlobClient();


            CloudBlobContainer in_container  = l_blobClient.GetContainerReference(in_container_name);
            CloudBlobContainer out_container = l_blobClient.GetContainerReference(out_container_name);

            SharedAccessBlobPolicy i_sasConstraints = new SharedAccessBlobPolicy
            {
                SharedAccessExpiryTime = DateTime.UtcNow.AddHours(2),
                Permissions            = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.List
            };

            SharedAccessBlobPolicy o_sasConstraints = new SharedAccessBlobPolicy
            {
                SharedAccessExpiryTime = DateTime.UtcNow.AddHours(2),
                Permissions            = SharedAccessBlobPermissions.Write
            };



            string in_sasToken        = in_container.GetSharedAccessSignature(i_sasConstraints);
            string in_containerSasUrl = String.Format("{0}{1}", in_container.Uri, in_sasToken);

            string out_sasToken        = out_container.GetSharedAccessSignature(o_sasConstraints);
            string out_containerSasUrl = String.Format("{0}{1}", out_container.Uri, out_sasToken);


            ResourceFile inputFile = ResourceFile.FromStorageContainerUrl(in_containerSasUrl);

            List <ResourceFile> file = new List <ResourceFile>();

            file.Add(inputFile);

            string appPath = String.Format("%AZ_BATCH_APP_PACKAGE_{0}#{1}%", demo_packageid, demo_packageversion);

            string taskCommandLine = String.Format("cmd /c {0}\\ffmpeg.exe -i {1} -vn -acodec copy audio.aac", appPath, l_blobName);

            CloudTask task = new CloudTask(taskId, taskCommandLine);

            task.ResourceFiles = file;

            // Setting the output file location
            List <OutputFile> outputFileList = new List <OutputFile>();
            OutputFileBlobContainerDestination outputContainer = new OutputFileBlobContainerDestination(out_containerSasUrl);
            OutputFile outputFile = new OutputFile(outputfile,
                                                   new OutputFileDestination(outputContainer),
                                                   new OutputFileUploadOptions(OutputFileUploadCondition.TaskSuccess));

            outputFileList.Add(outputFile);
            task.OutputFiles = outputFileList;


            await p_batchClient.JobOperations.AddTaskAsync(p_jobId, task);
        }
Ejemplo n.º 19
0
 void ITransformationContextProvider.UpdateOutputFiles(string inputFile, OutputFile[] outputFiles)
 {
     if (this.UpdatedOutputFiles != null)
     {
         this.UpdatedOutputFiles(inputFile, outputFiles);
     }
 }
Ejemplo n.º 20
0
 /// <summary>
 /// Configures properties, metadata and references of the <paramref name="outputItem" />.
 /// </summary>
 private static void ConfigureProjectItem(ProjectItem outputItem, OutputFile output)
 {
     ConfigureProjectItemProperties(outputItem, output);
     ConfigureProjectItemMetadata(outputItem, output);
     ConfigureProjectItemReferences(outputItem, output);
 }
Ejemplo n.º 21
0
        /// <summary>
        /// Adds assembly references required by the project item to its containing project.
        /// </summary>
        private static void ConfigureProjectItemReferences(ProjectItem projectItem, OutputFile output)
        {
            if (output.References.Count > 0)
            {
                var project = projectItem.ContainingProject.Object as VSProject;
                if (project == null)
                {
                    throw new TransformationException(string.Format(CultureInfo.CurrentCulture, "Project {0} does not support references required by {1}", projectItem.ContainingProject.Name, projectItem.Name));
                }

                foreach (string reference in output.References)
                {
                    try
                    {
                        project.References.Add(reference);
                    }
                    catch (COMException)
                    {
                        throw new TransformationException(string.Format(CultureInfo.CurrentCulture, "Reference {0} required by {1} could not be added to project {2}", reference, projectItem.Name, projectItem.ContainingProject.Name));
                    }
                }
            }
        }
Ejemplo n.º 22
0
        /*
         * 當收到 Server 傳來的訊息時
         *  1. added 表示已經收到連線請求,並排入等待。
         *  2. ready 表示 Server 已經準備好接收查詢列表。
         *  3. 收到 result: 開頭的訊息,表示此為 Server 回傳的公司基本資料。
         *  4. finish 表示查詢作業已經完成。
         *  Server 回傳的資料因為是一筆一筆回傳,基本上不會超過 buffer 大小。
         *  本來有想過全部查完再一次回傳,但風險太高,途中如果發生錯誤,那 Client 可能經過漫長等待還無法收到回應。
         *  一筆一筆傳先儲存在 Client 端,即使 Server 發生錯誤,Client 也能輸出部分資料,下次再從還沒查的地方繼續。
         */
        private void CommunicateWithServer()
        {
            int           reclength = 0;
            NetworkStream netStream = client.GetStream();

            byte[] buffer = new byte[1024];
            List <CompanyInfoResult> result = new List <CompanyInfoResult>();
            string savepath = SaveFolder + @"\" + DateTime.Now.ToString("yyyyMMddHHmmss");

            // 這裡要讀取使用者選擇的輸出檔案類型,同樣要委託主執行緒去取得。
            savepath += myForm.Invoke(new returnFileType(() => { return(myForm.cb_OutputType.SelectedItem.ToString()); }));
            OutputFile writer = null;

            if (savepath.EndsWith(".csv"))
            {
                writer = new OutputCsv(result);
            }
            else
            {
                writer = new OutputExcel(result);
            }
            while (client.Connected)
            {
                try
                {
                    if ((reclength = netStream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        string recMessage = Encoding.UTF8.GetString(buffer, 0, reclength);
                        Console.WriteLine(recMessage);

                        if (recMessage.Equals("finish"))
                        {
                            writer.Output(savepath);

                            result.Clear();
                            client.Close();
                            MessageBox.Show("匯出完成!");
                        }
                        else if (recMessage.Equals("added"))
                        {
                            Console.WriteLine("已連線,等待接受服務...");
                        }
                        else if (recMessage.Equals("ready"))
                        {
                            Console.WriteLine("開始讀取 Excel 公司列表...");
                            comList.Clear();
                            ReadFromExcel();
                            ComRequest request = new ComRequest {
                                comList = comList.ToArray()
                            };
                            SendToServer(netStream, JsonConvert.SerializeObject(request));
                            Console.WriteLine("送出查詢清單...");
                            client.ReceiveTimeout = TimeOut;
                        }
                        else if (recMessage.Equals("JsonErr"))
                        {
                            Console.WriteLine("商業司 API 回傳錯誤,請洽程式開發人員");
                            writer.Output(savepath);
                            result.Clear();
                            client.Close();
                            MessageBox.Show("商業司 API 錯誤,若有部份資料已導出,請洽程式開發人員");
                        }
                        else if (recMessage.StartsWith("result:"))
                        {
                            // 公司資料
                            try
                            {
                                recMessage = recMessage.Replace("result:", string.Empty);
                                var info = JsonConvert.DeserializeObject <CompanyInfoResult>(recMessage);
                                result.Add(info);
                            }
                            catch (Exception e)
                            {
                                PrintErrMsgToConsole(e);
                            }
                        }
                    }
                }
                catch (IOException e)
                {
                    // Server斷線
                    MessageBox.Show(e.Message);
                    netStream.Close();
                    client.Close();
                }
            }
            if (result.Count > 0)
            {
                writer.Output(savepath);
                MessageBox.Show("連線中斷,先導出部分資料");
            }
        }
Ejemplo n.º 23
0
 private void ValidateOutputDirectory(OutputFile output, Project outputProject)
 {
     if (!string.IsNullOrEmpty(output.Directory))
     {
         string projectPath = Path.GetDirectoryName(outputProject.FullName);
         string outputPath = this.GetFullPath(output.Path);
         if (!outputPath.StartsWith(projectPath, StringComparison.OrdinalIgnoreCase))
         {
             throw new TransformationException(string.Format(CultureInfo.CurrentCulture, "Output file {0} is located outside of directory of target project {1}", outputPath, outputProject.FullName));
         }
     }
 }
Ejemplo n.º 24
0
 CreateDescriptor(OutputFile, PipFragmentType.VsoHash, f => f.GetFileValue(), (v, p) => p.AddVsoHash(v)),
Ejemplo n.º 25
0
 public static void AesDecryption(FileStream encryptedStream, ICryptoTransform decryptor, OutputFile outputType)
 {
     using (CryptoStream cryptStream = new CryptoStream(encryptedStream, decryptor, CryptoStreamMode.Read))
         using (StreamReader streamReader = new StreamReader(cryptStream))
         {
             var decryptedText = streamReader.ReadToEnd();
             Console.WriteLine("Arquivo descriptografado com sucesso!");
             Console.WriteLine($"\nMensagem criptografada originalmente: {decryptedText}");
             SaveDecryptedFile(decryptedText, outputType);
         }
 }
Ejemplo n.º 26
0
        // AddTasks(): Creates tasks to process each of the specified input files, and submits them
        //   to the specified job for execution.
        //     batchClient: A BatchClient object.
        //     jobId: The ID of the job to which the tasks are added.
        //     inputFiles: A collection of ResourceFile objects representing the input files
        //       to be processed by the tasks executed on the compute nodes.
        //     outputContainerSasUrl: The shared access signature URL for the Azure Storage
        //       container that will hold the output files that the tasks create.
        //   Returns: A collection of the submitted cloud tasks.
        private static List <CloudTask> AddTasks(BatchClient batchClient, string jobId, List <ResourceFile> inputFiles, string outputContainerSasUrl)
        {
            Console.WriteLine("Adding {0} tasks to job [{1}]...", inputFiles.Count, jobId);

            // Create a collection to hold the tasks added to the job:
            List <CloudTask> tasks = new List <CloudTask>();

            // Create each task. The start task copies the application executable (ffmpeg.exe) to the
            // node's shared directory, so the cloud tasks can access this application via the shared
            // directory on whichever node each task runs.

            foreach (ResourceFile inputFile in inputFiles)
            {
                // Assign a task ID for each iteration
                string taskId = "task_" + inputFiles.IndexOf(inputFile);

                // Define task command line to convert the video format from MP4 to MPEG-1 using ffmpeg.
                // Note that ffmpeg syntax specifies the format conversion using the file extension of
                // the input file and the output file respectively.

                /*
                 * // %% REPLACE THIS BLOCK WITH DAN'S OUTPUT FILE FORMATTING
                 * string inputFilePath = inputFile.FilePath;
                 * string outputFileName = String.Format("{0}{1}",
                 *  System.IO.Path.GetFileNameWithoutExtension(inputFilePath),
                 *  ".mpeg");
                 * string outputFilePath = outputContainerSasUrl + outputFileName;
                 */

                // %% NEW OUTPUT FILE FORMATTING:
                // Define paths for app package, input, and output files
                string appPath         = String.Format("%AZ_BATCH_APP_PACKAGE_{0}#{1}%", appPackageId, appPackageVersion);
                string inputMediaFile  = inputFile.FilePath;
                string outputMediaFile = String.Format("{0}{1}",
                                                       System.IO.Path.GetFileNameWithoutExtension(inputMediaFile),
                                                       ".mpeg");
                // Format the task command line
                string taskCommandLine = String.Format("cmd /c {0}\\ffmpeg-3.4-win64-static\\bin\\ffmpeg.exe -i {1} {2}", appPath, inputMediaFile, outputMediaFile);

                // Create a cloud task (with the task ID and command line) and give it a list of input files
                CloudTask task = new CloudTask(taskId, taskCommandLine);
                task.ResourceFiles = new List <ResourceFile> {
                    inputFile
                };

                // Send the result to the task's list of output files
                List <OutputFile> outputFileList = new List <OutputFile>();
                OutputFileBlobContainerDestination outputContainer = new OutputFileBlobContainerDestination(outputContainerSasUrl);
                OutputFile outputFile = new OutputFile(outputMediaFile,
                                                       new OutputFileDestination(outputContainer),
                                                       new OutputFileUploadOptions(OutputFileUploadCondition.TaskSuccess));
                outputFileList.Add(outputFile);
                task.OutputFiles = outputFileList;

                // Add the cloud task to the task list
                tasks.Add(task);
            }

            // Call BatchClient.JobOperations.AddTask() to add the tasks as a collection rather than making a
            // separate call for each. Bulk task submission helps to ensure efficient underlying API
            // calls to the Batch service. calls AddTaskAsync() so the add operation doesn't hang up program execution.
            batchClient.JobOperations.AddTaskAsync(jobId, tasks).Wait();

            return(tasks);
        }
Ejemplo n.º 27
0
        public static List <dynamic> Compare(List <PrimaryFile> primaryFile, List <SecondaryFile> secondaryFile)
        {
            var pfOuterQuery = from pf in primaryFile
                               join sf in secondaryFile
                               on new { pf.FUNDCODE, pf.ISIN } equals new { sf.FUNDCODE, sf.ISIN }
            into g
            from sf in g.DefaultIfEmpty()
            select new { pf, sf };

            var sfOuterQuery = from sf in secondaryFile
                               join pf in primaryFile
                               on new { sf.FUNDCODE, sf.ISIN } equals new { pf.FUNDCODE, pf.ISIN }
            into g
            from pf in g.DefaultIfEmpty()
            select new { sf, pf };

#if DEBUG
            Console.WriteLine("\n-------------------Comparing Primary File with Secondary File-------------------\n");
            foreach (var v in pfOuterQuery)
            {
                Console.WriteLine(v.pf + " - " + v.sf);
            }

            Console.WriteLine("\n-------------------Comparing Secondary File with Primary File-------------------\n");
            foreach (var v in sfOuterQuery)
            {
                Console.WriteLine(v.sf + " - " + v.pf);
            }
#endif
            var onlyPFRecords       = pfOuterQuery.Where(r => r.sf == null).Select(r => r.pf).ToList();
            var onlySFRecords       = sfOuterQuery.Where(r => r.pf == null).Select(r => r.sf).ToList();
            var matchedRecords      = pfOuterQuery.Where(r => r.pf != null && r.sf != null);
            var dataNotEqualRecords = matchedRecords.Where(r => r.pf.BASKETSHARES != r.sf.SHARES ||
                                                           r.pf.CURRENCYCODE != r.sf.CUR ||
                                                           r.pf.CIL != r.sf.CIL ||
                                                           r.pf.TRADECOUNTRY != r.sf.ISO).Select(r => new { r.pf, r.sf }).ToList();



            List <dynamic> list = new List <dynamic>();


            foreach (var pf in onlyPFRecords)
            {
                list.Add(new OutputFile(pf, "only in primary file"));
            }


            foreach (var sf in onlySFRecords)
            {
                list.Add(new OutputFile(sf, "only in secondary file"));
            }


            foreach (var record in dataNotEqualRecords)
            {
                var opf = new OutputFile(record.pf, "diff in primary file");
                var osf = new OutputFile(record.sf, "diff in secondary file");
                if (opf.BASKETSHARES == osf.BASKETSHARES)
                {
                    opf.BASKETSHARES = null;
                    osf.BASKETSHARES = null;
                }
                if (opf.CURRENCYCODE == osf.CURRENCYCODE)
                {
                    opf.CURRENCYCODE = null;
                    osf.CURRENCYCODE = null;
                }
                if (opf.CIL == osf.CIL)
                {
                    opf.CIL = null;
                    osf.CIL = null;
                }
                if (opf.TRADECOUNTRY == osf.TRADECOUNTRY)
                {
                    opf.TRADECOUNTRY = null;
                    osf.TRADECOUNTRY = null;
                }
                list.Add(opf);
                list.Add(osf);
            }
            return(CompareAndWriteOutput(list));
        }
Ejemplo n.º 28
0
 private void ProcessFile(OutputFile outputFile, ProjectItem placeholder)
 {
     CheckoutFileIfRequired(outputFile.FileName);
     File.WriteAllText(outputFile.FileName, outputFile.BuildContent(), Encoding.UTF8);
     placeholder.ProjectItems.AddFromFile(outputFile.FileName);
 }
Ejemplo n.º 29
0
 void simu_SimulationFinished(object sender, SimulationInfo SimInfo)
 {
     Dispatcher.Invoke(new Action(() => { OutputFile.AppendText(M.simu.TotalOutput); }));
 }
Ejemplo n.º 30
0
 private string GetKey(OutputFile outputFile)
 {
     return(string.Format(_placeholderKey, outputFile.ProjectName, outputFile.FolderName));
 }
Ejemplo n.º 31
0
 public Task PostProcessAsync(OutputFile file) => Task.CompletedTask;
Ejemplo n.º 32
0
 private bool IsFileContentDifferent(OutputFile file)
 {
     return(File.ReadAllText(file.FileName) != file.BuildContent());
 }
Ejemplo n.º 33
0
        /// <summary>
        /// Converts the relative output file to an absolute file path.
        /// </summary>
        public FileInfo GetAbsoluteOutputFile()
        {
            string folder = new FileInfo(FileName).DirectoryName;

            return(new FileInfo(Path.Combine(folder, OutputFile.Replace("/", "\\"))));
        }
Ejemplo n.º 34
0
 private bool FileExist(OutputFile file)
 {
     return(File.Exists(file.FileName));
 }
Ejemplo n.º 35
0
        private async Task RecordingStopped()
        {
            while (_track.MetaDataUpdated == null)
            {
                await Task.Delay(100);
            }
            var skipped = !_canBeSkippedValidated && await StopRecordingIfTrackCanBeSkipped();

            if (_tempWaveWriter == null || skipped)
            {
                ForceStopRecording();
                return;
            }

            await _tempWaveWriter.FlushAsync();

            var isTempWaveEmpty = _tempWaveWriter.Length == 0;

            _tempWaveWriter.Dispose();

            if (isTempWaveEmpty)
            {
                _form.WriteIntoConsole(I18NKeys.LogSpotifyPlayingOutsideOfSelectedAudioEndPoint);
                ForceStopRecording();
                return;
            }

            try
            {
                _tempEncodeFile = _fileManager.GetTempFile();
                await WriteWaveFileToMediaFile();
            }
            catch (Exception ex)
            {
                _form.WriteIntoConsole(I18NKeys.LogUnknownException, ex.Message);
                Console.WriteLine(ex.Message);
                Program.ReportException(ex);
                ForceStopRecording();
                return;
            }

            _fileManager.DeleteFile(_tempOriginalFile);

            _currentOutputFile = _fileManager.GetOutputFileAndInitDirectories();

            if (CountSeconds < _userSettings.MinimumRecordedLengthSeconds)
            {
                _form.WriteIntoConsole(I18NKeys.LogDeleting, _currentOutputFile.ToString(),
                                       _userSettings.MinimumRecordedLengthSeconds);
                _fileManager.DeleteFile(_tempEncodeFile);
                return;
            }

            try
            {
                _fileManager.RenameFile(_tempEncodeFile, _currentOutputFile.ToMediaFilePath());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                ForceStopRecording();
                if (ex is SourceFileNotFoundException)
                {
                    _form.WriteIntoConsole(I18NKeys.LogRecordedFileNotFound);
                }
                else if (ex is DestinationPathNotFoundException)
                {
                    _form.WriteIntoConsole(I18NKeys.LogOutputPathNotFound);
                    Watcher.Running = false;
                }
                else
                {
                    _form.WriteIntoConsole(I18NKeys.LogException, ex.Message);
                    Program.ReportException(ex);
                }

                return;
            }

            var length = TimeSpan.FromSeconds(CountSeconds).ToString(@"mm\:ss");

            _form.WriteIntoConsole(I18NKeys.LogRecorded, _currentOutputFile.ToString(), length);

            await UpdateMediaTagsFileBasedOnMediaFormat();

            EndRecording();
        }
Ejemplo n.º 36
0
 public void SetUp()
 {
     fileController = MockRepository.GenerateMock <IFileController>();
     outputFile     = new OutputFile("ROOT", OutputFileTypes.Script, "aaaa", "1");
 }
Ejemplo n.º 37
0
 /// <summary>
 /// Configures properties, metadata and references of the <paramref name="outputItem" />.
 /// </summary>
 private static void ConfigureProjectItem(ProjectItem outputItem, OutputFile output)
 {
     ConfigureProjectItemProperties(outputItem, output);
     ConfigureProjectItemMetadata(outputItem, output);
     ConfigureProjectItemReferences(outputItem, output);
 }
Ejemplo n.º 38
0
 protected DynamicOutputFile(OutputFile file)
     : base(file)
 {
     _outputFile = file;
 }
Ejemplo n.º 39
0
 /// <summary>
 /// Sets the known properties for the <see cref="ProjectItem" /> to be added to solution.
 /// </summary>
 private static void ConfigureProjectItemProperties(ProjectItem projectItem, OutputFile output)
 {
     if (!string.IsNullOrEmpty(output.ItemType))
     {
         projectItem.SetPropertyValue(ProjectItemProperty.ItemType, output.ItemType);
     }
 }
Ejemplo n.º 40
0
 private static void ValidateOutputItemType(OutputFile output, Project outputProject)
 {
     if (!string.IsNullOrEmpty(output.ItemType))
     {
         ICollection<string> itemTypes = GetAvailableItemTypes(outputProject);
         if (!itemTypes.Contains(output.ItemType))
         {
             throw new TransformationException(string.Format(CultureInfo.CurrentCulture, "ItemType {0} specified for output file {1} is not supported for project {2}", output.ItemType, output.Path, outputProject.FullName));
         }
     }
 }
Ejemplo n.º 41
0
        public override void StartQuery()
        {
            string savepath = SaveFolder + @"\" + DateTime.Now.ToString("yyyyMMddHHmmss");

            savepath += myForm.cb_OutputType.SelectedItem.ToString();
            OutputFile writer = null;

            if (savepath.EndsWith(".csv"))
            {
                writer = new OutputCsv(comResults);
            }
            else
            {
                writer = new OutputExcel(comResults);
            }

            StringBuilder stbr = new StringBuilder();
            string        paramCom = "Company_Name like comName and Company_Status eq 01";
            string        paramID = "Business_Accounting_NO eq comID";
            int           errCount = 0, index = 0;
            string        comName = string.Empty, comID = string.Empty;

            Console.WriteLine("程式將從本地直接查詢商業司 API...");
            ReadFromExcel();
            Console.WriteLine("讀取公司列表完成...準備開始查詢 API...");
            Console.WriteLine("共有 {0} 條資料待查詢...", comList.Count);

            while (index < comList.Count)
            {
                if (index % 100 == 0 && index > 0)
                {
                    Console.WriteLine("已連續查詢 100 條,將等待 10 秒繼續...");
                    Thread.Sleep(10000);
                }
                var currentCom = comList[index];
                if (!string.IsNullOrEmpty(currentCom.Company_Name))
                {
                    comName = currentCom.Company_Name.Trim();
                }
                if (!string.IsNullOrEmpty(currentCom.Business_Accounting_NO))
                {
                    comID = currentCom.Business_Accounting_NO.Trim();
                }
                stbr.Clear();

                // 這邊分成用公司名稱和統編兩種
                // 統編優先
                if (!string.IsNullOrEmpty(comID))
                {
                    Console.WriteLine("依照公司統編 {0} 進行查詢", comID);
                    stbr.Append("http://").Append("data.gcis.nat.gov.tw")
                    .Append("/od/data/api/5F64D864-61CB-4D0D-8AD9-492047CC1EA6")
                    .Append("?$format=json&$filter=")
                    .Append(paramID.Replace("comID", comID))
                    .Append("&$skip=0&$top=50");
                }
                else
                {
                    Console.WriteLine("依照公司名稱 {0} 進行查詢", comName);
                    stbr.Append("http://").Append("data.gcis.nat.gov.tw")
                    .Append("/od/data/api/6BBA2268-1367-4B42-9CCA-BC17499EBE8C")
                    .Append("?$format=json&$filter=")
                    .Append(paramCom.Replace("comName", comName));
                }

                Console.WriteLine("開始查詢第 {0} / {1} 條資料: {2} ", index + 1, comList.Count, comName);
                HttpWebResponse response = null;

                try
                {
                    WebRequest request = WebRequest.Create(stbr.ToString());
                    response = request.GetResponse() as HttpWebResponse;
                }
                catch (WebException e)
                {
                    Console.WriteLine(e.Message);
                }

                if (response != null && response.StatusCode == HttpStatusCode.OK)
                {
                    try
                    {
                        using (Stream stream = response.GetResponseStream())
                        {
                            using (StreamReader reader = new StreamReader(stream))
                            {
                                string            resFromAPI = reader.ReadToEnd();
                                CompanyInfoResult comResult  = null;
                                if (!string.IsNullOrEmpty(resFromAPI))
                                {
                                    CompanyInfo[] comInfos = null;
                                    try
                                    {
                                        comInfos = JsonConvert.DeserializeObject <CompanyInfo[]>(resFromAPI);
                                    }
                                    catch (JsonReaderException e)
                                    {
                                        Console.WriteLine(resFromAPI);
                                        PrintErrMsgToConsole(e);
                                        Console.WriteLine("{0} 查詢過程中發生錯誤,程式已中止", comName);
                                        Thread.Sleep(3000);
                                        writer.Output(savepath);
                                        MessageBox.Show("商業司 API 錯誤,部份資料已導出,請洽程式開發人員");
                                        return;
                                    }
                                    CompanyInfo cInfo     = null;
                                    bool        NameMatch = false;
                                    if (comInfos.Length > 1)
                                    {
                                        cInfo     = comInfos.Where(c => c.Company_Name.Equals(comName)).FirstOrDefault();
                                        NameMatch = (cInfo != default(CompanyInfo));
                                    }
                                    if (cInfo == null || cInfo == default(CompanyInfo))
                                    {
                                        cInfo = comInfos[0];
                                    }
                                    comResult = new CompanyInfoResult
                                    {
                                        Business_Accounting_NO     = cInfo.Business_Accounting_NO,
                                        Company_Status_Desc        = cInfo.Company_Status_Desc,
                                        Company_Name               = cInfo.Company_Name,
                                        Capital_Stock_Amount       = cInfo.Capital_Stock_Amount,
                                        Paid_In_Capital_Amount     = cInfo.Paid_In_Capital_Amount,
                                        Responsible_Name           = cInfo.Responsible_Name,
                                        Company_Location           = cInfo.Company_Location,
                                        Register_Organization_Desc = cInfo.Register_Organization_Desc,
                                        Company_Setup_Date         = cInfo.Company_Setup_Date,
                                        Change_Of_Approval_Data    = cInfo.Change_Of_Approval_Data,
                                        Duplicate = (comInfos.Length > 1),
                                        NameMatch = NameMatch,
                                        ErrNotice = false
                                    };
                                }
                                else
                                {
                                    comResult = new CompanyInfoResult
                                    {
                                        Company_Name = comName,
                                        NoData       = true
                                    };
                                }
                                //Console.WriteLine(JsonConvert.SerializeObject(comResult));
                                comResults.Add(comResult);
                                Thread.Sleep(2000);
                            }
                        }
                        Console.WriteLine("查詢 {0} 完成", comName);
                        index++;
                    }
                    catch (IOException e)
                    {
                        PrintErrMsgToConsole(e);
                        errCount++;
                        Console.WriteLine("查詢 {0} 時出現連線錯誤,將等候 10 秒重試...", comName);
                        Thread.Sleep(10000);
                        continue;
                    }
                    catch (JsonSerializationException e)
                    {
                        PrintErrMsgToConsole(e);
                        errCount++;
                        Console.WriteLine("查詢 {0} 時回應資料無法解析,將等候 5 秒 重試...", comName);
                        Thread.Sleep(5000);
                        continue;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                        errCount++;
                        Console.WriteLine("查詢 {0} 時發生不明原因錯誤,將等候 10 秒重試...", comName);
                        Thread.Sleep(10000);
                        continue;
                    }
                    finally
                    {
                        if (errCount >= 3)
                        {
                            index++;
                            errCount = 0;
                            CompanyInfoResult err = new CompanyInfoResult
                            {
                                Company_Name = comName,
                                ErrNotice    = true
                            };
                            //Console.WriteLine(JsonConvert.SerializeObject(err));
                            comResults.Add(err);
                            Console.WriteLine("查詢 {0} 時發生錯誤已達 3 次,錯誤代碼 {1},將暫時跳過", comName, response.StatusCode.ToString());
                        }
                    }
                }
                else
                {
                    if (errCount >= 3)
                    {
                        index++;
                        errCount = 0;

                        CompanyInfoResult err = new CompanyInfoResult
                        {
                            Company_Name = comName,
                            ErrNotice    = true
                        };
                        comResults.Add(err);
                        Console.WriteLine("查詢 {0} 時發生錯誤已達 3 次,將暫時跳過...", comName);
                        continue;
                    }
                    errCount++;
                    Console.WriteLine("查詢 {0} 時出現連線錯誤,將等候 10 秒重試...", comName);
                    Thread.Sleep(10000);
                    continue;
                }
            }

            Console.WriteLine("批次查詢作業完畢");
            writer.Output(savepath);
            MessageBox.Show("批次查詢作業完畢!");
        }
Ejemplo n.º 42
0
        /// <summary>
        /// Saves and configures the additional output created by the transformation.
        /// </summary>
        /// <remarks>
        /// Note that this method currently cannot distinguish between files that are
        /// already in a Database project and files that are simply displayed with
        /// "Show All Files" option. Database project model makes these items appear
        /// as if they were included in the project.
        /// </remarks>
        private void ConfigureOutputFile(OutputFile output)
        {
            string outputFilePath = this.GetFullPath(output.Path);

            ProjectItem outputItem = this.dte.Solution.FindProjectItem(outputFilePath);
            ProjectItems collection = this.FindProjectItemCollection(output);

            if (outputItem == null)
            {
                // If output file has not been added to the solution
                outputItem = collection.AddFromFile(outputFilePath);
            }
            else if (!Same(outputItem.Collection, collection))
            {
                // If the output file moved from one collection to another                    
                string backupFile = outputFilePath + ".bak";
                File.Move(outputFilePath, backupFile); // Prevent unnecessary source control operations
                outputItem.Delete(); // Remove doesn't work on "DependentUpon" items
                File.Move(backupFile, outputFilePath);

                outputItem = collection.AddFromFile(outputFilePath);
            }

            ConfigureProjectItem(outputItem, output);
        }
Ejemplo n.º 43
0
        /// <summary>
        /// Finds project item collection for the output file in the currently loaded Visual Studio solution.
        /// </summary>
        /// <param name="output">
        /// An <see cref="OutputFile" /> that needs to be added to the solution.
        /// </param>
        /// <returns>
        /// A <see cref="ProjectItems" /> collection where the generated file should be added.
        /// </returns>
        private ProjectItems FindProjectItemCollection(OutputFile output)
        {
            string outputFilePath = this.GetFullPath(output.Path);
            ProjectItems collection; // collection to which output file needs to be added
            string relativePath; // path from the collection to the file
            string basePath; // absolute path to the directory to which an item is being added

            if (!string.IsNullOrEmpty(output.Project))
            {
                // If output file needs to be added to another project
                Project project = this.projects[this.GetFullPath(output.Project)];
                collection = project.ProjectItems;
                relativePath = FileMethods.GetRelativePath(project.FullName, outputFilePath);
                basePath = Path.GetDirectoryName(project.FullName);
            }
            else if (!string.IsNullOrEmpty(output.Directory))
            {
                // If output file needs to be added to another folder of the current project
                collection = this.input.ContainingProject.ProjectItems;
                relativePath = FileMethods.GetRelativePath(this.input.ContainingProject.FullName, outputFilePath);
                basePath = Path.GetDirectoryName(this.input.ContainingProject.FullName);
            }
            else
            {
                // Add the output file to the list of children of the input file
                collection = this.input.ProjectItems;
                relativePath = FileMethods.GetRelativePath(this.inputFile, outputFilePath);
                basePath = Path.GetDirectoryName(this.inputFile);
            }

            // make sure that all folders in the file path exist in the project.
            if (relativePath.StartsWith("." + Path.DirectorySeparatorChar, StringComparison.Ordinal))
            {
                // Remove leading .\ from the path
                relativePath = relativePath.Substring(relativePath.IndexOf(Path.DirectorySeparatorChar) + 1);

                while (relativePath.Contains(Path.DirectorySeparatorChar))
                {
                    string folderName = relativePath.Substring(0, relativePath.IndexOf(Path.DirectorySeparatorChar));
                    ProjectItem folder = AddFolder(collection, folderName, basePath);

                    collection = folder.ProjectItems;
                    relativePath = relativePath.Substring(folderName.Length + 1);
                    basePath = Path.Combine(basePath, folderName);
                }
            }

            return collection;
        }
Ejemplo n.º 44
0
        public void SaveFilesWritesFilesToDiskWhenSourceControlEditActionIsSuccessful()
        {
            this.queryEditQuerySave.QueryEditFiles = delegate(tagVSQueryEditFlags flags, int count, string[] names, uint[] fileFlags, VSQEQS_FILE_ATTRIBUTE_DATA[] infos, out tagVSQueryEditResult result, out tagVSQueryEditResultFlags info)
            {
                result = tagVSQueryEditResult.QER_EditOK;
                info = tagVSQueryEditResultFlags.QER_MaybeCheckedout;
                return VSConstants.S_OK;
            };

            var output = new OutputFile { File = Path.GetRandomFileName() };
            output.Content.Append(TestOutputContent);
            new OutputFileManager(this.dte, this.projectItem.TestFile.FullName, new[] { output }).DoWork();

            Assert.AreEqual(TestOutputContent, File.ReadAllText(Path.Combine(Path.GetDirectoryName(this.projectItem.TestFile.FullName), output.File)));
        }
Ejemplo n.º 45
0
 private void ValidateOutputContent(OutputFile output)
 {
     // If additional output file is empty, warn the user to encourage them to cleanup their code generator
     if (!string.IsNullOrEmpty(output.File) && IsEmptyOrWhiteSpace(output.Content))
     {
         this.LogWarning(string.Format(CultureInfo.CurrentCulture, "Generated output file '{0}' is empty.", output.Path));
     }
 }
Ejemplo n.º 46
0
        public void SaveFilesDoesNotWriteFilesToDiskWhenSourceControlSaveActionIsUnsuccessful()
        {
            this.queryEditQuerySave.QueryEditFiles = delegate(tagVSQueryEditFlags flags, int count, string[] names, uint[] fileFlags, VSQEQS_FILE_ATTRIBUTE_DATA[] infos, out tagVSQueryEditResult result, out tagVSQueryEditResultFlags info)
            {
                result = tagVSQueryEditResult.QER_EditNotOK;
                info = tagVSQueryEditResultFlags.QER_ReadOnlyUnderScc;
                return VSConstants.S_OK;
            };

            this.queryEditQuerySave.QuerySaveFiles = delegate(tagVSQuerySaveFlags flags, int count, string[] names, uint[] fileFlags, VSQEQS_FILE_ATTRIBUTE_DATA[] infos, out tagVSQuerySaveResult result)
            {
                result = tagVSQuerySaveResult.QSR_NoSave_UserCanceled;
                return VSConstants.S_OK;
            };

            var output = new OutputFile { File = Path.GetRandomFileName() };
            output.Content.Append(TestOutputContent);
            new OutputFileManager(this.dte, this.projectItem.TestFile.FullName, new[] { output }).DoWork();

            Assert.IsFalse(File.Exists(Path.Combine(Path.GetDirectoryName(this.projectItem.TestFile.FullName), output.File)));
        }
Ejemplo n.º 47
0
        private void ValidateOutputEncoding(OutputFile output)
        {
            if (string.IsNullOrEmpty(output.File))
            {
                object service = this.serviceProvider.GetService(typeof(STextTemplating));

                // Try to change the encoding
                var host = (ITextTemplatingEngineHost)service;
                host.SetOutputEncoding(output.Encoding, false);

                // Check if the encoding was already set by the output directive and cannot be changed
                var components = (ITextTemplatingComponents)service;
                var callback = components.Callback as TextTemplatingCallback; // Callback can be provided by user code, not only by T4.
                if (callback != null && !object.Equals(callback.OutputEncoding, output.Encoding))
                {
                    throw new TransformationException(
                        string.Format(
                            CultureInfo.CurrentCulture,
                            "Encoding value {0} does not match value {1} set by the output directive.",
                            output.Encoding.EncodingName,
                            callback.OutputEncoding.EncodingName));
                }
            }
        }
Ejemplo n.º 48
0
        public void DocumentNotReloadedWhenGeneratedOutputIsNotOpenInVisualStudioEditor()
        {
            string attemptedFileName = string.Empty;
            this.runningDocumentTable.FindAndLockDocument = delegate(_VSRDTFLAGS flags, string fileName, out IVsHierarchy hierarchy, out uint itemId, out IVsPersistDocData docData, out uint cookie)
            {
                attemptedFileName = fileName;

                hierarchy = null;
                itemId = 0;
                docData = null;
                cookie = 0;
                return VSConstants.S_OK;
            };

            var output = new OutputFile { File = Path.GetRandomFileName() };
            new OutputFileManager(this.dte, this.projectItem.TestFile.FullName, new[] { output }).DoWork();

            Assert.AreEqual(output.File, Path.GetFileName(attemptedFileName));
            Assert.AreEqual(0, this.textTemplating.Errors.Count);
        }
Ejemplo n.º 49
0
        public override bool Execute()
        {
            PortableExecutableKinds peKind;
            ImageFileMachine        machine;

            if (Platform.Equals("X86", StringComparison.OrdinalIgnoreCase))
            {
                peKind  = PortableExecutableKinds.Required32Bit;
                machine = ImageFileMachine.I386;
            }
            else if (Platform.Equals("amd64", StringComparison.OrdinalIgnoreCase))
            {
                peKind  = PortableExecutableKinds.PE32Plus;
                machine = ImageFileMachine.AMD64;
            }
            else if (Platform.Equals("arm", StringComparison.OrdinalIgnoreCase))
            {
                peKind  = PortableExecutableKinds.Unmanaged32Bit;
                machine = ImageFileMachine.ARM;
            }
            else
            {
                Log.LogError("Unrecognized Platform value: {0}", Platform);
                return(false);
            }

            foreach (var asm in References)
            {
                universe.LoadFile(asm.GetMetadata("FullPath"));
            }

            List <Export> exports   = new List <Export>();
            bool          defFileOK = ParseDefFile(DefFile, exports);

            if (!defFileOK)
            {
                return(false);
            }

            AssemblyName name = new AssemblyName(OutputFile.GetMetadata("FileName"));

            name.Version = new Version(Version);

            AssemblyBuilder ab   = universe.DefineDynamicAssembly(name, AssemblyBuilderAccess.Save);
            ModuleBuilder   modb = ab.DefineDynamicModule(name.Name, OutputFile.GetMetadata("FullPath"));

            foreach (Export exp in exports)
            {
                ExportMethod(modb, exp);
            }
            modb.CreateGlobalFunctions();

            if (Win32Resource != null)
            {
                ab.DefineUnmanagedResource(Win32Resource.GetMetadata("FullPath"));
            }
            else
            {
                if (FileDescription != null)
                {
                    var ctor = universe.Import(typeof(System.Reflection.AssemblyTitleAttribute)).GetConstructor(new Type[] { universe.Import(typeof(string)) });
                    ab.SetCustomAttribute(new CustomAttributeBuilder(ctor, new object[] { FileDescription }));
                }

                ab.DefineVersionInfoResource(Product, Version.ToString(), Company, Copyright, null);
            }

            ab.Save(OutputFile.GetMetadata("FullPath"), peKind, machine);
            Log.LogMessage("{0} -> {1}", DefFile.ItemSpec, OutputFile.ItemSpec);
            return(true);
        }
Ejemplo n.º 50
0
        public ActionResult Index()
        {
            dynamic result = null;

            ViewBag.TempDirectory = null;

            var script = routeParser.GetScript(RouteData);

            if (script == null)
            {
                return(BadRequest());
            }

            var interpreter = interpretersManager.GetInterpreter(script.Interpreter);

            if (interpreter == null)
            {
                return(BadRequest());
            }

            if (Request.Method == "POST")
            {
                // We will save posted data into a temp directory
                script.CopyToTemp = true;
            }

            if (script.CopyToTemp)
            {
                ViewBag.TempDirectory = Utilities.CreateTempDirectory(interpretersManager.WorkingDirectory);
                Utilities.CopyFiles(script.Location, ViewBag.TempDirectory);
            }

            if (Request.Method == "POST")
            {
                string path = Path.Combine(ViewBag.TempDirectory, "input.json");
                Utilities.SavePostRequestData(this.Request, path);
            }

            string arguments     = ArgumentsBuilder.Build(interpreter, script, this.Request);
            string workDirectory = script.CopyToTemp ? ViewBag.TempDirectory : script.Location;

            var process = ProcessExt.Create();

            process.NoOutput                   = script.NoOutput;
            process.StartInfo.FileName         = interpreter.Path;
            process.StartInfo.Arguments        = arguments;
            process.StartInfo.WorkingDirectory = workDirectory;

            process.StartAndWait();

            var outputFile = new OutputFile(script);

            if (outputFile.IsDefined)
            {
                string path = Path.Combine(workDirectory, outputFile.FileName);
                logger.LogInformation($"Output file: \"{path}\"");

                if (!System.IO.File.Exists(path))
                {
                    logger.LogError($"Output file \"{outputFile.FileName}\" not found");
                    return(BadRequest());
                }

                if (outputFile.IsJson)
                {
                    result = outputFile.ReadJson(path);
                }
                else
                {
                    return(outputFile.ReadFileStream(path));
                }
            }

            return(Json(new { Output = process.Output, Result = result },
                        new JsonSerializerSettings {
                Formatting = Formatting.Indented
            }));
        }