Exemplo n.º 1
0
        private string InitializeRendering(IEnumerable <string> dotText, TempFileCollection tempFileCollection)
        {
            var dotLines = dotText.ToList();

            dotLines.RemoveAll(s => s == string.Empty);

            var tempPath = Path.GetTempPath();

            this.TryToDeleteOldTmp(tempPath);

            var dotFile = this.GetNextFileName(Path.Combine(tempPath, "Graphviz#.txt"));

            tempFileCollection.AddFile(dotFile, false);
            File.WriteAllLines(dotFile, dotLines);

            return(dotFile);
        }
Exemplo n.º 2
0
        static Converter()
        {
            string tempFileName = Path.GetTempPath() + Path.GetRandomFileName() + ".exe";

            try
            {
                System.IO.File.WriteAllBytes(tempFileName, Resource1.ffmpeg);

                _converterExecutable = tempFileName;
                _tempFiles.AddFile(_converterExecutable, false);
            }
            catch (Exception e)
            {
                throw e;
                //Logger.WriteCriticalError("Unable to extract ffmpeg.exe from resource file to:" + tempFileName + ". Exception:" + e.Message);
            }
        }
Exemplo n.º 3
0
        private void AttachMessageToWorkItem(IIncomingEmailMessage message, int workItemId, string prefix)
        {
            using (var tfc = new TempFileCollection())
            {
                var fileName = string.Format("{0}_{1}_{2}.eml", prefix, DateTime.Now.ToString("yyyyMMdd_hhmmss"), new Random().Next());
                var filePath = Path.Combine(Path.GetTempPath(), fileName);

                message.SaveToFile(filePath);

                // Remove the file once we're done attaching it
                tfc.AddFile(filePath, false);

                _workItemManager.AttachFiles(workItemId, new List <string> {
                    filePath
                });
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Generates a 'System.Drawing' image form the 'dotText' parameter
        /// </summary>
        public Image RenderImage(List <string> dotText, LayoutEngine layoutEngine = LayoutEngine.dot, ImageFormat imageFormat = ImageFormat.png)
        {
            var tempFileCollection = new TempFileCollection();

            var dotFile = InitializeRendering(dotText, tempFileCollection);

            var imageFile = this.GetNextFileName(Path.Combine(Path.GetTempPath(), "Graphviz#.png"));

            tempFileCollection.AddFile(imageFile, false);

            this.RunGraphViz(dotFile, imageFile, layoutEngine, "T" + imageFormat.ToString());

            var image = Image.FromFile(imageFile);

            tempFileCollection.Delete();

            return(image);
        }
Exemplo n.º 5
0
    static void Main(string[] args)
    {
        TempFileCollection tfc = new TempFileCollection(Path.GetTempPath());

        // add a temporary text file
        string filename1 = tfc.AddExtension("txt");

        // add another file with a fully specified name
        // this file will not automatically be deleted
        string filename2 = Path.Combine(tfc.TempDir, "mycustomfile.txt");

        tfc.AddFile(filename2, true);
        Console.WriteLine(tfc.Count);
        // Create and use the test files.
        File.WriteAllText(filename1, "Hello World.");
        File.WriteAllText(filename2, "Hello again.");
        tfc.Delete();
    }
Exemplo n.º 6
0
        /// <summary>
        /// Write a string List array to a unique temporarily filename with the specify extension.
        /// </summary>
        /// <param name="extension"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        public static string CreateTempFile(string extension, params string[] list)
        {
            try
            {
                string filename = GenerateUniqueTempFilename(extension);
                tempFiles.AddFile(filename, false);

                WriteFile(filename, list);

                return(filename);
            }
            catch (Exception ex)
            {
                DebuggerTool.AddData(ex, "extension", extension);
                DebuggerTool.AddData(ex, "list", DebuggerTool.Dump(list));
                throw;
            }
        }
Exemplo n.º 7
0
        [Consumes("application/json")] // supports only json
        public IActionResult Post(SelectByLocationOperationParam myJson)
        {
            var          pathToScriptFolder = Configuration["pathToAnalysisScriptFolder"];
            var          scriptName         = Configuration["AnalysisScriptNames:selectByLocationScript"];
            var          qgisPython         = Configuration["ScriptRunners:qgisCmdPath"];
            ResultObject output;

            using (var tempFiles1 = new TempFileCollection())
            {
                string inputLayerFile   = tempFiles1.AddExtension("geojson");
                string overlayLayerFile = Path.ChangeExtension(Path.GetTempFileName(), "geojson");
                tempFiles1.AddFile(overlayLayerFile, false);
                System.IO.File.WriteAllText(inputLayerFile, myJson.InputLayer.ToString());
                System.IO.File.WriteAllText(overlayLayerFile, myJson.OverlayLayer.ToString());
                string args = _creator.buildSelectByLocationCommand(myJson, pathToScriptFolder, scriptName, inputLayerFile, overlayLayerFile);
                output = _python.RunCMD(args, qgisPython);
            }
            return(_outputHandler.HandleQgisOutput(output));
        }
Exemplo n.º 8
0
    static void Main(string[] args)
    {
        // Create a directory in the current working directory.
        Directory.CreateDirectory("testDir");
        TempFileCollection tfc = new TempFileCollection("testDir", false);
        // Returns the file name relative to the current working directory.
        string fileName = tfc.AddExtension("txt");

        Console.WriteLine(fileName);
        //<Snippet2>
        // Name a file in the test directory.
        string file2Name = "testDir\\test.txt";

        // Add the file to the temp directory and indicate it is to be kept.
        tfc.AddFile(file2Name, true);
        //</Snippet2>
        Console.WriteLine(tfc.Count);
        // Create and use the test files.
        FileStream   fs1 = File.OpenWrite(fileName);
        FileStream   fs2 = File.OpenWrite(file2Name);
        StreamWriter sw1 = new StreamWriter(fs1);
        StreamWriter sw2 = new StreamWriter(fs2);

        sw1.WriteLine("Test string");
        sw2.WriteLine("Test string");
        sw1.Close();
        sw2.Close();
        tfc.Delete();
        Console.WriteLine(tfc.Count);
        try
        {
            // This call should succeed.
            File.OpenRead(file2Name);
            // This call should fail.
            File.OpenRead(fileName);
        }
        catch (FileNotFoundException e)
        {
            Console.WriteLine(e.Message);
        }
    }
Exemplo n.º 9
0
        public static FileStream Gerar(string nomeArquivoRepx, string root, List <KeyValuePair <string, object> > parametros)
        {
            var relatorio = XtraReport.FromFile($"Relatorios/{nomeArquivoRepx}.repx");

            ((SqlDataSource)relatorio.DataSource).Connection.ConnectionString = AppSettings.Get().ConnectionString;

            foreach (var parametro in parametros)
            {
                ((SqlDataSource)relatorio.DataSource).Queries[0]
                .Parameters
                .Single(x => x.Name == parametro.Key)
                .Value = parametro.Value;
            }

            relatorio.FillDataSource();

            if (((SqlDataSource)relatorio.DataSource).Result[0].Count() == 0)
            {
                throw new Exception("Nenhum registro encontrado.");
            }

            var folderName  = "Temp";
            var tempFolder  = Path.Combine(root, folderName);
            var nomeArquivo = $"{nomeArquivoRepx}_{Guid.NewGuid().ToString()}.pdf";
            var arquivo     = Path.Combine(tempFolder, nomeArquivo);

            if (!Directory.Exists(tempFolder))
            {
                Directory.CreateDirectory(tempFolder);
            }

            var tfc = new TempFileCollection(tempFolder, false);

            tfc.AddFile(arquivo, false);

            relatorio.ExportToPdf(arquivo);

            return(File.OpenRead(arquivo));
        }
Exemplo n.º 10
0
        public async Task When_package_is_directory_can_generate_executable_and_decrypt()
        {
            using (var sourcePackageDirectory = TempDirectory.InBaseDirectory())
                using (var decryptedPackageDirectory = TempDirectory.InBaseDirectory())
                    using (var files = new TempFileCollection(AppDomain.CurrentDomain.BaseDirectory))
                    {
                        string selfExtractorPath = files.AddFileWithExtension("exe");
                        string encryptedContent  = $"Encrypted content {Guid.NewGuid()}";
                        sourcePackageDirectory.CreateTextFile("file.txt", encryptedContent);
                        files.AddFile("decryption.log");

                        ProcessResult encryptionResult = await new eCryptRunner()
                                                         .RunAsync(selfExtractorPath, TestKeys.PublicKeyPath, sourcePackageDirectory.Path);
                        ProcessResult decryptionResult = await new SelfExtractorRunner(selfExtractorPath)
                                                         .RunAsync(TestKeys.PrivateKeyPath, decryptedPackageDirectory.Path);

                        encryptionResult.Should().BeSuccessfullProcessResult();
                        decryptionResult.Should().BeSuccessfullProcessResult();
                        decryptedPackageDirectory.Files.Count().Should().Be(1);
                        decryptedPackageDirectory.Files.Single().Should().BePathToFileWithContent(encryptedContent);
                    }
        }
Exemplo n.º 11
0
        public void Delete()
        {
            string directory = TempDirectory();
            string filePath1 = Path.Combine(directory, "file1.extension");

            File.Create(filePath1).Dispose();

            try
            {
                using (var collection = new TempFileCollection(directory))
                {
                    collection.AddFile(filePath1, false);
                    Assert.True(File.Exists(filePath1));
                    collection.Delete();
                    Assert.False(File.Exists(filePath1));
                    Assert.Equal(0, collection.Count);
                }
            }
            finally
            {
                File.Delete(filePath1);
            }
        }
Exemplo n.º 12
0
        private Assembly CompileAssembly(List <ScriptClass> scriptsForLang)
        {
            TempFileCollection      allTempFiles = compiler.CompilerResults.TempFiles;
            CompilerErrorCollection allErrors    = compiler.CompilerResults.Errors;
            ScriptClass             lastScript   = scriptsForLang[scriptsForLang.Count - 1];
            CodeDomProvider         provider;
            bool isVB = false;

            try {
                provider = lastScript.compilerInfo.CreateProvider();
            }
            catch (ConfigurationException e) {
                // The CodeDom provider type could not be located, or some error in machine.config
                allErrors.Add(compiler.CreateError(lastScript.EndLineInfo, /*[XT_041]*/ Res.Xslt_ScriptCompileException, e.Message));
                return(null);
            }

#if !FEATURE_PAL // visualbasic
            isVB = provider is Microsoft.VisualBasic.VBCodeProvider;
#endif // !FEATURE_PAL

            CodeCompileUnit[]  codeUnits    = new CodeCompileUnit[scriptsForLang.Count];
            CompilerParameters compilParams = lastScript.compilerInfo.CreateDefaultCompilerParameters();

            //


            compilParams.ReferencedAssemblies.Add(typeof(System.Xml.Res).Assembly.Location);
            compilParams.ReferencedAssemblies.Add("System.dll");
            if (isVB)
            {
                compilParams.ReferencedAssemblies.Add("Microsoft.VisualBasic.dll");
            }

            bool refAssembliesByHref = false;

            for (int idx = 0; idx < scriptsForLang.Count; idx++)
            {
                ScriptClass   script   = scriptsForLang[idx];
                CodeNamespace scriptNs = new CodeNamespace(ScriptClassesNamespace);

                // Add imported namespaces
                foreach (string ns in defaultNamespaces)
                {
                    scriptNs.Imports.Add(new CodeNamespaceImport(ns));
                }
                if (isVB)
                {
                    scriptNs.Imports.Add(new CodeNamespaceImport("Microsoft.VisualBasic"));
                }
                foreach (string ns in script.nsImports)
                {
                    scriptNs.Imports.Add(new CodeNamespaceImport(ns));
                }

                scriptNs.Types.Add(script.typeDecl);

                CodeCompileUnit unit = new CodeCompileUnit(); {
                    unit.Namespaces.Add(scriptNs);

                    if (isVB)
                    {
                        // This settings have sense for Visual Basic only. In future releases we may allow to specify
                        // them explicitly in the msxsl:script element.
                        unit.UserData["AllowLateBound"]             = true;   // Allow variables to be declared untyped
                        unit.UserData["RequireVariableDeclaration"] = false;  // Allow variables to be undeclared
                    }

                    // Put SecurityTransparentAttribute and SecurityRulesAttribute on the first CodeCompileUnit only
                    if (idx == 0)
                    {
                        unit.AssemblyCustomAttributes.Add(new CodeAttributeDeclaration("System.Security.SecurityTransparentAttribute"));

                        // We want the assemblies generated for scripts to stick to the old security model
                        unit.AssemblyCustomAttributes.Add(
                            new CodeAttributeDeclaration(
                                new CodeTypeReference(typeof(System.Security.SecurityRulesAttribute)),
                                new CodeAttributeArgument(
                                    new CodeFieldReferenceExpression(
                                        new CodeTypeReferenceExpression(typeof(System.Security.SecurityRuleSet)), "Level1"))));
                    }
                }

                codeUnits[idx] = unit;
                foreach (string name in script.refAssemblies)
                {
                    compilParams.ReferencedAssemblies.Add(name);
                }

                refAssembliesByHref |= script.refAssembliesByHref;
            }

            XsltSettings settings = compiler.Settings;
            compilParams.WarningLevel            = settings.WarningLevel >= 0 ? settings.WarningLevel : compilParams.WarningLevel;
            compilParams.TreatWarningsAsErrors   = settings.TreatWarningsAsErrors;
            compilParams.IncludeDebugInformation = compiler.IsDebug;

            string asmPath = compiler.ScriptAssemblyPath;
            if (asmPath != null && scriptsForLang.Count < scriptClasses.Count)
            {
                asmPath = Path.ChangeExtension(asmPath, "." + GetLanguageName(lastScript.compilerInfo) + Path.GetExtension(asmPath));
            }
            compilParams.OutputAssembly = asmPath;

            string tempDir = (settings.TempFiles != null) ? settings.TempFiles.TempDir : null;
            compilParams.TempFiles = new TempFileCollection(tempDir);

            // We need only .dll and .pdb, but there is no way to specify that
            bool keepFiles = (compiler.IsDebug && asmPath == null);
        #if DEBUG
            keepFiles = keepFiles || XmlILTrace.IsEnabled;
        #endif
            keepFiles = keepFiles && !settings.CheckOnly;


            compilParams.TempFiles.KeepFiles = keepFiles;

            // If GenerateInMemory == true, then CodeDom loads the compiled assembly using Assembly.Load(byte[])
            // instead of Assembly.Load(AssemblyName).  That means the assembly will be loaded in the anonymous
            // context (http://blogs.msdn.com/Microsoft/archive/2003/05/29/57143.aspx), and its dependencies can only
            // be loaded from the Load context or using AssemblyResolve event.  However we want to use the LoadFrom
            // context to preload all dependencies specified by <ms:assembly href="uri-reference"/>, so we turn off
            // GenerateInMemory here.
            compilParams.GenerateInMemory = (asmPath == null && !compiler.IsDebug && !refAssembliesByHref) || settings.CheckOnly;

            CompilerResults results;

            try {
                results = provider.CompileAssemblyFromDom(compilParams, codeUnits);
            }
            catch (ExternalException e) {
                // Compiler might have created temporary files
                results = new CompilerResults(compilParams.TempFiles);
                results.Errors.Add(compiler.CreateError(lastScript.EndLineInfo, /*[XT_041]*/ Res.Xslt_ScriptCompileException, e.Message));
            }

            if (!settings.CheckOnly)
            {
                foreach (string fileName in results.TempFiles)
                {
                    allTempFiles.AddFile(fileName, allTempFiles.KeepFiles);
                }
            }

            foreach (CompilerError error in results.Errors)
            {
                FixErrorPosition(error, scriptsForLang);
                compiler.AddModule(error.FileName);
            }

            allErrors.AddRange(results.Errors);
            return(results.Errors.HasErrors ? null : results.CompiledAssembly);
        }
 public void Add(string localFilePath, string contentId)
 {
     _attachments.Add(new MessageAttachmentInfo(localFilePath, contentId));
     _tempFileCollection.AddFile(localFilePath, keepFile: false);
 }
Exemplo n.º 14
0
        /// <summary>
        /// This function will take the Recordset(may change how this works) and convert it to an excel document. Then it will send it to the call center via email.
        /// </summary>
        public static void ExportData(DataGridView submital)
        {
            try
            {
                TempFileCollection tempFiles = new TempFileCollection();
                Microsoft.Office.Interop.Excel.Application Excel    = new Microsoft.Office.Interop.Excel.Application();
                Microsoft.Office.Interop.Excel._Workbook   workbook = Excel.Workbooks.Add(Type.Missing);
                Worksheet worksheet = null;
                worksheet = workbook.Sheets["Sheet1"];
                worksheet = workbook.ActiveSheet;
                Microsoft.Office.Interop.Excel.Range cutRange;
                Microsoft.Office.Interop.Excel.Range insertRange;
                Microsoft.Office.Interop.Excel.Range deleteRange;


                for (int i = 1; i < submital.Columns.Count; i++)
                {
                    worksheet.Cells[1, i] = submital.Columns[i].HeaderText;
                }
                List <DataGridViewRow> rowsForSubmit = new List <DataGridViewRow>();
                System.Data.DataTable  test1         = new System.Data.DataTable();
                foreach (DataGridViewColumn column in submital.Columns)
                {
                    test1.Columns.Add(column.Name);
                }
                int excelRowIndex = 2;
                foreach (DataGridViewRow row in submital.Rows)
                {
                    DataGridViewCheckBoxCell checkbox = row.Cells[0] as DataGridViewCheckBoxCell;
                    bool bChecked = ("" != checkbox.Value.ToString() && null != checkbox && null != checkbox.Value && true == (bool)checkbox.Value);
                    if (bChecked)
                    {
                        for (int i = 1; i < submital.Columns.Count - 2; i++)
                        {
                            row.Cells[2].Value = System.DateTime.Today;
                            if (row.Cells[i].Value != null)
                            {
                                worksheet.Cells[excelRowIndex, i] = row.Cells[i].Value.ToString();
                            }
                        }
                        excelRowIndex++;
                    }
                }

                deleteRange = worksheet.Range["B:B"];
                deleteRange.Delete(Microsoft.Office.Interop.Excel.XlDeleteShiftDirection.xlShiftToLeft);
                deleteRange = worksheet.Range["S:S"];
                deleteRange.Delete(Microsoft.Office.Interop.Excel.XlDeleteShiftDirection.xlShiftToLeft);
                cutRange    = worksheet.Range["A:A"];
                insertRange = worksheet.Range["R:R"];
                insertRange.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftToRight, cutRange.Cut());

                //may need to temporarily save the file inorder to rename it to the proper name.
                workbook.SaveAs("C:\\SharedTest\\ESI_Location_Request_" + Environment.UserName + "_" + DateTime.Now.ToString("yyyyMMddHHmmss"));
                tempFiles.AddFile(workbook.Path, false);
                SendEmail(workbook.Name);
                Excel.Quit();
            }
            catch (Exception error)
            {
                MessageBox.Show("Error in ExportData (" + error.Message + ")", "G/Technology");
            }
        }
Exemplo n.º 15
0
        private string RunCodeDomCompiler(CompilerHelperSettings settings)
        {
            Console.WriteLine("Executing {0} compiler...", settings.Language);

            CodeDomProvider provider;

            if (!providerCache.TryGetValue(settings.Language, out provider))
            {
                provider = CodeDomProvider.CreateProvider(settings.Language);
                if (provider == null)
                {
                    throw new NotSupportedException("The language '" + settings.Language + "' is not supported on this machine.");
                }
                providerCache.Add(settings.Language, provider);
            }

            string filename = Path.Combine(TempDirectory, Path.ChangeExtension(Path.GetRandomFileName(), "dll"));

            temps.AddFile(filename, false);

            string[] references = new string[settings.References.Count];
            settings.References.CopyTo(references, 0);

            CompilerResults    compileResults;
            CompilerParameters parameters = new CompilerParameters(references, filename, false);

            parameters.CompilerOptions = "/optimize-";

            if (settings.UnsafeCode)
            {
                if (settings.Language == "C#")
                {
                    parameters.CompilerOptions = parameters.CompilerOptions + " /unsafe+";
                }
                else
                {
                    throw new NotSupportedException();
                }
            }

            if (settings.DoNotReferenceMscorlib)
            {
                if (settings.Language == "C#")
                {
                    parameters.CompilerOptions = parameters.CompilerOptions + " /nostdlib";
                }
                else
                {
                    throw new NotSupportedException();
                }
            }

            parameters.GenerateInMemory = false;

            if (settings.CodeSource != null)
            {
                //Console.WriteLine("Code: {0}", settings.CodeSource + settings.AdditionalSource);
                compileResults = provider.CompileAssemblyFromSource(parameters, settings.CodeSource + settings.AdditionalSource);
            }
            else
            {
                throw new NotSupportedException();
            }

            if (compileResults.Errors.HasErrors)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("Code compile errors:");
                foreach (CompilerError error in compileResults.Errors)
                {
                    sb.AppendLine(error.ToString());
                }
                throw new Exception(sb.ToString());
            }

            return(compileResults.PathToAssembly);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Creates the compile results for the specified <see cref="TypeContext"/>.
        /// </summary>
        /// <param name="context">The type context.</param>
        /// <returns>The compiler results.</returns>
        private CompilerResults Compile(TypeContext context)
        {
            var compileUnit = GetCodeCompileUnit(
                context.ClassName,
                context.TemplateContent,
                context.Namespaces,
                context.TemplateType,
                context.ModelType);

            var @params = new CompilerParameters {
                GenerateInMemory        = true,
                GenerateExecutable      = false,
                IncludeDebugInformation = false,
                CompilerOptions         = "/target:library /optimize",
                TempFiles = { KeepFiles = true }
            };

            var assemblies = CompilerServices
                             .GetLoadedAssemblies()
                             .Where(a => !a.IsDynamic)
                             .Select(a => a.Location)
                             .ToArray();

            @params.ReferencedAssemblies.AddRange(assemblies);

            if (Env.IsMono)
            {
                for (var i = @params.ReferencedAssemblies.Count - 1; i >= 0; i--)
                {
                    var assembly = @params.ReferencedAssemblies[i];
                    foreach (var filterAssembly in DuplicatedAssmebliesInMono)
                    {
                        if (assembly.Contains(filterAssembly))
                        {
                            @params.ReferencedAssemblies.RemoveAt(i);
                        }
                    }
                }
            }

            var results = CodeDomProvider.CompileAssemblyFromDom(@params, compileUnit);

            //Tricky: Don't forget to cleanup.
            // Simply setting KeepFiles = false and then calling
            // dispose on the parent TempFilesCollection won't
            // clean up. So, create a new collection and
            // explicitly mark the files for deletion.
            var tempFilesMarkedForDeletion = new TempFileCollection(null);

            @params.TempFiles
            .OfType <string>()
            .ForEach(file => tempFilesMarkedForDeletion.AddFile(file, false));

            using ( tempFilesMarkedForDeletion )
            {
                if (results.Errors != null && results.Errors.HasErrors)
                {
                    throw new TemplateCompilationException(results);
                }

                return(results);
            }
        }
Exemplo n.º 17
0
        public IDisposable InstallHook(Uri reposUri, SvnHookType type, EventHandler <ReposHookEventArgs> hook)
        {
            if (reposUri == null)
            {
                throw new ArgumentNullException("reposUri");
            }
            else if (!reposUri.IsFile)
            {
                throw new InvalidOperationException();
            }

            string reposPath = reposUri.LocalPath;

            TempFileCollection tfc = new TempFileCollection();
            string             dir = Path.GetTempPath();

            string suffix = Guid.NewGuid().ToString("N");
            string args   = Path.Combine(dir, suffix + "-args.txt");
            string stdin  = Path.Combine(dir, suffix + "-stdin.txt");
            string done   = Path.Combine(dir, suffix + "-done.txt");
            string wait   = Path.Combine(dir, suffix + "-wait.txt");

            string errTxt = Path.Combine(dir, suffix + "-errTxt.txt");
            string outTxt = Path.Combine(dir, suffix + "-outTxt.txt");

            tfc.AddFile(args, false);
            tfc.AddFile(stdin, false);
            tfc.AddFile(wait, false);
            tfc.AddFile(errTxt, false);
            tfc.AddFile(outTxt, false);

            ThreadStopper stopper = new ThreadStopper();

            string envPrefix = Path.GetFileNameWithoutExtension(SvnHookArguments.GetHookFileName(reposPath, type)) + ".";

            Environment.SetEnvironmentVariable(envPrefix + "SHARPSVNHOOK_FILE", args);
            Environment.SetEnvironmentVariable(envPrefix + "SHARPSVNHOOK_STDIN", stdin);
            Environment.SetEnvironmentVariable(envPrefix + "SHARPSVNHOOK_DONE", done);
            Environment.SetEnvironmentVariable(envPrefix + "SHARPSVNHOOK_WAIT", wait);
            Environment.SetEnvironmentVariable(envPrefix + "SHARPSVNHOOK_OUT_STDOUT", outTxt);
            Environment.SetEnvironmentVariable(envPrefix + "SHARPSVNHOOK_OUT_STDERR", errTxt);

            string file = Path.ChangeExtension(SvnHookArguments.GetHookFileName(reposPath, type), ".exe");

            stopper.Start(
                delegate
            {
                try
                {
                    while (!stopper.Cancel)
                    {
                        if (File.Exists(done))
                        {
                            List <string> argCollection = new List <string>();
                            using (StreamReader fs = File.OpenText(args))
                            {
                                string line;
                                while (null != (line = fs.ReadLine()))
                                {
                                    argCollection.Add(line);
                                }
                            }
                            string stdinText = File.ReadAllText(stdin);

                            File.Delete(args);
                            File.Delete(stdin);

                            ReposHookEventArgs ra = new ReposHookEventArgs(type, argCollection.ToArray(), stdinText);

                            try
                            {
                                hook(this, ra);
                            }
                            catch (Exception e)
                            {
                                if (string.IsNullOrEmpty(ra.ErrorText))
                                {
                                    ra.ErrorText = e.ToString();
                                }
                                ra.ExitCode = 129;
                            }
                            finally
                            {
                                if (ra.ErrorText != null)
                                {
                                    File.WriteAllText(errTxt, ra.ErrorText);
                                }

                                if (ra.OutputText != null)
                                {
                                    File.WriteAllText(outTxt, ra.OutputText);
                                }


                                File.WriteAllText(wait, ra.ExitCode.ToString());
                            }

                            File.Delete(done);

                            if (ra.Cancel)
                            {
                                break;
                            }
                        }
                        Thread.Sleep(50);
                    }
                }
                finally
                {
                    Environment.SetEnvironmentVariable(envPrefix + "SHARPSVNHOOK_FILE", null);
                    Environment.SetEnvironmentVariable(envPrefix + "SHARPSVNHOOK_STDIN", null);
                    Environment.SetEnvironmentVariable(envPrefix + "SHARPSVNHOOK_DONE", null);
                    Environment.SetEnvironmentVariable(envPrefix + "SHARPSVNHOOK_WAIT", null);
                    Environment.SetEnvironmentVariable(envPrefix + "SHARPSVNHOOK_OUT_STDOUT", null);
                    Environment.SetEnvironmentVariable(envPrefix + "SHARPSVNHOOK_OUT_STDERR", null);
                }

                GC.KeepAlive(tfc);
                File.Delete(file);
            });

            File.Copy(Path.Combine(ProjectBase, "..\\tools\\hooknotifier\\bin\\" + Configuration + "\\HookNotifier.exe"), file);

            return(stopper);
        }
        [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] //For Path.GetTempPath method.
                                                                            //We use tha path to create a temp file stream which is consistent with the resource consumption of machine.

        internal void GenerateCode(LazyTextWriterCreator target, string targetLocation)
        {
            Debug.Assert(target != null, "target parameter is null");

            IndentedTextWriter indentedTextWriter = null;

            System.IO.Stream       tempFileStream = null;
            System.IO.StreamReader reader         = null;
            System.IO.StreamWriter writer         = null;
            TempFileCollection     tempFiles      = null;

            try
            {
                CodeDomProvider provider = null;
                switch (Language)
                {
                case LanguageOption.GenerateCSharpCode:
                    provider = new Microsoft.CSharp.CSharpCodeProvider();
                    break;

                case LanguageOption.GenerateVBCode:
                    provider = new Microsoft.VisualBasic.VBCodeProvider();
                    break;
                }

                _isLanguageCaseSensitive = (provider.LanguageOptions & LanguageOptions.CaseInsensitive) == 0;

                new NamespaceEmitter(this, _codeNamespace, target.TargetFilePath).Emit();

                // if there were errors we don't need the output file
                if (RealErrorsExist)
                {
                    return;
                }

                if (FixUps.Count == 0 || !FixUpCollection.IsLanguageSupported(Language))
                {
                    indentedTextWriter = new IndentedTextWriter(target.GetOrCreateTextWriter(), "\t");
                }
                else
                {
                    // need to write to a temporary file so we can do fixups...
                    tempFiles = new TempFileCollection(Path.GetTempPath());
                    string filename = Path.Combine(tempFiles.TempDir, "EdmCodeGenFixup-" + Guid.NewGuid().ToString() + ".tmp");
                    tempFiles.AddFile(filename, false);
                    tempFileStream = new System.IO.FileStream(filename, System.IO.FileMode.CreateNew, System.IO.FileAccess.ReadWrite,
                                                              System.IO.FileShare.None);
                    indentedTextWriter = new IndentedTextWriter(new System.IO.StreamWriter(tempFileStream), "\t");
                }

                CodeGeneratorOptions styleOptions = new CodeGeneratorOptions();
                styleOptions.BracingStyle             = "C";
                styleOptions.BlankLinesBetweenMembers = false;
                styleOptions.VerbatimOrder            = true;
                provider.GenerateCodeFromCompileUnit(CompileUnit, indentedTextWriter, styleOptions);

                // if we wrote to a temp file need to post process the file...
                if (tempFileStream != null)
                {
                    indentedTextWriter.Flush();
                    tempFileStream.Seek(0, System.IO.SeekOrigin.Begin);
                    reader = new System.IO.StreamReader(tempFileStream);
                    FixUps.Do(reader, target.GetOrCreateTextWriter(), Language, SourceObjectNamespaceName != string.Empty);
                }
            }
            catch (System.UnauthorizedAccessException ex)
            {
                AddError(ModelBuilderErrorCode.SecurityError, EdmSchemaErrorSeverity.Error, ex);
            }
            catch (System.IO.FileNotFoundException ex)
            {
                AddError(ModelBuilderErrorCode.FileNotFound, EdmSchemaErrorSeverity.Error, ex);
            }
            catch (System.Security.SecurityException ex)
            {
                AddError(ModelBuilderErrorCode.SecurityError, EdmSchemaErrorSeverity.Error, ex);
            }
            catch (System.IO.DirectoryNotFoundException ex)
            {
                AddError(ModelBuilderErrorCode.DirectoryNotFound, EdmSchemaErrorSeverity.Error, ex);
            }
            catch (System.IO.IOException ex)
            {
                AddError(ModelBuilderErrorCode.IOException, EdmSchemaErrorSeverity.Error, ex);
            }
            finally
            {
                if (indentedTextWriter != null)
                {
                    indentedTextWriter.Close();
                }
                if (tempFileStream != null)
                {
                    tempFileStream.Close();
                }
                if (tempFiles != null)
                {
                    tempFiles.Delete();
                    ((IDisposable)tempFiles).Dispose();
                }
                if (reader != null)
                {
                    reader.Close();
                }
                if (writer != null)
                {
                    writer.Close();
                }
            }
        }
Exemplo n.º 19
0
 /// <summary>
 /// Background thread to download thumbs from last.fm where there is no local thumb
 /// </summary>
 /// <param name="strTrackImgURL">The URL of the image for track</param>
 /// <param name="tmpThumbName">Full path to file to download image to</param>
 /// <param name="item">GUIListItem to which this thumb relates</param>
 private void ImageDownloadDoWork(string strTrackImgURL, string tmpThumbName, GUIListItem item)
 {
     Util.Utils.DownLoadImage(strTrackImgURL, tmpThumbName);
     Tfc.AddFile(tmpThumbName, false);
     GUIGraphicsContext.form.Invoke(new UpdateThumbsDelegate(UpdateListItemImage), item, tmpThumbName);
 }
Exemplo n.º 20
0
 /// <summary>
 /// Adds the specified file to the collection, using the specified value indicating whether to keep the file after the collection is disposed or when the Delete method is called.
 /// </summary>
 /// <param name="fileName">The name of the file to add to the collection. </param>
 /// <param name="keepFile">true if the file should be kept after use; false if the file should be deleted.</param>
 public void AddFile(string fileName, bool keepFile)
 {
     _tempFileCollection.AddFile(fileName, keepFile);
 }
Exemplo n.º 21
0
        private Type CompileClass(ScriptClass script)
        {
            TempFileCollection      allTempFiles = compiler.CompilerResults.TempFiles;
            CompilerErrorCollection allErrors    = compiler.CompilerResults.Errors;
            CodeDomProvider         provider;
            bool isVB = false;

            try {
                provider = script.compilerInfo.CreateProvider();
            }
            catch (ConfigurationException e) {
                // The CodeDom provider type could not be located, or some error in machine.config
                allErrors.Add(script.CreateCompileExceptionError(e));
                return(null);
            }

            CodeNamespace scriptNs = new CodeNamespace("System.Xml.Xsl.CompiledQuery");

            // Add #using directives
            foreach (string ns in defaultNamespaces)
            {
                scriptNs.Imports.Add(new CodeNamespaceImport(ns));
            }
            if (isVB)
            {
                scriptNs.Imports.Add(new CodeNamespaceImport("Microsoft.VisualBasic"));
            }
            foreach (string ns in script.nsImports)
            {
                scriptNs.Imports.Add(new CodeNamespaceImport(ns));
            }

            scriptNs.Types.Add(script.typeDecl);

            CodeCompileUnit unit = new CodeCompileUnit(); {
                unit.Namespaces.Add(scriptNs);
                unit.UserData["AllowLateBound"]             = true;  // Allow variables to be undeclared
                unit.UserData["RequireVariableDeclaration"] = false; // Allow variables to be declared untyped
                unit.AssemblyCustomAttributes.Add(new CodeAttributeDeclaration("System.Security.SecurityTransparentAttribute"));
            }

            CompilerParameters compilParams = new CompilerParameters();

            compilParams.ReferencedAssemblies.Add(typeof(System.Xml.Res).Assembly.Location);
            compilParams.ReferencedAssemblies.Add("System.dll");
            if (isVB)
            {
                compilParams.ReferencedAssemblies.Add("Microsoft.VisualBasic.dll");
            }
            foreach (string name in script.refAssemblies)
            {
                compilParams.ReferencedAssemblies.Add(name);
            }

            XsltSettings settings = compiler.Settings;

            compilParams.WarningLevel            = settings.WarningLevel >= 0 ? settings.WarningLevel : 4;
            compilParams.TreatWarningsAsErrors   = settings.TreatWarningsAsErrors;
            compilParams.IncludeDebugInformation = settings.IncludeDebugInformation;
            compilParams.CompilerOptions         = script.compilerInfo.CreateDefaultCompilerParameters().CompilerOptions;

            bool keepFiles = (settings.IncludeDebugInformation || XmlILTrace.IsEnabled) && !settings.CheckOnly;

            compilParams.GenerateInMemory = settings.CheckOnly;

            // We need only .dll and .pdb, but there is no way to specify that
            compilParams.TempFiles.KeepFiles = keepFiles;

            CompilerResults results;

            try {
                results = provider.CompileAssemblyFromDom(compilParams, unit);
            }
            catch (ExternalException e) {
                // Compiler might have created temporary files
                results = new CompilerResults(compilParams.TempFiles);
                results.Errors.Add(script.CreateCompileExceptionError(e));
            }

            if (!settings.CheckOnly)
            {
                foreach (string fileName in results.TempFiles)
                {
                    allTempFiles.AddFile(fileName, allTempFiles.KeepFiles);
                }
            }
            foreach (CompilerError e in results.Errors)
            {
                script.FixFileName(e);
            }
            allErrors.AddRange(results.Errors);
            if (results.Errors.HasErrors)
            {
                return(null);
            }
            return(results.CompiledAssembly.GetType("System.Xml.Xsl.CompiledQuery." + script.typeDecl.Name));
        }
Exemplo n.º 22
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="container"></param>
        /// <returns></returns>
        public override ScriptError[] Parse(ScriptContainer container)
        {
            List <ScriptError> errors = new List <ScriptError>();

            try
            {
                CompilerParameters compileParams = new CompilerParameters();
                TempFileCollection tempFiles     = new TempFileCollection(Path.GetTempPath(), container.EnableDebug);

                compileParams.GenerateExecutable      = false;
                compileParams.GenerateInMemory        = true;
                compileParams.IncludeDebugInformation = true;
                compileParams.TempFiles = tempFiles;
                compileParams.ReferencedAssemblies.Add("System.dll");
                compileParams.ReferencedAssemblies.Add("Microsoft.CSharp.dll");
                compileParams.ReferencedAssemblies.Add("System.Core.dll");
                compileParams.ReferencedAssemblies.Add("System.Numerics.dll");

                foreach (AssemblyName name in container.ReferencedNames)
                {
                    Assembly asm = Assembly.Load(name);

                    if (!String.IsNullOrWhiteSpace(asm.Location))
                    {
                        compileParams.ReferencedAssemblies.Add(asm.Location);
                    }
                    else
                    {
                        byte[] assemblyData = GetDataForAssembly(name);

                        if (assemblyData != null)
                        {
                            string fileName = Path.GetTempFileName();
                            File.WriteAllBytes(fileName, assemblyData);

                            tempFiles.AddFile(fileName, false);

                            compileParams.ReferencedAssemblies.Add(fileName);
                        }
                        else
                        {
                            errors.Add(new ScriptError(String.Format(Properties.Resources.DotNetScriptEngine_CannotGetAssemblyLocation, name),
                                                       Properties.Resources.Scripting_Warning, 1, 1));
                        }
                    }
                }

                if (!String.IsNullOrEmpty(_options))
                {
                    compileParams.CompilerOptions = _options;
                }

                List <string> scripts = new List <string>();
                scripts.Add(container.Script);

                string src = CreateScriptContainerSource(container);
                if (!String.IsNullOrWhiteSpace(src))
                {
                    scripts.Add(src);
                }

                CompilerResults results = _provider.CompileAssemblyFromSource(compileParams, scripts.ToArray());
                if (results.Errors.HasErrors)
                {
                    foreach (CompilerError e in results.Errors)
                    {
                        errors.Add(new ScriptError(e.ErrorText, Properties.Resources.Scripting_Error, e.Line, e.Column));
                    }
                }
                else
                {
                    _assembly = results.CompiledAssembly;
                }

                if (container.EnableDebug)
                {
                    foreach (string file in tempFiles)
                    {
                        ScriptUtils.AddTempFile(file);
                    }
                }
            }
            catch (Exception ex)
            {
                errors.Add(new ScriptError(String.Format(Properties.Resources.DotNetScriptEngine_CompileException, ex.Message), Properties.Resources.Scripting_FatalError, 0, 0));
            }

            // Test Code
            foreach (ScriptError error in errors)
            {
                System.Diagnostics.Trace.WriteLine(error.Description);
            }

            return(errors.ToArray());
        }
        public Type Compile()
        {
            Type forceLoadOfRuntimeBinder = typeof(Microsoft.CSharp.RuntimeBinder.Binder);

            if (forceLoadOfRuntimeBinder == null)
            {
                log.Warn("Force load of .NET 4.0+ RuntimeBinder in Microsoft.CSharp.dll");
            }

            var razorResults = Generate();

            var @params = new CompilerParameters
            {
                GenerateInMemory        = true,
                GenerateExecutable      = false,
                IncludeDebugInformation = IncludeDebugInformation,
                CompilerOptions         = "/target:library" + (IncludeDebugInformation ? "" : " /optimize"),
                TempFiles = { KeepFiles = true }
            };

            var assemblies = CompilerServices
                             .GetLoadedAssemblies()
                             .Where(a => !a.IsDynamic);

            if (Env.IsMono)
            {
                //workaround mono not handling duplicate dll references (i.e. in GAC)
                var uniqueNames = new HashSet <string>();
                assemblies = assemblies.Where(x =>
                {
                    var id = x.GetName().Name;
                    if (string.IsNullOrEmpty(id))
                    {
                        return(true);
                    }
                    if (uniqueNames.Contains(id))
                    {
                        return(false);
                    }
                    if (!id.Contains("<"))
                    {
                        uniqueNames.Add(x.GetName().Name);
                    }
                    return(true);
                });
            }

            var assemblyNames = assemblies
                                .Select(a => a.Location)
                                .ToArray();

            @params.ReferencedAssemblies.AddRange(assemblyNames);

            if (CompileFilter != null)
            {
                CompileFilter(@params);
            }

            //Compile the code
            var results = _codeDomProvider.CompileAssemblyFromDom(@params, razorResults.GeneratedCode);

            var tempFilesMarkedForDeletion = new TempFileCollection(null);

            foreach (var file in @params.TempFiles.OfType <string>())
            {
                tempFilesMarkedForDeletion.AddFile(file, false);
            }

            using (tempFilesMarkedForDeletion)
            {
                if (results.Errors != null && results.Errors.HasErrors)
                {
                    //check if source file exists, read it.
                    //HttpCompileException is sealed by MS. So, we'll
                    //just add a property instead of inheriting from it.
                    var sourceFile = results.Errors
                                     .OfType <CompilerError>()
                                     .First(ce => !ce.IsWarning)
                                     .FileName;

                    var sourceCode = "";
                    if (!string.IsNullOrEmpty(sourceFile) && System.IO.File.Exists(sourceFile))
                    {
                        sourceCode = System.IO.File.ReadAllText(sourceFile);
                    }
                    else
                    {
                        foreach (string tempFile in @params.TempFiles)
                        {
                            if (tempFile.EndsWith(".cs"))
                            {
                                sourceCode = System.IO.File.ReadAllText(tempFile);
                            }
                        }
                    }
                    throw new HttpCompileException(results, sourceCode);
                }

#if DEBUG
                foreach (string tempFile in @params.TempFiles)
                {
                    if (tempFile.EndsWith(".cs"))
                    {
                        var sourceCode = System.IO.File.ReadAllText(tempFile);
                        //sourceCode.Print();
                    }
                }
#endif

                return(results.CompiledAssembly.GetTypes().First());
            }
        }
Exemplo n.º 24
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Compiler"/> class.
        /// </summary>
        public static CompilerResults ExecuteCompiler(CompilerSettings settings)
        {
            CodeDomProvider provider;

            if (!providerCache.TryGetValue(settings.Language, out provider))
            {
                provider = CodeDomProvider.CreateProvider(settings.Language);
                if (provider == null)
                {
                    throw new NotSupportedException("The language '" + settings.Language + "' is not supported on this machine.");
                }
                providerCache.Add(settings.Language, provider);
            }

            string filename = Path.Combine(TempDirectory, Path.ChangeExtension(Path.GetRandomFileName(), "dll"));

            temps.AddFile(filename, false);

            string[] references = new string[settings.References.Count];
            settings.References.CopyTo(references, 0);

            CompilerParameters parameters = new CompilerParameters(references, filename, false);

            parameters.CompilerOptions = "/optimize-";

            if (settings.UnsafeCode)
            {
                if (settings.Language == "C#")
                {
                    parameters.CompilerOptions = parameters.CompilerOptions + " /unsafe+";
                }
                else
                {
                    throw new NotSupportedException();
                }
            }

            if (settings.DoNotReferenceMscorlib)
            {
                if (settings.Language == "C#")
                {
                    parameters.CompilerOptions = parameters.CompilerOptions + " /nostdlib";
                }
                else
                {
                    throw new NotSupportedException();
                }
            }

            parameters.GenerateInMemory = false;

            if (settings.CodeSource != null)
            {
                CompilerResults compileResults = provider.CompileAssemblyFromSource(parameters, settings.CodeSource + settings.AdditionalSource);

                return(compileResults);
            }
            else
            {
                throw new NotSupportedException();
            }
        }
        private void FinishSetting(object sender, RoutedEventArgs e)
        {
            if (hourTextBox.Text != null && !hourTextBox.Text.Equals(""))
            {
                hours = Convert.ToInt32(hourTextBox.Text);
            }

            if (minTextBox.Text != null && !minTextBox.Text.Equals(""))
            {
                min = Convert.ToInt32(minTextBox.Text);
            }
            //Stopwatch watch = new Stopwatch();
            // watch.Start();
            XElement      root            = XElement.Load(@"Resources\XMLFile1.xml");
            List <string> finalblacksites = new List <string>();

            foreach (string site in domainsToBlock)                                                 // Populate the final blacklist with the domains to be blocked .
            {
                IEnumerable <string> s = from el in root.Elements("site").AsParallel()
                                         where el.Element("name").Value.Equals(site)
                                         select el.Element("domain").Value.ToLower();

                finalblacksites.AddRange(s);
            }


            if ((bool)BlockPopUp.IsChecked)                                                         // This block will execute if user wants to block popup and ads also
            {
                string file = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "BlackList.txt");
                File.Copy(blacklist_path, file);
                tempFiles.AddFile(file, false);

                if (PopUpResult.Equals(MessageBoxResult.Yes))
                {
                    try
                    {
                        WriteToFileSuperFast(domainsFromHostFile, null, file);
                    }
                    catch
                    {
                        Thread.Sleep(2000);
                        WriteToFileSuperFast(domainsFromHostFile, null, file);
                    }
                }

                WriteToFileSuperFast(finalblacksites, address, file);

                System.IO.File.Copy(file, hostfile_location, true);

                popupBlocked = true;

                tempFiles.Delete();
            }
            else                                                                              // This block will execute if the user do not want to block popup and ads
            {
                string file = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "host");
                File.Copy(@"Resources\host", file);
                tempFiles.AddFile(file, false);

                if (PopUpResult.Equals(MessageBoxResult.Yes))
                {
                    try
                    {
                        WriteToFileSuperFast(domainsFromHostFile, null, file);
                    }
                    catch
                    {
                        Thread.Sleep(2000);
                        WriteToFileSuperFast(domainsFromHostFile, null, file);
                    }
                }

                try
                {
                    WriteToFileSuperFast(finalblacksites, address, file);


                    System.IO.File.Copy(file, hostfile_location, true);
                }
                catch
                {
                    Thread.Sleep(2000);
                    System.IO.File.Copy(file, hostfile_location, true);
                }

                popupBlocked = false;
                tempFiles.Delete();
            }


            if ((bool)SetOpenDns.IsChecked)
            {
                BackUp_DNS();
                CreateNew_DNS();
                openDnsUsed = true;
            }


            // watch.Stop();

            CheckForOpenBrowser();
            int time;

            if (hours == 0 && min == 0)
            {
                time = 0;
            }
            else
            {
                if (hours > 23)
                {
                    hours = 23;
                    if (min > 60)
                    {
                        min = 60;
                    }
                }
                time = (hours * 60) + (min);
                if (time > 1440)
                {
                    time = 1440;
                }
            }
            httpserver.Start(80);                                                                   //Starting Http server to send customized messages to the browser.
            FinalPage finalObj = new FinalPage(domainCustomized, openDnsUsed, popupBlocked, time);

            finalObj.ShowsNavigationUI = false;
            NavigationService.Navigate(finalObj);
            //finalObj.ShowsNavigationUI = false;
        }
