AddFile() public method

public AddFile ( string fileName, bool keepFile ) : void
fileName string
keepFile bool
return void
Example #1
0
		string CompileAndGetOutput(string fileContent)
		{
			TempFileCollection  tf = new TempFileCollection ();
			
			string path = Path.Combine(tf.BasePath, tf.TempDir);
			Directory.CreateDirectory(path);
			string generatedScript = Path.Combine(path, "InternalGeneratedScript.cs");
			string generatedDLL    = Path.Combine(path, "A.DLL");
			tf.AddFile(generatedScript, false);
			tf.AddFile(generatedDLL, false);
			
			StreamWriter sw = new StreamWriter(generatedScript);
			sw.Write(fileContent);
			sw.Close();
			
			string output = String.Empty;
			string error  = String.Empty;
			
			Executor.ExecWaitWithCapture(GetCompilerName() + " /target:library \"/out:" + generatedDLL + "\" \"" + generatedScript +"\"", tf, ref output, ref error);
			
			if (!File.Exists(generatedDLL)) {
				
				StreamReader sr = File.OpenText(output);
				string errorMessage = sr.ReadToEnd();
				sr.Close();
				MessageService.ShowMessage(errorMessage);
				return ">>>>ERROR IN CODE GENERATION GENERATED SCRIPT WAS:\n" + fileContent + "\n>>>>END";
			}
			
			Assembly asm = Assembly.Load(GetBytes(generatedDLL));
			
			object templateInstance = asm.CreateInstance("Template");
			
			
			foreach (TemplateProperty property in item.Properties) {
				FieldInfo fieldInfo = templateInstance.GetType().GetField(property.Name);
				fieldInfo.SetValue(templateInstance, Convert.ChangeType(StringParser.Properties["Properties." + property.Name], property.Type.StartsWith("Types:") ? typeof(string): Type.GetType(property.Type)));
			}
			MethodInfo methodInfo = templateInstance.GetType().GetMethod("GenerateOutput");
			string ret = methodInfo.Invoke(templateInstance, null).ToString();
			tf.Delete();
			return ret;
		}
Example #2
0
		public void Constructor1_Deny_Unrestricted ()
		{
			TempFileCollection tfc = new TempFileCollection (temp);
			Assert.AreEqual (0, tfc.Count, "Count");
			Assert.IsFalse (tfc.KeepFiles, "KeepFiles");
			Assert.AreEqual (temp, tfc.TempDir, "TempDir");
			tfc.AddFile ("main.cs", false);
			tfc.CopyTo (array, 0);
			tfc.Delete ();
			(tfc as IDisposable).Dispose ();
		}
Example #3
0
		static Assembly CompileAssembly(string fileContent)
		{
			if (cachedAssemblies.ContainsKey(fileContent))
				return cachedAssemblies[fileContent];
			
			using (TempFileCollection tf = new TempFileCollection()) {
				string path = Path.Combine(tf.BasePath, tf.TempDir);
				Directory.CreateDirectory(path);
				string generatedScript = Path.Combine(path, "InternalGeneratedScript.cs");
				string generatedDLL    = Path.Combine(path, "A.DLL");
				tf.AddFile(generatedScript, false);
				tf.AddFile(generatedDLL, false);
				
				StreamWriter sw = new StreamWriter(generatedScript);
				sw.Write(fileContent);
				sw.Close();
				
				string output = String.Empty;
				string error  = String.Empty;
				
				Executor.ExecWaitWithCapture(GetCompilerName() + " /target:library \"/out:" + generatedDLL + "\" \"" + generatedScript +"\"", tf, ref output, ref error);
				
				if (!File.Exists(generatedDLL)) {
					
					StreamReader sr = File.OpenText(output);
					string errorMessage = sr.ReadToEnd();
					sr.Close();
					MessageService.ShowMessage(errorMessage);
					return null;
				}
				
				Assembly asm = Assembly.Load(File.ReadAllBytes(generatedDLL));
				cachedAssemblies[fileContent] = asm;
				return asm;
			}
		}
        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 });
            }
        }
