public void AddExtension_InvalidFileExtension_ThrowsArgumentException(string fileExtension) { using (var collection = new TempFileCollection()) { Assert.Throws <ArgumentException>("fileExtension", () => collection.AddExtension(fileExtension)); Assert.Throws <ArgumentException>("fileExtension", () => collection.AddExtension(fileExtension, keepFile: false)); } }
public void PermitOnly_FileIOPermission_EnvironmentPermission() { TempFileCollection tfc = new TempFileCollection(); // ok Assert.IsNotNull(tfc.BasePath, "BasePath"); tfc.AddExtension(".cs"); tfc.AddExtension(".cx", true); // both AddExtension methods depends on BasePath Assert.AreEqual(String.Empty, tfc.TempDir, "TempDir"); // and that last one is *important* }
private void ViewMessage(MessageViewModel message) { if (Settings.Default.UseMessageInspectorOnDoubleClick) { InspectMessage(message); return; } TempFileCollection tempFiles = new TempFileCollection(); FileInfo msgFile = new FileInfo(tempFiles.AddExtension("eml")); message.SaveToFile(msgFile); if (Registry.ClassesRoot.OpenSubKey(".eml", false) == null || string.IsNullOrEmpty((string)Registry.ClassesRoot.OpenSubKey(".eml", false).GetValue(null))) { switch (MessageBox.Show(this, "You don't appear to have a viewer application associated with .eml files!\nWould you like to download Windows Live Mail (free from live.com website)?", "View Message", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)) { case DialogResult.Yes: Process.Start("http://download.live.com/wlmail"); return; case DialogResult.Cancel: return; } } Process.Start(msgFile.FullName); messageGrid.Refresh(); }
public IHttpActionResult Post([FromBody] Request request) { var asm = Assembly.GetExecutingAssembly(); var path = Path.GetDirectoryName(asm.Location); using (var temp = new TempFileCollection(path, false)) { var file = temp.AddExtension("jpg"); File.WriteAllBytes(file, Convert.FromBase64String(request.Base64Image)); try { var results = OpenAlprHelper.Recognize(file, "gb"); if (results == null || !results.Plates.Any()) { return(NotFound()); } var model = new Result { Registration = results.Plates[0].TopNPlates[0].Characters, Confidence = results.Plates[0].TopNPlates[0].OverallConfidence }; return(Ok(model)); } catch (Exception ex) { return(BadRequest(ex.Message)); } } }
[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)); } }
/// <summary> /// Creates a temporary file with the provided contents. /// </summary> /// <param name="extension">The file extension requested</param> /// <param name="contents">Data containing the contents of the requested file.</param> /// <returns>A full path name to the newly created file.</returns> private string CreateTemporaryFile(string extension, string contents) { Debug.Assert(extension != null && extension.Length > 0); if (_tempFileCollection == null) { _tempFileCollection = new TempFileCollection(); } // // Create the temp file. // string fileName = _tempFileCollection.AddExtension(extension, KeepConfigFile); // // Populate the file. // if (contents != null) { using (StreamWriter sw = new StreamWriter(fileName, false)) { sw.Write(contents); } } return(fileName); }
/// <summary> /// Converts a <see cref="DataTable"/> to an SPSS .SAV file. /// </summary> /// <param name="dataTable"> /// The <see cref="DataTable"/> with the schema and data to fill into the SPSS .SAV file. /// </param> /// <param name="data">An enumerable list of DataRows.</param> /// <param name="fillInMetaDataCallBack"> /// The callback method that will provide additional metadata on each column. /// </param> /// <returns> /// A <see cref="MemoryStream"/> containing the contents of the SPSS .SAV data file. /// </returns> /// <remarks> /// A temporary file is created during this process, but is guaranteed to be removed /// as the method returns. /// </remarks> public static MemoryStream ToStream(DataTable dataTable, IEnumerable <DataRow> data, Action <SpssVariable> fillInMetaDataCallBack) { // Create a temporary file for the SPSS data that we will generate. using (TempFileCollection tfc = new TempFileCollection()) { string filename = tfc.AddExtension("sav", false); ToFile(dataTable, data, filename, fillInMetaDataCallBack); // Now read the file into memory using (FileStream fs = File.OpenRead(filename)) { MemoryStream ms = new MemoryStream((int)fs.Length); int b = 0; while ((b = fs.ReadByte()) >= 0) { ms.WriteByte((byte)b); } // reset to start of stream. ms.Position = 0; // return the memory stream. All temporary files will delete as we exit. return(ms); } } }
/// <summary> /// Converts the metadata in an SPSS .SAV data file into a DataTable. /// </summary> /// <param name="spssSav"> /// The stream containing the SPSS .SAV data file. /// </param> /// <returns> /// The <see cref="DataTable"/> containing all the metadata. /// </returns> public static DataTable ToDataTable(Stream spssSav) { if (spssSav == null) { throw new ArgumentNullException("spssSav"); } // To read an SPSS file, spssio32.dll requires that the file is actually on disk, // so persist this stream to a temporary file on disk. using (TempFileCollection tfc = new TempFileCollection()) { string filename = tfc.AddExtension("sav", false); using (FileStream fs = new FileStream(filename, FileMode.CreateNew)) { int b; while ((b = spssSav.ReadByte()) >= 0) { fs.WriteByte((byte)b); } } return(ToDataTable(filename)); // leaving this block will remove the temporary file automatically } }
public IActionResult Posting(TransformOperationParam json) { var OSGeo4WShell = Configuration["ScriptRunners:OSGeo4WPath"]; // Creating temp directory to store ogr2ogr output string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Directory.CreateDirectory(tempDirectory); string tempDirectoryFile = Path.Combine(tempDirectory, Path.ChangeExtension(Path.GetRandomFileName(), json.SingleFileFormat)); ResultObject output; // file disposes after block using (TempFileCollection files = new TempFileCollection()) { string file = files.AddExtension("geojson"); System.IO.File.WriteAllText(file, json.InputLayer.ToString()); string cmdInput = _creator.buildOgr2Ogr(json, "ogr2ogr", tempDirectoryFile, file); output = _python.RunCMD(cmdInput, OSGeo4WShell); } var result = _outputHandler.HandleGdalOutput(output, tempDirectory); // Deleting source DirectoryInfo directory = new DirectoryInfo(tempDirectory); directory.Delete(true); return(result); }
public void AddExtension2_Deny_FileIOPermission() { TempFileCollection tfc = new TempFileCollection(); // requires path access tfc.AddExtension(".cx", true); }
[Category("NotDotNet")] // MS doesn't check for Environment under 1.x #endif public void AddExtension2_PermitOnly_FileIOPermission() { TempFileCollection tfc = new TempFileCollection(); // good but not enough tfc.AddExtension(".cx", true); }
[Category("NotDotNet")] // MS doesn't check for Environment under 1.x #endif public void AddExtension2_Deny_EnvironmentPermission() { TempFileCollection tfc = new TempFileCollection(); // requires Unrestricted Environment access tfc.AddExtension(".cx", true); }
public void AddExtension_PermitOnly_EnvironmentPermission() { TempFileCollection tfc = new TempFileCollection(); // good but not enough tfc.AddExtension(".cs"); }
public static void Save(object o, string topsection, string file, bool makebackupfile) { lock (IniSerializer.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); } _Save(o, topsection, tempfile); //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(); } } }
public void FileLoggerTest() { var tfc = new TempFileCollection(); var fileName = tfc.AddExtension("txt"); var logger = LoggerFactory.Instance.GetLogger(LogType.File, fileName); logger.Log(TEST_LOG); }
public void ViewLog() { TempFileCollection tempFiles = new TempFileCollection(); FileInfo msgFile = new FileInfo(tempFiles.AddExtension("txt")); File.WriteAllText(msgFile.FullName, Session.Log, Encoding.ASCII); Process.Start(msgFile.FullName); }
public void FileSerializeMatchesLength() { using (TempFileCollection tfc = new TempFileCollection()) { string file = tfc.AddExtension(".txt"); File.WriteAllText(file, "sometext"); var part = MultipartPostPart.CreateFormFilePart("someformname", file, "text/plain"); VerifyLength(part); } }
public void AddAddressNoteWithFile(string routeId, int addressId) { // Create the manager with the api key Route4MeManager route4Me = new Route4MeManager(c_ApiKey); NoteParameters noteParameters = new NoteParameters() { RouteId = routeId, AddressId = addressId, Latitude = 33.132675170898, Longitude = -83.244743347168, DeviceType = DeviceType.Web.Description(), ActivityType = StatusUpdateType.DropOff.Description() }; string[] names = Assembly.GetExecutingAssembly().GetManifestResourceNames(); foreach (string nm in names) { Console.WriteLine(nm); } string tempFilePath = null; using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Route4MeSDKTest.Resources.test.png")) { var tempFiles = new TempFileCollection(); { tempFilePath = tempFiles.AddExtension("png"); System.Console.WriteLine(tempFilePath); using (Stream fileStream = File.OpenWrite(tempFilePath)) { stream.CopyTo(fileStream); } } } // Run the query string errorString; string contents = "Test Note Contents with Attachment " + DateTime.Now.ToString(); AddressNote note = route4Me.AddAddressNote(noteParameters, contents, tempFilePath, out errorString); Console.WriteLine(""); if (note != null) { Console.WriteLine("AddAddressNoteWithFile executed successfully"); Console.WriteLine("Note ID: {0}", note.NoteId); } else { Console.WriteLine("AddAddressNoteWithFile error: {0}", errorString); } }
public void AddAddressNoteWithFile() { // Create the manager with the api key var route4Me = new Route4MeManager(ActualApiKey); RunOptimizationSingleDriverRoute10Stops(); OptimizationsToRemove = new List <string>() { SD10Stops_optimization_problem_id }; var noteParameters = new NoteParameters() { RouteId = SD10Stops_route_id, AddressId = (int)SD10Stops_route.Addresses[1].RouteDestinationId, Latitude = 33.132675170898, Longitude = -83.244743347168, DeviceType = DeviceType.Web.Description(), ActivityType = StatusUpdateType.DropOff.Description() }; string[] names = Assembly.GetExecutingAssembly().GetManifestResourceNames(); foreach (string nm in names) { Console.WriteLine(nm); } string tempFilePath = null; using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Route4MeSDKTest.Resources.test.png")) { var tempFiles = new TempFileCollection(); { tempFilePath = tempFiles.AddExtension("png"); Console.WriteLine(tempFilePath); using (Stream fileStream = File.OpenWrite(tempFilePath)) { stream.CopyTo(fileStream); } } } // Run the query string contents = "Test Note Contents with Attachment " + DateTime.Now.ToString(); AddressNote note = route4Me.AddAddressNote( noteParameters, contents, tempFilePath, out string errorString); PrintExampleAddressNote(note, errorString); RemoveTestOptimizations(); }
public void AddFileExtension() { string tempDirectory = TempDirectory(); using (var collection = new TempFileCollection(tempDirectory)) { string file = collection.AddExtension("txt"); Assert.False(File.Exists(file)); Assert.Equal(collection.BasePath + "." + "txt", file); } }
public void MultiPartPostMultiByteCharacters() { using (TempFileCollection tfc = new TempFileCollection()) { string file = tfc.AddExtension("txt"); File.WriteAllText(file, "\x1020\x818"); this.VerifyFullPost(new List <MultipartPostPart> { MultipartPostPart.CreateFormPart("a", "\x987"), MultipartPostPart.CreateFormFilePart("SomeFormField", file, "text/plain"), }); } }
public void MultiPartPostAscii() { using (TempFileCollection tfc = new TempFileCollection()) { string file = tfc.AddExtension("txt"); File.WriteAllText(file, "sometext"); this.VerifyFullPost(new List <MultipartPostPart> { MultipartPostPart.CreateFormPart("a", "b"), MultipartPostPart.CreateFormFilePart("SomeFormField", file, "text/plain"), }); } }
public Assembly EndCompile() { Assembly ret = null; CompilerParameters compilerparams = new CompilerParameters(); compilerparams.GenerateInMemory = false; compilerparams.GenerateExecutable = false; compilerparams.IncludeDebugInformation = true; compilerparams.CompilerOptions = "/t:library"; TempFileCollection tempcoll = new TempFileCollection(DynamicDir(), true); compilerparams.TempFiles = tempcoll; string dllfilename = Path.GetFileName(tempcoll.AddExtension("dll", true)); compilerparams.OutputAssembly = Path.Combine(DynamicDir(), dllfilename); // cargamos los assemblies Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assem in assemblies) { try { if (Path.GetExtension(assem.Location).EndsWith("dll") && !compilerparams.ReferencedAssemblies.Contains(assem.Location)) { compilerparams.ReferencedAssemblies.Add(assem.Location); } } catch { } } foreach (string assem in _assemblies) { try { string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, assem); if (!compilerparams.ReferencedAssemblies.Contains(filePath)) { compilerparams.ReferencedAssemblies.Add(filePath); } } catch { } } CompilerResults results = provider.CompileAssemblyFromDom(compilerparams, unit); CheckCompilerErrors(results); results.TempFiles.Delete(); ret = results.CompiledAssembly; return(ret); }
/// <summary> /// Saves Rationale field into LinkedDocument /// </summary> /// <param name="element"></param> private void SaveDescription(IEAElement element) { //_element.Notes = Rationale; using (var tempFiles = new TempFileCollection()) { string fileName = tempFiles.AddExtension("rtf"); using (var file = new StreamWriter(fileName)) { file.WriteLine(Description); } element.LoadFileIntoLinkedDocument(fileName); } }
public void TestInvokerThreads() { var tfc = new TempFileCollection(); var ftpFileName = tfc.AddExtension("tmp1"); var httpFileName = tfc.AddExtension("tmp2"); var fileName = tfc.AddExtension("txt"); var fileManager = new FileManager(); var randFileCommand = new CreateRandomFileCommand(fileManager, fileName); var ftpClient = new WebClient(); var httpClient = new WebClient(); var ftpCommand = new FtpGetFileCommand(ftpClient, FTP_URI, ftpFileName); var httpCommand = new HttpGetFileCommand(httpClient, HTTP_URI, httpFileName); var invoker = new Invoker(true); invoker.Execute(ftpCommand); invoker.Execute(randFileCommand); invoker.Execute(httpCommand); Thread.Sleep(1000); using (var reader = File.OpenText(ftpFileName)) { var content = reader.ReadToEnd(); Assert.IsFalse(string.IsNullOrEmpty(content)); } using (var reader = File.OpenText(httpFileName)) { var content = reader.ReadToEnd(); Assert.IsFalse(string.IsNullOrEmpty(content)); } using (var reader = File.OpenText(fileName)) { var content = reader.ReadToEnd(); Assert.IsFalse(string.IsNullOrEmpty(content)); } }
public void TestCopy() { var tfc = new TempFileCollection(); var srcFileName = tfc.AddExtension("tmp1"); var destFileName = tfc.AddExtension("tmp2"); var fileManager = new FileManager(); var createCommand = new CreateRandomFileCommand(fileManager, srcFileName); var copyCommand = new CopyFileCommand(fileManager, srcFileName, destFileName); var invoker = new Invoker(); invoker.Execute(createCommand); invoker.Execute(copyCommand); using (StreamReader srcReader = File.OpenText(srcFileName), destReader = File.OpenText(destFileName)) { var srcContent = srcReader.ReadToEnd(); var destContent = destReader.ReadToEnd(); Assert.AreEqual(srcContent, destContent); } }
public static Texture getTextureFromResource(Bitmap resource) { using (var tempFiles = new TempFileCollection()) { string filePath = tempFiles.AddExtension("png"); resource.Save(filePath); if (File.Exists(filePath)) { return(Game.CreateTextureFromFile(filePath)); } } return(null); }
internal WriteFileContext(string filename, string templateFilename) { string directoryname = UrlPath.GetDirectoryOrRootName(filename); _templateFilename = templateFilename; _tempFiles = new TempFileCollection(directoryname); try { _tempNewFilename = _tempFiles.AddExtension("newcfg"); } catch { ((IDisposable)_tempFiles).Dispose(); _tempFiles = null; throw; } }
public void ToFile() { DataTable dt = new DataTable(); dt.Columns.Add("var1", typeof(int)); dt.Columns.Add("var2", typeof(string)); dt.Rows.Add(new object[] { 1, "hi" }); using (TempFileCollection tfc = new TempFileCollection()) { tfc.KeepFiles = false; string filename = tfc.AddExtension("sav"); SpssConvert.ToFile(dt, dt.Select(), filename, null); } }
public FileInfo FromString(string extension, string content) { var path = _collection.AddExtension($"{Convert.ToInt32(_random.Next())}.{extension}"); var fs = new FileInfo(path); using (var stream = fs.OpenWrite()) { var bytes = Encoding.UTF8.GetBytes(content); stream.Write(bytes, 0, bytes.Length); } return(fs); }