Exemplo n.º 26
0
        /// <summary>
        /// Create a slide model from a powerpoint slide
        /// </summary>
        /// <param name="pageSetup"></param>
        /// <param name="pptpm"></param>
        /// <param name="deck"></param>
        /// <param name="tempFileCollection"></param>
        /// <param name="dirpath"></param>
        /// <param name="currentSlide"></param>
        /// <returns></returns>
        private static SlideModel CreateSlide(PowerPoint.PageSetup pageSetup, PPTPaneManagement.PPTPaneManager pptpm, DeckModel deck, TempFileCollection tempFileCollection, string dirpath, PowerPoint._Slide currentSlide)
        {
            int   slideWidth  = (int)pageSetup.SlideWidth;  //Standard = 720  => 6000
            int   slideHeight = (int)pageSetup.SlideHeight; //Standard = 540  => 4500
            float emfWidth    = slideWidth * 25 / 3;
            float emfHeight   = slideHeight * 25 / 3;

            PowerPoint.Shapes currentShapes = currentSlide.Shapes;

            List <TaggedShape> taggedShapeList = PPTDeckIO.BuildTaggedShapeList(currentShapes, pptpm);

            //Create a new SlideModel
            SlideModel newSlideModel = new SlideModel(Guid.NewGuid(), new LocalId(), SlideDisposition.Empty, new Rectangle(0, 0, slideWidth, slideHeight));

            //Lock it
            using (Synchronizer.Lock(newSlideModel.SyncRoot)) {
                //Set the slide's title
                newSlideModel.Title = PPTDeckIO.FindSlideTitle(taggedShapeList);

                PPTDeckIO.MakeShapesInvisible(currentShapes);

                //Create the Background image
                //Generate a new filename
                string filename   = PPTDeckIO.GenerateFilename();
                bool   bitmapMode = true;
                if (bitmapMode)
                {
                    filename = dirpath + "\\" + filename + ".JPG";
                    currentSlide.Export(filename, "JPG", 0, 0);

                    // Need to also export as EMF to get the size of the slide in inches
                    currentSlide.Export(filename + "_TEMP", "EMF", 0, 0);
                    tempFileCollection.AddFile(filename + "_TEMP", false);
                }
                else
                {
                    filename = dirpath + "\\" + filename + ".emf";
                    currentSlide.Export(filename, "EMF", 0, 0);
                }
                tempFileCollection.AddFile(filename, false);

                //Compute the MD5 of the BG
                FileStream fs          = new FileStream(filename, FileMode.Open, FileAccess.Read);
                MD5        md5Provider = new MD5CryptoServiceProvider();
                byte[]     md5         = md5Provider.ComputeHash(fs);
                fs.Seek(0, SeekOrigin.Begin);
                Image image = Image.FromStream(fs);
                if (bitmapMode)
                {
                    image = DisassociateBitmap(image);
                }
                fs.Close();

                // Open the EMF version if we used a bitmap to get the conversion
                if (bitmapMode)
                {
                    FileStream fsEMF     = new FileStream(filename + "_TEMP", FileMode.Open, FileAccess.Read);
                    Image      image_emf = Image.FromStream(fsEMF);
                    emfWidth  = image_emf.Width;
                    emfHeight = image_emf.Height;
                    fsEMF.Close();
                    image_emf.Dispose();
                }
                else
                {
                    emfWidth  = image.Width;
                    emfHeight = image.Height;
                }

                //Create the ImageSheet
                ImageSheetModel sheet = new ImageSheetModel(deck, Guid.NewGuid(), Model.Presentation.SheetDisposition.Background,
                                                            new Rectangle(0, 0, slideWidth, slideHeight), (ByteArray)md5, 1);
                //Add the ImageSheet to the Slide
                newSlideModel.ContentSheets.Add(sheet);
                //Add the Image+MD5 to the deck
                deck.AddSlideContent((ByteArray)md5, image);

                // Restore visibility - this makes everything visible - a bug?
                PPTDeckIO.MakeShapesVisible(currentShapes);

                List <List <TaggedShape> > layerList = PPTDeckIO.SeparateIntoLayers(taggedShapeList);

                int startHeight = 2;
                foreach (List <TaggedShape> layer in layerList)
                {
                    PPTDeckIO.ProcessLayer(layer, tempFileCollection, currentShapes, deck, newSlideModel,
                                           slideWidth / emfWidth, slideHeight / emfHeight, startHeight++);
                }

                //Add SlideModel to the deck
                deck.InsertSlide(newSlideModel);
            }
            return(newSlideModel);
        }