Example #5
0
        /// <summary>
        /// Take attachments from the current mail message and put them in a work item
        /// </summary>
        /// <param name="message"></param>
        private static TempFileCollection SaveAttachments(IIncomingEmailMessage message)
        {
            var attachmentFiles = new TempFileCollection();

            foreach (var attachment in message.Attachments)
            {
                var filename = attachment.SaveAttachmentToFile();
                if (filename != null)
                {
                    attachmentFiles.AddFile(filename, false);
                    Logger.InfoFormat("Attachment saved to file {0}", filename);
                }
            }

            return attachmentFiles;
        }
        public FileHashDB(short _BlockSize, bool KEYS)
        {
            if(KEYS) Map = new Hashtable();
            ObjectReadCB = new OnReadHandler(ReadObjectSink);
            string FullFilePath = Guid.NewGuid().ToString();
            tfc = new TempFileCollection();
            tfc.AddFile(FullFilePath,false);

            MaxBlockSize = _BlockSize;
            fstream = new FileStream(FullFilePath,FileMode.Create,FileAccess.ReadWrite,FileShare.Read);
            DBFileInfo = new FileInfo(FullFilePath);
            DeleteBuffer = new byte[MaxBlockSize];
            DeleteCB = new AsyncCallback(DeleteSink);
            ClearCB = new AsyncCallback(ClearSink);
            MemoryStream ms = new MemoryStream();
            byte[] x = BitConverter.GetBytes((short)0);
            ms.Write(x,0,x.Length);
            ms.Write(x,0,x.Length);
            ClearBlock = ms.ToArray();
            ms.Close();

            IndexFilePath = DBFileInfo.FullName.Substring(0,DBFileInfo.FullName.Length-DBFileInfo.Extension.Length) + ".idx";
            tfc.AddFile(IndexFilePath,false);

            // Initialize File Header
            byte[] BlockSize = BitConverter.GetBytes((short)MaxBlockSize);
            byte[] bUpdateID = BitConverter.GetBytes(UpdateID);
            byte[] eVersion = BitConverter.GetBytes(EngineVersion);
            SeekLock.WaitOne();
            fstream.Seek(0,SeekOrigin.Begin);
            InitializeCounter = 3;
            fstream.BeginWrite(BlockSize,0,2,new AsyncCallback(InitHeaderSink),null);
            fstream.BeginWrite(bUpdateID,0,4,new AsyncCallback(InitHeaderSink),null);
            fstream.BeginWrite(eVersion,0,4,new AsyncCallback(InitHeaderSink),null);
            SeekLock.ReleaseMutex();
            if(Interlocked.Decrement(ref InitializeCounter)==0)
            {
                if(OnReady!=null) OnReady(this,null);
            }
        }
Example #7
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();
        }
        [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();
                }
            }
        }
Example #9
0
        public void AddFile_DuplicateFileName_ThrowsArgumentException()
        {
            using (var collection = new TempFileCollection())
            {
                const string FileName = "FileName";
                collection.AddFile(FileName, keepFile: false);
                Assert.Throws<ArgumentException>("fileName", () => collection.AddFile(FileName, keepFile: false));

                // Case insensitive
                Assert.Throws<ArgumentException>("fileName", () => collection.AddFile(FileName.ToLowerInvariant(), keepFile: false));
            }
        }
