本文整理汇总了C#中System.CodeDom.Compiler.TempFileCollection.AddFile方法的典型用法代码示例。如果您正苦于以下问题:C# TempFileCollection.AddFile方法的具体用法?C# TempFileCollection.AddFile怎么用?C# TempFileCollection.AddFile使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.CodeDom.Compiler.TempFileCollection
的用法示例。
在下文中一共展示了TempFileCollection.AddFile方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CompileAndGetOutput
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;
}
示例2: Constructor1_Deny_Unrestricted
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 ();
}
示例3: CompileAssembly
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;
}
}
示例4: AttachMessageToWorkItem
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 });
}
}
示例5: SaveAttachments
/// <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;
}
示例6: FileHashDB
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);
}
}
示例7: Parse
/// <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();
}
示例8: GenerateCode
[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();
//.........这里部分代码省略.........
示例9: AddFile_DuplicateFileName_ThrowsArgumentException
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));
}
}
示例10: AddFile_MultipleFiles_DeletesAllIfKeepFilesFalse
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);
}
}
}
示例11: CreateSlide
/// <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++ );
//.........这里部分代码省略.........
示例12: VerifyImportedProjectRootElementsInheritExplicitLoadFlag
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.");
}
}
示例13: Compile
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();
}
}
示例14: CreateSlide
/// <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;
}
示例15: InstallHook
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);
//.........这里部分代码省略.........