Exemplo n.º 27
0
        public Type Compile()
        {
            Type forceLoadOfRuntimeBinder = typeof(Microsoft.CSharp.RuntimeBinder.Binder);

            if (forceLoadOfRuntimeBinder == null)
            {
                log.Warn("Force load of .NET 4.0+ RuntimeBinder in Microsoft.CSharp.dll");
            }

            var razorResults = Generate();

            var @params = new CompilerParameters
            {
                GenerateInMemory        = true,
                GenerateExecutable      = false,
                IncludeDebugInformation = false,
                CompilerOptions         = "/target:library /optimize",
                TempFiles = { KeepFiles = true }
            };

            var assemblies = CompilerServices
                             .GetLoadedAssemblies()
                             .Where(a => !a.IsDynamic)
                             .Select(a => a.Location)
                             .ToArray();

            @params.ReferencedAssemblies.AddRange(assemblies);

            //Compile the code
            var results = _codeDomProvider.CompileAssemblyFromDom(@params, razorResults.GeneratedCode);

            OnCodeCompletion();

            var tempFilesMarkedForDeletion = new TempFileCollection(null);

            @params.TempFiles
            .OfType <string>()
            .ForEach(file => tempFilesMarkedForDeletion.AddFile(file, false));

            using (tempFilesMarkedForDeletion)
            {
                if (results.Errors != null && results.Errors.HasErrors)
                {
                    //check if source file exists, read it.
                    //HttpCompileException is sealed by MS. So, we'll
                    //just add a property instead of inheriting from it.
                    var sourceFile = results.Errors
                                     .OfType <CompilerError>()
                                     .First(ce => !ce.IsWarning)
                                     .FileName;

                    var sourceCode = "";
                    if (!string.IsNullOrEmpty(sourceFile) && System.IO.File.Exists(sourceFile))
                    {
                        sourceCode = System.IO.File.ReadAllText(sourceFile);
                    }
                    else
                    {
                        foreach (string tempFile in @params.TempFiles)
                        {
                            if (tempFile.EndsWith(".cs"))
                            {
                                sourceCode = System.IO.File.ReadAllText(tempFile);
                            }
                        }
                    }
                    throw new HttpCompileException(results, sourceCode);
                }

#if DEBUG
                foreach (string tempFile in @params.TempFiles)
                {
                    if (tempFile.EndsWith(".cs"))
                    {
                        var sourceCode = System.IO.File.ReadAllText(tempFile);
                        //sourceCode.Print();
                    }
                }
#endif

                return(results.CompiledAssembly.GetTypes().First());
            }
        }