Example #10
0
        public void AddFile_MultipleFiles_DeletesAllIfKeepFilesFalse(bool keepFiles)
        {
            string directory = TempDirectory();
            string filePath1 = Path.Combine(directory, "file1.extension");
            string filePath2 = Path.Combine(directory, "file2.extension");

            File.Create(filePath1).Dispose();
            File.Create(filePath2).Dispose();

            try
            {
                using (var collection = new TempFileCollection(directory))
                {
                    collection.AddFile(filePath1, keepFiles);
                    collection.AddFile(filePath2, keepFiles);
                }

                Assert.Equal(keepFiles, File.Exists(filePath1));
                Assert.Equal(keepFiles, File.Exists(filePath2));
            }
            finally
            {
                if (File.Exists(filePath1))
                {
                    File.Delete(filePath1);
                }
                if (File.Exists(filePath2))
                {
                    File.Delete(filePath2);
                }
            }
        }
Example #11
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;

            // Adding an empty textbox in the upper left corner of the the
            // slide before layers are exported works around a common
            // issue with shape positioning.  Without this, text shapes often get pushed too far
            // to the right and down due to some extra padding that PPT inserts on
            // the top and left of the exported images.  It doesn't pad the top left of an
            // empty text box, so the positioning is corrected.
            // This isn't perfect since the workaround should probably be applied to
            // every layer with text boxes.
            currentSlide.Shapes.AddTextbox(Core.MsoTextOrientation.msoTextOrientationHorizontal, 0, 0, 1, 1);

            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, currentSlide);

                PPTDeckIO.MakeShapesInvisible(currentShapes);

                //Create the Background image
                //Generate a new filename
                string filename = PPTDeckIO.GenerateFilename();
                bool bitmapMode = true;
                if (bitmapMode) {
                    filename = dirpath + "\\" + filename + ".png";
                    currentSlide.Export(filename, "PNG", 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;
        }
Example #12
0
        public void VerifyImportedProjectRootElementsInheritExplicitLoadFlag()
        {
            string contents1 = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'>
 <Import Project='{0}' />
 <Target Name='test' />
</Project>
");

            string contents2 = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'>
    <PropertyGroup>
        <ImportedProperty>ImportedValue</ImportedProperty>
    </PropertyGroup>
</Project>
");

            using (TempFileCollection tfc = new TempFileCollection())
            {
                string importedProjectPath = FileUtilities.GetTemporaryFile();
                string rootProjectPath = FileUtilities.GetTemporaryFile();
                tfc.AddFile(importedProjectPath, false);
                tfc.AddFile(rootProjectPath, false);
                File.WriteAllText(importedProjectPath, contents2);
                File.WriteAllText(rootProjectPath, String.Format(CultureInfo.InvariantCulture, contents1, importedProjectPath));

                var projectCollection = new ProjectCollection();

                // Run a simple build just to prove that nothing is left in the cache.
                BuildRequestData data = new BuildRequestData(rootProjectPath, ReadOnlyEmptyDictionary<string, string>.Instance, null, new[] { "test" }, null);
                _parameters.ResetCaches = true;
                _parameters.ProjectRootElementCache = projectCollection.ProjectRootElementCache;
                _buildManager.BeginBuild(_parameters);
                BuildResult result = _buildManager.BuildRequest(data);
                _buildManager.EndBuild();
                _buildManager.ResetCaches();

                // The semantic of TryOpen is to only retrieve the PRE if it is already in the weak cache.
                Assert.IsNull(Microsoft.Build.Construction.ProjectRootElement.TryOpen(rootProjectPath, projectCollection), "The built project shouldn't be in the cache anymore.");
                Assert.IsNull(Microsoft.Build.Construction.ProjectRootElement.TryOpen(importedProjectPath, projectCollection), "The built project's import shouldn't be in the cache anymore.");

                Project project = projectCollection.LoadProject(rootProjectPath);
                Microsoft.Build.Construction.ProjectRootElement preRoot, preImported;
                Assert.IsNotNull(preRoot = Microsoft.Build.Construction.ProjectRootElement.TryOpen(rootProjectPath, projectCollection), "The root project file should be in the weak cache.");
                Assert.IsNotNull(preImported = Microsoft.Build.Construction.ProjectRootElement.TryOpen(importedProjectPath, projectCollection), "The imported project file should be in the weak cache.");
                Assert.IsTrue(preRoot.IsExplicitlyLoaded);
                Assert.IsTrue(preImported.IsExplicitlyLoaded);

                // Run a simple build just to prove that it doesn't impact what is in the cache.
                data = new BuildRequestData(rootProjectPath, ReadOnlyEmptyDictionary<string, string>.Instance, null, new[] { "test" }, null);
                _parameters.ResetCaches = true;
                _parameters.ProjectRootElementCache = projectCollection.ProjectRootElementCache;
                _buildManager.BeginBuild(_parameters);
                result = _buildManager.BuildRequest(data);
                _buildManager.EndBuild();
                _buildManager.ResetCaches();

                // Now make sure they are still in the weak cache.  Since they were loaded explictly before the build, the build shouldn't have unloaded them from the cache.
                Assert.AreSame(preRoot, Microsoft.Build.Construction.ProjectRootElement.TryOpen(rootProjectPath, projectCollection), "The root project file should be in the weak cache after a build.");
                Assert.AreSame(preImported, Microsoft.Build.Construction.ProjectRootElement.TryOpen(importedProjectPath, projectCollection), "The imported project file should be in the weak cache after a build.");
                Assert.IsTrue(preRoot.IsExplicitlyLoaded);
                Assert.IsTrue(preImported.IsExplicitlyLoaded);

                projectCollection.UnloadProject(project);
                projectCollection.UnloadAllProjects();
                Assert.IsNull(Microsoft.Build.Construction.ProjectRootElement.TryOpen(rootProjectPath, projectCollection), "The unloaded project shouldn't be in the cache anymore.");
                Assert.IsNull(Microsoft.Build.Construction.ProjectRootElement.TryOpen(importedProjectPath, projectCollection), "The unloaded project's import shouldn't be in the cache anymore.");
            }
        }
Example #13
0
        public Type Compile()
        {
            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 ( System.IO.File.Exists( sourceFile ) )
                    {
                        sourceCode = System.IO.File.ReadAllText( sourceFile );
                    }
                    throw new HttpCompileException( results, sourceCode );
                }

                return results.CompiledAssembly.GetTypes().First();
            }
        }
