protected override void RunOverride(MainForm form, object tag) { TempFileCollection files = null; IWICImagingFactory factory = (IWICImagingFactory) new WICImagingFactory(); IWICBitmapEncoderInfo info = null; IWICBitmapEncoder encoder = null; IWICStream stream = null; int i = 0; try { files = new TempFileCollection(); info = (IWICBitmapEncoderInfo)factory.CreateComponentInfo(Parent.Clsid); do { stream.ReleaseComObject(); encoder.ReleaseComObject(); stream = factory.CreateStream(); stream.InitializeFromFilename(files.AddExtension(i.ToString(CultureInfo.InvariantCulture)), NativeMethods.GenericAccessRights.GENERIC_WRITE); i++; try { encoder = info.CreateInstance(); encoder.Initialize(stream, WICBitmapEncoderCacheOption.WICBitmapEncoderNoCache); } catch (Exception e) { form.Add(this, e.TargetSite.ToString(Resources._0_Failed), new DataEntry(e)); break; } }while(ProcessEncoder(form, encoder, tag)); } finally { factory.ReleaseComObject(); info.ReleaseComObject(); encoder.ReleaseComObject(); stream.ReleaseComObject(); files?.Delete(); ((IDisposable)files)?.Dispose(); } }
private void LoadFile(string file) { L_Path.Text = Path.GetDirectoryName(FileName); L_FileName.Text = Path.GetFileName(FileName); //Delete old temp files to prevent eating up space on the system. TempFiles.Delete(); //Places the filename into a new string that doesn't change so that it can be referenced later, even if the filename itself changes. OriginalFileName = FileName; //Reset zip boolean when loading a new file. zip = false; if (FileName.EndsWith(".gz")) { //Create a temporary file and place the name into a variable. var fn = Path.GetTempFileName(); //Opens the selected file and puts it into a variable. var backup = new FileStream(FileName, FileMode.Open, FileAccess.Read); //Puts the temp file into a variable var temp = new FileStream(fn, FileMode.Create); //Decompresses the selected file into a variable var gzip = new GZipStream(backup, CompressionMode.Decompress); //Copies the decompressed file into the temporary file. gzip.CopyTo(temp); gzip.Close(); temp.Close(); backup.Close(); //Adds the temporary file to the list of temporary files. TempFiles.AddFile(fn, false); //Places the filename into a new string that doesn't change so that it can be referenced later, even if the filename itself changes. OriginalFileName = FileName; //Set the filename to the temporary files' name. FileName = fn; zip = true; } ParseFile(); }
/* * Compiles an assembly from source files */ private static Assembly CompileAssembly(string OutputAssemblyPath, List <string> SourceFileNames, List <string> ReferencedAssembies, List <string> PreprocessorDefines = null, bool TreatWarningsAsErrors = false) { var TemporaryFiles = new TempFileCollection(); // Setup compile parameters var CompileParams = new CompilerParameters(); { // Always compile the assembly to a file on disk, so that we can load a cached version later if we have one CompileParams.GenerateInMemory = false; // This is the full path to the assembly file we're generating CompileParams.OutputAssembly = OutputAssemblyPath; // We always want to generate a class library, not an executable CompileParams.GenerateExecutable = false; // Always fail compiles for warnings CompileParams.TreatWarningsAsErrors = true; // Always generate debug information as it takes minimal time CompileParams.IncludeDebugInformation = true; #if !DEBUG // Optimise the managed code in Development CompileParams.CompilerOptions += " /optimize"; #endif Log.TraceVerbose("Compiling " + OutputAssemblyPath); // Keep track of temporary files emitted by the compiler so we can clean them up later CompileParams.TempFiles = TemporaryFiles; // Warnings as errors if desired CompileParams.TreatWarningsAsErrors = TreatWarningsAsErrors; // Add assembly references { if (ReferencedAssembies == null) { // Always depend on the CLR System assembly CompileParams.ReferencedAssemblies.Add("System.dll"); } else { // Add in the set of passed in referenced assemblies CompileParams.ReferencedAssemblies.AddRange(ReferencedAssembies.ToArray()); } // The assembly will depend on this application var UnrealBuildToolAssembly = Assembly.GetExecutingAssembly(); CompileParams.ReferencedAssemblies.Add(UnrealBuildToolAssembly.Location); } // Add preprocessor definitions if (PreprocessorDefines != null && PreprocessorDefines.Count > 0) { CompileParams.CompilerOptions += " /define:"; for (int DefinitionIndex = 0; DefinitionIndex < PreprocessorDefines.Count; ++DefinitionIndex) { if (DefinitionIndex > 0) { CompileParams.CompilerOptions += ";"; } CompileParams.CompilerOptions += PreprocessorDefines[DefinitionIndex]; } } // @todo: Consider embedding resources in generated assembly file (version/copyright/signing) } // Create the output directory if it doesn't exist already DirectoryInfo DirInfo = new DirectoryInfo(Path.GetDirectoryName(OutputAssemblyPath)); if (!DirInfo.Exists) { try { DirInfo.Create(); } catch (Exception Ex) { throw new BuildException(Ex, "Unable to create directory '{0}' for intermediate assemblies (Exception: {1})", OutputAssemblyPath, Ex.Message); } } // Compile the code CompilerResults CompileResults; try { // Enable .NET 4.0 as we want modern language features like 'var' var ProviderOptions = new Dictionary <string, string>() { { "CompilerVersion", "v4.0" } }; var Compiler = new CSharpCodeProvider(ProviderOptions); CompileResults = Compiler.CompileAssemblyFromFile(CompileParams, SourceFileNames.ToArray()); } catch (Exception Ex) { throw new BuildException(Ex, "Failed to launch compiler to compile assembly from source files '{0}' (Exception: {1})", SourceFileNames.ToString(), Ex.Message); } // Display compilation errors if (CompileResults.Errors.Count > 0) { Log.TraceInformation("Errors detected while compiling {0}:", OutputAssemblyPath); foreach (var CurError in CompileResults.Errors) { Log.TraceInformation(CurError.ToString()); } throw new BuildException("UnrealBuildTool encountered an error while compiling source files"); } // Grab the generated assembly Assembly CompiledAssembly = CompileResults.CompiledAssembly; if (CompiledAssembly == null) { throw new BuildException("UnrealBuildTool was unable to compile an assembly for '{0}'", SourceFileNames.ToString()); } // Clean up temporary files that the compiler saved TemporaryFiles.Delete(); return(CompiledAssembly); }
protected int BuildRFCProxyDLL(string[] strArrayProxySource, string strFilePath, bool bClientProxy) { CSharpCodeProvider oCSProvider = null; CompilerParameters oParameters = null; TempFileCollection oTMPCollect = null; string strTempDir = null; CompilerResults oCResults = null; Evidence evidence = null; string strResult = null; try { oCSProvider = new CSharpCodeProvider(); oParameters = new CompilerParameters(); oParameters.GenerateExecutable = false; oParameters.GenerateInMemory = false; oParameters.TreatWarningsAsErrors = false; oParameters.CompilerOptions = "/target:library"; strTempDir = Path.GetTempPath(); oTMPCollect = new TempFileCollection(strTempDir); oCResults = new CompilerResults(oTMPCollect); evidence = new Evidence(null); Url url = new Url("http://rfcschemaproxygenerator"); evidence.AddHost(url); oParameters.Evidence = evidence; oParameters.ReferencedAssemblies.Add("System.dll"); oParameters.ReferencedAssemblies.Add("System.Data.dll"); oParameters.ReferencedAssemblies.Add("System.XML.dll"); oParameters.ReferencedAssemblies.Add("SAP.Connector.dll"); oParameters.ReferencedAssemblies.Add("System.Web.Services.dll"); if (!bClientProxy) { oParameters.ReferencedAssemblies.Add("sap.connector.rfc.dll"); } oParameters.OutputAssembly = strFilePath.ToString(new CultureInfo(Thread.CurrentThread.CurrentUICulture.ToString())); oCResults = oCSProvider.CompileAssemblyFromSource(oParameters, strArrayProxySource); oCResults.Evidence.AddHost(url); if (!oCResults.Errors.Count.Equals(0)) { for (int idx = 0; idx < oCResults.Errors.Count; ++idx) { strResult = strResult + oCResults.Errors[idx].ToString() + " "; } throw new Exception(strResult); } } catch (Exception exp) { throw exp; } finally { oTMPCollect.Delete(); } return(oCResults.Errors.Count); }
//TODO: Image type needs to be more dynamically chosen... public static DeckModel OpenPPT(FileInfo file, BackgroundWorker worker, DoWorkEventArgs progress) { //Start the progress bar if (worker != null) { worker.ReportProgress(0, "Initializing..."); } //Make the default flat tree representation of the PPT //Try to detect if powerpoint is already running (powerpnt.exe) bool pptAlreadyRunning = false; Process[] processes = Process.GetProcesses(); for (int i = 0; i < processes.Length; i++) { string currentProcess = processes[i].ProcessName.ToLower(); if (currentProcess == "powerpnt") { pptAlreadyRunning = true; break; } } //Open PowerPoint + open file PowerPoint.Application pptapp; try { pptapp = new PowerPoint.Application(); } catch (Exception e) { throw new PPTNotInstalledException("Failed to create PowerPoint Application. See InnerException for details.", e); } PowerPoint._Presentation presentation; try { presentation = pptapp.Presentations.Open(file.FullName, Core.MsoTriState.msoTrue, Core.MsoTriState.msoFalse, Core.MsoTriState.msoFalse); } catch (Exception e) { throw new PPTFileOpenException("Failed to open PowerPoint file. See InnerException for details.", e); } //Initialize the PPT Shape tag reader PPTPaneManagement.PPTPaneManager pptpm = new PPTPaneManagement.PPTPaneManager(); //Create a new DeckModel DeckModel deck = new DeckModel(Guid.NewGuid(), DeckDisposition.Empty, file.Name); //Initialize a temporary file collection that will be where slide images are exported to TempFileCollection tempFileCollection = new TempFileCollection(); string dirpath = tempFileCollection.BasePath; if (!Directory.Exists(dirpath)) { Directory.CreateDirectory(dirpath); } else { Directory.Delete(dirpath, true); Directory.CreateDirectory(dirpath); } //Lock it using (Synchronizer.Lock(deck.SyncRoot)) { //Iterate over all slides for (int i = 1; i <= presentation.Slides.Count; i++) { if (progress != null && progress.Cancel) { break; } //Get the slide PowerPoint._Slide currentSlide = presentation.Slides[i]; SlideModel newSlideModel = CreateSlide(presentation.PageSetup, pptpm, deck, tempFileCollection, dirpath, currentSlide); //Create a new Entry + reference SlideModel TableOfContentsModel.Entry newEntry = new TableOfContentsModel.Entry(Guid.NewGuid(), deck.TableOfContents, newSlideModel); //Lock the TOC using (Synchronizer.Lock(deck.TableOfContents.SyncRoot)) { //Add Entry to TOC deck.TableOfContents.Entries.Add(newEntry); } //Increment the ProgressBarForm if (worker != null) { worker.ReportProgress((i * 100) / presentation.Slides.Count, "Reading slide " + i + " of " + presentation.Slides.Count); } } } //Close the presentation presentation.Close(); presentation = null; //If PowerPoint was not open before, close PowerPoint if (!pptAlreadyRunning) { pptapp.Quit(); pptapp = null; } GC.Collect(); //Delete temp directory tempFileCollection.Delete(); Directory.Delete(dirpath); if (worker != null) { worker.ReportProgress(100, "Done!"); } //Return the deck if (progress != null) { progress.Result = deck; } return(deck); }
/// <summary> /// this runs in a worker thread /// </summary> private static void OnDoTransformWork(object sender, DoWorkEventArgs args) { ProgressState progressState = (ProgressState)args.Argument; XslCompiledTransform transform = null; try { TransformWorkerArguments workerArguments = (TransformWorkerArguments)progressState.Arguments; transform = new XslCompiledTransform(); //all this just to allow a DTD statement in the source xslt XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.ProhibitDtd = false; progressState.StatusLabel = "Preparing..."; using (Stream stream = workerArguments.xsltStream) { using (XmlReader xsltReader = XmlReader.Create(stream, readerSettings)) { XsltSettings settings = new XsltSettings(true, true); transform.Load(xsltReader, settings, new XmlUrlResolver()); xsltReader.Close(); } stream.Close(); } progressState.StatusLabel = "Transforming..."; int entriesCount = workerArguments.inputDocument.SelectNodes("//entry").Count; progressState.TotalNumberOfSteps = 2 * (entriesCount) + workerArguments.postTransformSteps; _staticProgressStateForWorker = progressState; workerArguments.xsltArguments.XsltMessageEncountered += OnXsltMessageEncountered; if (!workerArguments.outputToXml) { transform.Transform(workerArguments.inputDocument, workerArguments.xsltArguments, workerArguments.outputStream); } else { //all this is to stop sticking on the BOM, which trips up princeXML XmlWriterSettings writerSettings = CanonicalXmlSettings.CreateXmlWriterSettings(); writerSettings.Encoding = new UTF8Encoding(false); using (var writer = XmlWriter.Create(workerArguments.outputStream, writerSettings)) { transform.Transform(workerArguments.inputDocument, workerArguments.xsltArguments, writer); } } workerArguments.outputStream.Close(); //let the next guy get at the file Debug.Assert(progressState.NumberOfStepsCompleted <= entriesCount, "Should use up more than we reserved for ourselves"); progressState.NumberOfStepsCompleted = entriesCount; if (workerArguments.postTransformMethod != null) { workerArguments.postTransformMethod.Invoke(sender, args); } progressState.State = ProgressState.StateValue.Finished; } catch (CancelingException) // not an error { progressState.State = ProgressState.StateValue.Finished; } catch (Exception err) { //currently, error reporter can choke because this is //being called from a non sta thread. //so let's leave it to the progress dialog to report the error // Reporting.ErrorReporter.ReportException(args,null, false); progressState.ExceptionThatWasEncountered = err; progressState.WriteToLog(err.Message); progressState.State = ProgressState.StateValue.StoppedWithError; } finally { if (transform != null) { progressState.StatusLabel = "Cleaning up..."; TempFileCollection tempfiles = transform.TemporaryFiles; if (tempfiles != null) // tempfiles will be null when debugging is not enabled { tempfiles.Delete(); } } } }
/// <summary> /// The Delete method examines each file in the collection to determine, on an individual basis, whether the file is to be kept or deleted. /// Files can be explicitly marked to be kept when added to the collection using add methods that take a keepFile parameter. /// When adding a file to the collection using the AddExtension overload that does not have a keepFile parameter the value of the KeepFiles property is used as the default keep file indicator. /// </summary> public void DeleteFiles() { _tempFileCollection.Delete(); }
/// <summary> /// PROXY 소스에서 DLL 파일을 빌드한다. /// </summary> /// <param name="strProxySource">BUILD 대상 소스 클래스</param> /// <param name="strFilePath">출력 파일의 경로</param> /// <param name="bClientProxy">Proxy 형태, true:Client, false:Server</param> /// <returns>함수 수행 결과 코드</returns> protected int BuildRFCProxyDLL(string[] strArrayProxySource, string strFilePath, bool bClientProxy) { CSharpCodeProvider oCSProvider = null; // C# 코드 생성기 및 코드 컴파일러의 인스턴스에 액세스 //ICodeCompiler iCompiler = null; // 컴파일러 인터페이스 CompilerParameters oParameters = null; // 컴파일러 매개 변수 TempFileCollection oTMPCollect = null; // 임시 파일의 컬렉션 string strTempDir = null; // 시스템의 임시 파일 경로 CompilerResults oCResults = null; // 컴파일 결과 Evidence evidence = null; // 보안 정책 관련 설정 string strResult = null; // Compile 결과 try { oCSProvider = new CSharpCodeProvider(); // Provider 개체 생성 //iCompiler = oCSProvider.CreateCompiler(); // 컴파일러 인터페이스 생성 oParameters = new CompilerParameters(); // 컴파일러 매개 변수 개체 생성 oParameters.GenerateExecutable = false; // DLL 파일로 생성 oParameters.GenerateInMemory = false; // 컴파일러에서 출력을 메모리에 생성해지 않음 oParameters.TreatWarningsAsErrors = false; // 경고를 오류로 간주하지 않음 oParameters.CompilerOptions = "/target:library"; // 라이브러리 형태로 생성 strTempDir = Path.GetTempPath(); // 현재 시스템의 임시 파일 경로를 반환 oTMPCollect = new TempFileCollection(strTempDir); // 시스템의 임시 파일 경로 설정 oCResults = new CompilerResults(oTMPCollect); // 컴파일 중에 생성되는 파일을 임시 경로에 저장하도록 설정 evidence = new Evidence(null); Url url = new Url("http://rfcschemaproxygenerator"); evidence.AddHost(url); oParameters.Evidence = evidence; // 참조 어셈블리 정보 설정 oParameters.ReferencedAssemblies.Add("System.dll"); oParameters.ReferencedAssemblies.Add("System.Data.dll"); oParameters.ReferencedAssemblies.Add("System.XML.dll"); oParameters.ReferencedAssemblies.Add("SAP.Connector.dll"); oParameters.ReferencedAssemblies.Add("System.Web.Services.dll"); if (!bClientProxy) // 서버 형태인 경우 { oParameters.ReferencedAssemblies.Add("sap.connector.rfc.dll"); } // 출력 어셈블리 정보 설정 oParameters.OutputAssembly = strFilePath.ToString(new CultureInfo(Thread.CurrentThread.CurrentUICulture.ToString())); // 어셈블리 컴파일 //oCResults = iCompiler.CompileAssemblyFromSourceBatch(oParameters, strArrayProxySource); oCResults = oCSProvider.CompileAssemblyFromSource(oParameters, strArrayProxySource); oCResults.Evidence.AddHost(url); if (!oCResults.Errors.Count.Equals(0)) { for (int idx = 0; idx < oCResults.Errors.Count; ++idx) { strResult = strResult + oCResults.Errors[idx].ToString() + " "; } throw new Exception(strResult); } } catch (Exception exp) { throw exp; } finally { oTMPCollect.Delete(); } return(oCResults.Errors.Count); }
/// <summary> /// Save an object to ini file /// </summary> /// <param name="o">object to save</param> /// <param name="section">[Section] to save to</param> /// <param name="propertynames">array of properties to save</param> /// <param name="file">ini file name</param> public static void Save(object o, string section, string[] propertynames, string file, bool makebackupfile) { lock (sm_locker) { FileInfo fi = new FileInfo(file); if (fi.Exists) { FileAttributes fattr = File.GetAttributes(file); fattr &= ~FileAttributes.ReadOnly; File.SetAttributes(file, fattr); } if (Directory.Exists(Path.GetDirectoryName(file)) == false) { Directory.CreateDirectory(Path.GetDirectoryName(file)); } //get a temp file using (TempFileCollection tempfiles = new TempFileCollection(fi.DirectoryName, false)) { string tempfile = tempfiles.AddExtension(fi.Extension, false); if (fi.Exists) { File.Copy(file, tempfile); FileAttributes tattr = File.GetAttributes(tempfile); tattr &= ~FileAttributes.ReadOnly; File.SetAttributes(tempfile, tattr); } Type t = o.GetType(); ArrayList pis = new ArrayList(); foreach (string s in propertynames) { PropertyInfo propinfo = t.GetProperty(s); if (propinfo != null) { pis.Add(propinfo); } } Dictionary <string, string> existingEntries = GetIniSectionDictionary(section, file); foreach (PropertyInfo pi in pis) { bool hassetandget = pi.CanRead & pi.CanWrite; //if (hassetandget) { object v = pi.GetValue(o, null); string key = pi.Name; string inival = StringConverter.ConvertToString(v);//v.ToString(); string defval = ""; DefaultValueAttribute[] defvalfields = (DefaultValueAttribute[])pi.GetCustomAttributes(typeof(DefaultValueAttribute), true); if (defvalfields.Length > 0) { if (defvalfields[0].Value != null) { defval = StringConverter.ConvertToString(defvalfields[0].Value); } } string curinival = GetIniSectionValuefromDictionary(existingEntries, key, defval);//Ini.sGetPrivateProfileString(section, key, tempfile, defval); if ((curinival != inival) || SaveDefaultValues) { Ini.WritePrivateProfileString(section, key, inival, tempfile); } } } DateTime now = DateTime.Now; string datesuffix = string.Format("{0:00}{1:00}{2:00}{3:00}{4:00}", now.Month, now.Day, now.Year, now.Hour, now.Minute); //make a backup of the original file string backupfile = Path.Combine(BackupFolder.Path, Path.GetFileName(file) + ".BACKUP" + datesuffix); if (fi.Exists) { // check for read only flag, remove it if needed if (makebackupfile) { if (File.Exists(backupfile)) { FileAttributes attr = File.GetAttributes(backupfile); attr &= ~FileAttributes.ReadOnly; File.SetAttributes(backupfile, attr); } File.Copy(file, backupfile, true); File.SetAttributes(backupfile, FileAttributes.ReadOnly); } fi.Delete(); } //if we got here, then we should be OK if (File.Exists(tempfile)) { File.Move(tempfile, file); } tempfiles.Delete(); } } }
public void Transform(ProgressState progressState) { _progressState = progressState; XslCompiledTransform transform = null; using (Stream outputStream = File.Create(OutputFilePath)) { XmlDocument inputDocument = new XmlDocument(); inputDocument.PreserveWhitespace = true; inputDocument.Load(_inputFilePath); try { transform = new XslCompiledTransform(); //all this just to allow a DTD statement in the source xslt XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.DtdProcessing = DtdProcessing.Parse; _progressState.StatusLabel = "Preparing..."; using (Stream stream = _xsltStream) { using (XmlReader xsltReader = XmlReader.Create(stream, readerSettings)) { XsltSettings settings = new XsltSettings(true, true); transform.Load(xsltReader, settings, new XmlUrlResolver()); xsltReader.Close(); } stream.Close(); } _progressState.StatusLabel = "Processing..."; int entriesCount = 1; XmlNodeList nodeCountList = inputDocument.SelectNodes(_xpathToCountSteps); if (nodeCountList != null) { entriesCount = nodeCountList.Count; } _progressState.TotalNumberOfSteps = entriesCount; if (_xsltArguments == null) { _xsltArguments = new XsltArgumentList(); } _xsltArguments.XsltMessageEncountered += OnXsltMessageEncountered; transform.Transform(inputDocument, _xsltArguments, outputStream); outputStream.Close(); //let the next guy get at the file Debug.Assert(_progressState.NumberOfStepsCompleted <= entriesCount, "Should use up more than we reserved for ourselves"); _progressState.NumberOfStepsCompleted = entriesCount; _progressState.State = ProgressState.StateValue.Finished; } catch (CancelingException) //not an error { _progressState.State = ProgressState.StateValue.Finished; } catch (Exception err) { //currently, error reporter can choke because this is //being called from a non sta thread. //so let's leave it to the progress dialog to report the error // Reporting.ErrorReporter.ReportException(args,null, false); _progressState.ExceptionThatWasEncountered = err; _progressState.WriteToLog(err.Message); _progressState.State = ProgressState.StateValue.StoppedWithError; } finally { if (transform != null) { _progressState.StatusLabel = "Cleaning up..."; TempFileCollection tempfiles = transform.TemporaryFiles; if (tempfiles != null) // tempfiles will be null when debugging is not enabled { tempfiles.Delete(); } } } } }
/// <summary> /// Save an object to ini file, except for the properties marked with the DontSerializeAttribute. /// </summary> /// <param name="o">object to save</param> /// <param name="section">[Section] to save to</param> /// <param name="file">ini file name</param> /// <param name="makebackupfile">makes a backup file</param> public static void Save(object o, string section, string file, bool makebackupfile) { lock (sm_locker) { if (Directory.Exists(Path.GetDirectoryName(file)) == false) { try { Directory.CreateDirectory(Path.GetDirectoryName(file)); } catch (Exception ex) { throw new ApplicationException(string.Format("Unable to create directory '{0}'.", Path.GetDirectoryName(file)), ex); } } bool changesToIni = false; FileInfo fi = new FileInfo(file); if (fi.Exists) { FileAttributes fattr = File.GetAttributes(file); if ((fattr & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { fattr &= ~FileAttributes.ReadOnly; File.SetAttributes(file, fattr); } } //get a temp file using (TempFileCollection tempfiles = new TempFileCollection(fi.DirectoryName, false)) { string tempfile = tempfiles.AddExtension(fi.Extension, false); //if (fi.Exists) //{ // File.Copy(file, tempfile); // FileAttributes tattr = File.GetAttributes(tempfile); // tattr &= ~FileAttributes.ReadOnly; // File.SetAttributes(tempfile, tattr); //} Type t = o.GetType(); PropertyInfo[] pis = t.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.SetField); Dictionary <string, string> existingEntries = GetIniSectionDictionary(section, file); foreach (PropertyInfo pi in pis) { try { DontSerializeAttribute[] fields = (DontSerializeAttribute[])pi.GetCustomAttributes(typeof(DontSerializeAttribute), true); if (fields.Length == 0) { bool hassetandget = pi.CanRead & pi.CanWrite; //if (hassetandget) { object v = pi.GetValue(o, null); string key = pi.Name; string inival = StringConverter.ConvertToString(v); string defval = ""; DefaultValueAttribute[] defvalfields = (DefaultValueAttribute[])pi.GetCustomAttributes(typeof(DefaultValueAttribute), true); if (defvalfields.Length > 0) { if (defvalfields[0].Value != null) { defval = StringConverter.ConvertToString(defvalfields[0].Value); } } string curinival = GetIniSectionValuefromDictionary(existingEntries, key, defval);//Ini.sGetPrivateProfileString(section, key, tempfile, defval); if ((curinival != inival) || SaveDefaultValues) { if (changesToIni == false) { changesToIni = true; if (fi.Exists) { File.Copy(file, tempfile); FileAttributes tattr = File.GetAttributes(tempfile); if ((tattr & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { tattr &= ~FileAttributes.ReadOnly; File.SetAttributes(tempfile, tattr); } } } Ini.WritePrivateProfileString(section, key, inival, tempfile); } } } } catch (Exception exc) { MsgBox.ShowException(exc); } } if (changesToIni) { //make a backup of the original file DateTime now = DateTime.Now; string datesuffix = string.Format("{0:00}{1:00}{2:00}{3:00}{4:00}", now.Month, now.Day, now.Year, now.Hour, now.Minute); //make a backup of the original file string backupfile = Path.Combine(BackupFolder.Path, Path.GetFileName(file) + ".BACKUP" + datesuffix); if (fi.Exists) { // check for read only flag, remove it if needed if (makebackupfile) { if (File.Exists(backupfile)) { FileAttributes attr = File.GetAttributes(backupfile); attr &= ~FileAttributes.ReadOnly; File.SetAttributes(backupfile, attr); } File.Copy(file, backupfile, true); File.SetAttributes(backupfile, FileAttributes.ReadOnly); } fi.Delete(); } //if we got here, then we should be OK if (File.Exists(tempfile)) { File.Move(tempfile, file); } tempfiles.Delete(); } } } }
/// <summary> /// Executes the alphabetize operation on the set of RESX files. /// </summary> /// <param name="filename"> /// The name of the RESX file to alphabetize. /// </param> /// <seealso cref="Paraesthesia.Tools.NAntTasks.AlphaResx.AlphaResxTask" /> protected virtual void AlphabetizeResxFile(string filename) { TempFileCollection tempFiles = null; try { tempFiles = new TempFileCollection(); tempFiles.KeepFiles = false; if (!Directory.Exists(tempFiles.BasePath)) { Directory.CreateDirectory(tempFiles.BasePath); } string tfName = Path.Combine(tempFiles.BasePath, Path.GetFileName(filename)); using (ResXResourceReader reader = new ResXResourceReader(filename)) { // Add the resources to a dictionary that will be sorted later. Dictionary <string, object> resources = new Dictionary <string, object>(); IDictionaryEnumerator id = reader.GetEnumerator(); foreach (DictionaryEntry d in reader) { resources.Add(d.Key.ToString(), d.Value); } // Write the resources to a temporary file in alpha order by key. using (ResXResourceWriter writer = new ResXResourceWriter(tfName)) { List <string> resourceKeys = new List <string>(); resourceKeys.AddRange(resources.Keys); resourceKeys.Sort(); foreach (string key in resourceKeys) { writer.AddResource(key, resources[key]); } writer.Generate(); writer.Close(); } } // Copy temp file over original file if (File.Exists(tfName)) { File.Copy(tfName, filename, true); this.Log(Level.Info, "Alphabetized RESX file {0}", filename); } else { if (this.FailOnError) { throw new BuildException(String.Format(CultureInfo.InvariantCulture, "Unable to alphabetize RESX file {0}", filename), this.Location); } else { this.Log(Level.Error, "Unable to alphabetize RESX file {0}", filename); } } } finally { if (tempFiles != null) { tempFiles.Delete(); if (Directory.Exists(tempFiles.BasePath)) { Directory.Delete(tempFiles.BasePath, true); } tempFiles = null; } } }
public void Dispose() { _transformedFiles.Delete(); _resourcesDir.Dispose(); GC.SuppressFinalize(this); }
private static Assembly CompileAssembly(FileReference OutputAssemblyPath, HashSet <FileReference> SourceFileNames, List <string> ReferencedAssembies, List <string> PreprocessorDefines = null, bool TreatWarningsAsErrors = false) { TempFileCollection TemporaryFiles = new TempFileCollection(); // Setup compile parameters CompilerParameters CompileParams = new CompilerParameters(); { // Always compile the assembly to a file on disk, so that we can load a cached version later if we have one CompileParams.GenerateInMemory = false; // This is the full path to the assembly file we're generating CompileParams.OutputAssembly = OutputAssemblyPath.FullName; // We always want to generate a class library, not an executable CompileParams.GenerateExecutable = false; // Never fail compiles for warnings CompileParams.TreatWarningsAsErrors = false; // Set the warning level so that we will actually receive warnings - // doesn't abort compilation as stated in documentation! CompileParams.WarningLevel = 4; // Always generate debug information as it takes minimal time CompileParams.IncludeDebugInformation = true; #if !DEBUG // Optimise the managed code in Development CompileParams.CompilerOptions += " /optimize"; #endif Log.TraceVerbose("Compiling " + OutputAssemblyPath); // Keep track of temporary files emitted by the compiler so we can clean them up later CompileParams.TempFiles = TemporaryFiles; // Warnings as errors if desired CompileParams.TreatWarningsAsErrors = TreatWarningsAsErrors; // Add assembly references { if (ReferencedAssembies == null) { // Always depend on the CLR System assembly CompileParams.ReferencedAssemblies.Add("System.dll"); CompileParams.ReferencedAssemblies.Add("System.Core.dll"); } else { // Add in the set of passed in referenced assemblies CompileParams.ReferencedAssemblies.AddRange(ReferencedAssembies.ToArray()); } // The assembly will depend on this application Assembly UnrealBuildToolAssembly = Assembly.GetExecutingAssembly(); CompileParams.ReferencedAssemblies.Add(UnrealBuildToolAssembly.Location); // The assembly will depend on the utilities assembly. Find that assembly // by looking for the one that contains a common utility class Assembly UtilitiesAssembly = Assembly.GetAssembly(typeof(FileReference)); CompileParams.ReferencedAssemblies.Add(UtilitiesAssembly.Location); } // Add preprocessor definitions if (PreprocessorDefines != null && PreprocessorDefines.Count > 0) { CompileParams.CompilerOptions += " /define:"; for (int DefinitionIndex = 0; DefinitionIndex < PreprocessorDefines.Count; ++DefinitionIndex) { if (DefinitionIndex > 0) { CompileParams.CompilerOptions += ";"; } CompileParams.CompilerOptions += PreprocessorDefines[DefinitionIndex]; } } // @todo: Consider embedding resources in generated assembly file (version/copyright/signing) } // Create the output directory if it doesn't exist already DirectoryInfo DirInfo = new DirectoryInfo(OutputAssemblyPath.Directory.FullName); if (!DirInfo.Exists) { try { DirInfo.Create(); } catch (Exception Ex) { throw new BuildException(Ex, "Unable to create directory '{0}' for intermediate assemblies (Exception: {1})", OutputAssemblyPath, Ex.Message); } } // Compile the code CompilerResults CompileResults; try { Dictionary <string, string> ProviderOptions = new Dictionary <string, string>() { { "CompilerVersion", "v4.0" } }; CSharpCodeProvider Compiler = new CSharpCodeProvider(ProviderOptions); CompileResults = Compiler.CompileAssemblyFromFile(CompileParams, SourceFileNames.Select(x => x.FullName).ToArray()); } catch (Exception Ex) { throw new BuildException(Ex, "Failed to launch compiler to compile assembly from source files:\n {0}\n(Exception: {1})", String.Join("\n ", SourceFileNames), Ex.ToString()); } // Display compilation warnings and errors if (CompileResults.Errors.Count > 0) { Log.TraceInformation("While compiling {0}:", OutputAssemblyPath); foreach (CompilerError CurError in CompileResults.Errors) { Log.WriteLine(0, CurError.IsWarning? LogEventType.Warning : LogEventType.Error, LogFormatOptions.NoSeverityPrefix, "{0}", CurError.ToString()); } if (CompileResults.Errors.HasErrors || TreatWarningsAsErrors) { throw new BuildException("Unable to compile source files."); } } // Grab the generated assembly Assembly CompiledAssembly = CompileResults.CompiledAssembly; if (CompiledAssembly == null) { throw new BuildException("UnrealBuildTool was unable to compile an assembly for '{0}'", SourceFileNames.ToString()); } // Clean up temporary files that the compiler saved TemporaryFiles.Delete(); return(CompiledAssembly); }
//Clean the current session temp files (May skip some files due to it being used by a process) public static void CleanTempSession() { _collection.Delete(); }
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; }
public void Dispose() { files.Delete(); }