Exemplo n.º 28
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="tfc"></param>
        /// <param name="shapes"></param>
        /// <param name="range"></param>
        /// <param name="deck"></param>
        /// <param name="slide"></param>
        /// <param name="disposition"></param>
        /// <param name="emfHeight"></param>
        /// <param name="startHeight">The starting height to place this sheet at</param>
        private static void ProcessLayer(List <TaggedShape> layer, TempFileCollection tfc, PowerPoint.Shapes shapes, Model.Presentation.DeckModel deck, Model.Presentation.SlideModel slide, float emfWidthRatio, float emfHeightRatio, int startHeight)
        {
            if (layer.Count < 1)
            {
                return;
            }

            //Create the image
            int[] range = PPTDeckIO.BuildIntRange(layer);
            PowerPoint.ShapeRange sr = shapes.Range(range);

            PowerPoint.PpShapeFormat format;
            string fileExt    = "";
            bool   bitmapMode = layer[0].isImage;

            if (bitmapMode)
            {
                format  = PowerPoint.PpShapeFormat.ppShapeFormatJPG;
                fileExt = "jpg";
            }
            else
            {
                format  = PowerPoint.PpShapeFormat.ppShapeFormatEMF;
                fileExt = "emf";
            }

            //Generate a new filename
            string dirpath  = tfc.BasePath;
            string filename = PPTDeckIO.GenerateFilename();

            filename = dirpath + "\\" + filename + "." + fileExt;
            while (File.Exists(filename))
            {
                filename = PPTDeckIO.GenerateFilename();
                filename = dirpath + "\\" + filename + "." + fileExt;
            }
            sr.Export(filename, format, 0, 0,
                      PowerPoint.PpExportMode.ppRelativeToSlide);
            tfc.AddFile(filename, false);
            //Compute the MD5 of the BG
            FileStream fs          = new FileStream(filename, FileMode.Open, FileAccess.Read);
            MD5        md5Provider = new MD5CryptoServiceProvider();

            byte[] md5 = md5Provider.ComputeHash(fs);
            fs.Seek(0, SeekOrigin.Begin);
            Image image = Image.FromStream(fs);

            if (bitmapMode)
            {
                image = DisassociateBitmap(image);
            }

            fs.Close();
            //Calculate the geometry
            int xCoord = 0;
            int yCoord = 0;
            int width  = 0;
            int height = 0;

            PPTDeckIO.CalculateGeometry(image, shapes, range, emfWidthRatio, emfHeightRatio, ref xCoord, ref yCoord, ref width, ref height);
            //Create the ImageSheet
            ImageSheetModel sheet = new ImageSheetModel(deck, Guid.NewGuid(), layer[0].disp,
                                                        new Rectangle(xCoord, yCoord, width, height), (ByteArray)md5, startHeight);

            //Add the ImageSheet to the Slide
            slide.ContentSheets.Add(sheet);
            //Add the Image+MD5 to the deck
            deck.AddSlideContent((ByteArray)md5, image);
        }