Example #14
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;
        }
Example #15
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;
        }
Example #16
0
        public void AddFile(bool fileExists, bool keepFile)
        {
            string directory = TempDirectory();
            const string FileName = "file.extension";
            string filePath = Path.Combine(directory, FileName);
            if (fileExists)
            {
                File.Create(filePath).Dispose();
            }
            try
            {
                using (var collection = new TempFileCollection(directory))
                {
                    // AddFile(fileName) is a misnomer, and should really be AddFile(filePath),
                    // as only files added with their full path are deleted.
                    collection.AddFile(filePath, keepFile);
                    Assert.Equal(fileExists, File.Exists(filePath));
                }

                Assert.Equal(fileExists && keepFile, File.Exists(filePath));
            }
            finally
            {
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
            }
        }
Example #17
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.ppShapeFormatPNG;
                fileExt = "png";
            }
            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);

            if (bitmapMode) {
                // Starting with Office 2013, bitmaps may not be exported in the correct size.
                double version;
                if (!double.TryParse(((PowerPoint.Application)shapes.Application).Version, out version)) {
                    version = 0.0;
                }
                if (version >= 15.0) {
                    ScaleShapeImage(sr, filename);
                }
            }

            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);
        }
Example #18
0
 public void AddFile_InvalidFileName_ThrowsArgumentException(string fileName)
 {
     using (var collection = new TempFileCollection())
     {
         Assert.Throws<ArgumentException>("fileName", () => collection.AddFile(fileName, keepFile: false));
     }
 }
        [ResourceConsumption(ResourceScope.Machine)] //Temp file creation, and passing to InternalGenerateCode
        public IList<EdmSchemaError> GenerateCode(XmlReader sourceEdmSchema, TextWriter target, IEnumerable<XmlReader> additionalEdmSchemas, Version targetEntityFrameworkVersion)
        {
            EDesignUtil.CheckArgumentNull(sourceEdmSchema, "sourceEdmSchema");
            EDesignUtil.CheckArgumentNull(additionalEdmSchemas, "additionalEdmSchemas");
            EDesignUtil.CheckArgumentNull(target, "target");
            EDesignUtil.CheckTargetEntityFrameworkVersionArgument(targetEntityFrameworkVersion, "targetEntityFrameworkVersion");

            Version schemaVersion;
            if (!IsValidSchema(sourceEdmSchema, out schemaVersion))
            {
                return new List<EdmSchemaError>() { CreateSourceEdmSchemaNotValidError() };
            }

            using (TempFileCollection collection = new TempFileCollection())
            {

                string tempSourceEdmSchemaPath = collection.AddExtension(XmlConstants.CSpaceSchemaExtension);
                SaveXmlReaderToFile(sourceEdmSchema, tempSourceEdmSchemaPath);
                List<string> additionalTempPaths = new List<string>();
                foreach (XmlReader reader in additionalEdmSchemas)
                {

                    string temp = Path.GetTempFileName() + XmlConstants.CSpaceSchemaExtension;
                    SaveXmlReaderToFile(reader, temp);
                    additionalTempPaths.Add(temp);
                    collection.AddFile(temp, false);
                }
                return InternalGenerateCode(tempSourceEdmSchemaPath, schemaVersion, new LazyTextWriterCreator(target), additionalTempPaths, targetEntityFrameworkVersion);
            }
        }
Example #20
0
        public void CopyTo()
        {
            using (var collection = new TempFileCollection())
            {
                const int ArrayIndex = 1;
                const string FileName = "File";
                collection.AddFile(FileName, keepFile: false);

                var array = new string[ArrayIndex + collection.Count];
                collection.CopyTo(array, ArrayIndex);

                Assert.Null(array[0]);
                Assert.Equal(FileName, array[ArrayIndex]);
            }
        }
Example #21
0
 private string SaveTempFile(TempFileCollection tempFiles, XDocument workingDoc, string suffix = null)
 {
     var tempFileName = Path.Combine(tempFiles.TempDir,
                                     Path.GetDirectoryName(this._basePath)
                                     + TemplateDefinitionFileName
                                     + (suffix != null ? "." + suffix : ""));
     workingDoc.Save(tempFileName, SaveOptions.OmitDuplicateNamespaces);
     tempFiles.AddFile(tempFileName, tempFiles.KeepFiles);
     return tempFileName;
 }
Example #22
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 = 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); 
            @params.TempFiles
                   .OfType<string>()
                   .Each(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();
            }
        }
        private static AnalyzerOutput AnalyzeInternal(
            TransactionInfo transaction,
            DescriptiveItem<AnalysisType> analysisType,
            ScoreUtilityType? scoreUtilityType,
            PageSpeedStrategy? pageSpeedStrategy)
        {
            using (var tempFileCollection = new TempFileCollection(Path.GetTempPath(), false))
            {
                var fileName = Path.ChangeExtension(Path.GetRandomFileName(), ".har");

                var inputFilePath = Path.Combine(Path.GetTempPath(), fileName);
                tempFileCollection.AddFile(inputFilePath, false);

                var outputFilePath = inputFilePath + ".json";
                tempFileCollection.AddFile(outputFilePath, false);

                using (var stream = File.Create(inputFilePath))
                {
                    transaction.HarRoot.Serialize(stream);
                }

                var analysisResult = AnalyzeHar(
                    analysisType,
                    scoreUtilityType,
                    pageSpeedStrategy,
                    inputFilePath,
                    outputFilePath);

                return new AnalyzerOutput(transaction, analysisType, analysisResult);
            }
        }