public IActionResult AddEditServer(string serverID, string name, string url, string type, string user, string password) { Guid id = Guid.NewGuid(); //Check if we are editing the server info if (serverID != "" && serverID != null) { id = Guid.Parse(serverID); } var server = new JObject(); server["ID"] = id.ToString(); server["name"] = name; server["url"] = url; //server["type"] = type; server["user"] = user; server["password"] = password; server["lastSync"] = ""; FileFactory.WriteFile(server, id.ToString(), XferFactory.FileType.Server, directory); return(RedirectToAction("Servers")); }
public static ApplicationDockItem NewFromUri(string uri) { try { GLib.File file = FileFactory.NewForUri(uri); if (!file.Exists) { return(null); } DesktopItem desktopItem = DockServices.DesktopItems.DesktopItemFromDesktopFile(file.Path); if (desktopItem == null) { desktopItem = new DesktopItem(file.Path); } return(new ApplicationDockItem(desktopItem)); } catch (Exception e) { Log <ApplicationDockItem> .Error(e.Message); Log <ApplicationDockItem> .Debug(e.StackTrace); } return(null); }
/// <summary> /// 签名搜索; /// </summary> /// <param name="blDevice"></param> /// <param name="setting"></param> public static void SignSearch(IStreamFile streamFile) { var setting = CustomSignSearchService.GetSetting(); if (setting == null) { return; } var loadingDialog = DialogService.Current.CreateLoadingDialog(); loadingDialog.WindowTitle = LanguageService.FindResourceString(Constants.WindowTitle_CustomSignSearch); var part = FileFactory.CreatePartition(Constants.PartitionKey_CustomSignSearch); var partStoken = part.GetStoken(Constants.PartitionKey_CustomSignSearch); partStoken.BaseStream = streamFile.BaseStream; if (streamFile is IPartition streamPart) { partStoken.Name = $"{FileExtensions.GetPartFixAndName(streamPart)}-{LanguageService.FindResourceString(Constants.DocumentTitle_CustomSignSearch)}" + $"({CDFCCultures.Helpers.ByteConverterHelper.ConvertToHexFormat(setting.KeyWord)})"; } else { partStoken.Name = $"{streamFile.Name}-{LanguageService.FindResourceString(Constants.DocumentTitle_CustomSignSearch)}" + $"({CDFCCultures.Helpers.ByteConverterHelper.ConvertToHexFormat(setting.KeyWord)})"; } (long position, long size)[] fileBlocks = null;
private void OnFileSystemItemCreated(object sender, FileSystemEventArgs e) { if (System.IO.Directory.Exists(e.FullPath)) { var createdDirectoryInfo = new DirectoryInfo(e.FullPath); if (!Index.TryGetValue(createdDirectoryInfo.Parent.FullName, out IFileSystemItemModel parentFileSystemItem) || parentFileSystemItem is not IDirectory parentDirectoryItem) { // File system item is not indexed/never visited before. // Changes will be visible the first time this folder or its child items are indexed/visited return; } var createdDirectoryItem = DirectoryFactory.Invoke(createdDirectoryInfo, parentDirectoryItem); AddNewFileSystemInfo(createdDirectoryItem, parentDirectoryItem); } else if (System.IO.File.Exists(e.FullPath)) { var createdFileInfo = new FileInfo(e.FullPath); if (!Index.TryGetValue(createdFileInfo.DirectoryName, out IFileSystemItemModel parentFileSystemItem) || parentFileSystemItem is not IDirectory parentDirectoryItem) { // File system item is not indexed/never visited before. // Changes will be visible the first time this folder or its child items are indexed/visited return; } var createdFileItem = FileFactory.Invoke(createdFileInfo, parentDirectoryItem); AddNewFileSystemInfo(createdFileItem, parentDirectoryItem); } }
public IActionResult Remove(string id) { FileFactory.RemoveFile(id, XferFactory.FileType.Job, directory); //Remove job from xfer files JArray xfers = DataFactory.GetXfers(directory); JArray keptJobs = new JArray(); foreach (JObject x in xfers) { string xferID = x.GetValue("id").ToString(); JArray xJobs = (JArray)x.GetValue("jobs"); foreach (string j in xJobs) { if (j != id) { keptJobs.Add(j); } } x["count"] = keptJobs.Count(); x["jobs"] = keptJobs; //Rebuild the Xfer file using the meta data JObject newXfer = DataFactory.RebuildXfer(x, directory); FileFactory.WriteFile(newXfer, xferID.ToString(), XferFactory.FileType.Xfer, directory); //Meta file for when we want to list Xfer files but not load all the data FileFactory.WriteFile(x, xferID.ToString(), XferFactory.FileType.XferMeta, directory); } return(RedirectToAction("Index")); }
private void button1_Click(object sender, EventArgs e) { Task executing = new Task(() => { string root = "E:\\Judge\\"; FileFactory factory = new FileFactory("E:\\Judge\\"); string code = textBox1.Text; string language = comboBox1.Text; Submit submit = new Submit(code, language); Problem sum = new Problem(); sum.Tests = new List <TestCase> { new TestCase("5 5", "10"), new TestCase("3 9", "12"), new TestCase("3 6", "9"), new TestCase("5 5", "10"), new TestCase("3 9", "12"), new TestCase("3 6", "9") }; IChecker checker = new StringChecker(); Judger judger = new Judger(factory, checker); judger.Judge(submit, new ExecutingOptions(5, 1000)); string current = ""; this.textBox2.Text = ""; foreach (var result in judger.Assessment(judger.BuildedFileName + ".exe", sum)) { current = String.Format("\nStatus:{0} Memory:{1} Execution Time:{2}", result.Verdict, result.Memory.ToString(), result.Time.ToString()); // this.textBox2.Text = textBox2.Text + current; } }); executing.Start(); }
private void Delete(string directory, GLib.File dir, bool recursive) { if (!dir.Exists) { return; } if (dir.QueryFileType(FileQueryInfoFlags.NofollowSymlinks, null) != FileType.Directory) { return; } // If native, use the System.IO recursive delete if (dir.IsNative && !DisableNativeOptimizations) { System.IO.Directory.Delete(directory, recursive); return; } if (recursive) { foreach (string child in GetFiles(dir, false)) { FileFactory.NewForUri(child).Delete(); } foreach (string child in GetDirectories(dir, false)) { Delete(child, GetDir(child, true), true); } } dir.Delete(); }
public void CanReadDataAtTheEndOfFile() { byte[] buffer = new byte[20]; ManualResetEvent completed = new ManualResetEvent(false); using (CompletionThread worker = new CompletionThread()) { string path = Path.Combine(sandbox.Directory, "abc.txt"); FileFactory factory = new FileFactory(worker); using (FileStream stream = System.IO.File.Create(path)) { stream.Write(new byte[10], 0, 10); stream.Flush(true); worker.Start(); } using (File file = factory.OpenOrCreate(path)) { file.Read(10, buffer, data => { Assert.That(data.Count, Is.EqualTo(0)); completed.Set(); }); Assert.That(completed.WaitOne(TimeSpan.FromSeconds(5)), Is.True); } } }
public void CanWriteData() { byte[] buffer = new byte[20]; ManualResetEvent completed = new ManualResetEvent(false); using (CompletionThread worker = new CompletionThread()) { string path = Path.Combine(sandbox.Directory, "abc.txt"); FileFactory factory = new FileFactory(worker); worker.Start(); using (File file = factory.OpenOrCreate(path)) { file.Write(0, buffer, data => { completed.Set(); }); } using (FileStream stream = System.IO.File.OpenRead(path)) { stream.Read(new byte[10], 0, 10); } } Assert.That(completed.WaitOne(TimeSpan.FromSeconds(5)), Is.True); }
void PixbufDataFunc(TreeViewColumn tree_column, CellRenderer cell, TreeModel tree_model, TreeIter iter) { var renderer = cell as CellRendererPixbuf; string stock; var uri = folder_tree_model.GetUriByIter(iter); if (uri == null) { return; } var file = FileFactory.NewForUri(uri); try { var info = file.QueryInfo("standard::icon", FileQueryInfoFlags.None, null); if (info.Icon is ThemedIcon themed_icon && themed_icon.Names.Length > 0) { stock = themed_icon.Names[0]; } else { stock = "gtk-directory"; } } catch (Exception) {
public void PlayStream(string url) { DockServices.System.RunOnThread(() => { try { WebClient cl = new WebClient(); cl.Headers.Add("user-agent", DockServices.System.UserAgent); if (DockServices.System.UseProxy) { cl.Proxy = DockServices.System.Proxy; } string tempPath = System.IO.Path.GetTempPath(); string filename = url.Split(new [] { '/' }).Last(); filename = System.IO.Path.Combine(tempPath, filename); GLib.File file = FileFactory.NewForPath(filename); if (file.Exists) { file.Delete(); } cl.DownloadFile(url, file.Path); DockServices.System.Open(file); } catch (Exception e) { Docky.Services.Log <Station> .Error("Failed to play streaming url ({0}) : {1}", url, e.Message); Docky.Services.Log <Station> .Debug(e.StackTrace); // also notify the user that we couldn't play this stream for some reason. Docky.Services.Log.Notify(Name, Icon, "The streaming link failed to play. " + "This is most likely a problem with the NPR station."); } }); }
protected override AbstractDockItem OnAcceptDrop(string uri) { File tempFile = FileFactory.NewForPath(System.IO.Path.GetTempFileName()); FileDockItem bookmark = FileDockItem.NewFromUri(uri); // make sure the bookmarked location actually exists if (!bookmark.OwnedFile.Exists) { return(null); } using (DataInputStream reader = new DataInputStream(BookmarksFile.Read(null))) { using (DataOutputStream writer = new DataOutputStream(tempFile.AppendTo(FileCreateFlags.None, null))) { string line; ulong length; while ((line = reader.ReadLine(out length, null)) != null) { writer.PutString(string.Format("{0}{1}", line, reader.NewLineString()), null); } writer.PutString(string.Format("{0}{1}", bookmark.Uri, reader.NewLineString()), null); } } items.Add(bookmark); Items = InnerItems; if (tempFile.Exists) { tempFile.Move(BookmarksFile, FileCopyFlags.Overwrite, null, null); } return(bookmark); }
public void test() { LoggerFactory factory = new FileFactory(); //可引入配置文件实现 Logger logger = factory.createLogger(); logger.writeLog(); }
private static ILogger CreateLogger() { ICollection <IAppender> appenders = new List <IAppender>(); LayoutFactory layoutFactory = new LayoutFactory(); FileFactory fileFactory = new FileFactory(); AppenderFactory appenderFactory = new AppenderFactory(layoutFactory, fileFactory); int appendersCount = int.Parse(Console.ReadLine()); for (int i = 0; i < appendersCount; i++) { string[] args = Console.ReadLine().Split(); string appenderType = args[0]; string layoutType = args[1]; string level = ""; if (args.Length == 3) { level = args[2]; } IAppender appender = appenderFactory.Create(appenderType, layoutType, level); appenders.Add(appender); } ILogger logger = new Logger(appenders); return(logger); }
public ulong GetMTime(SafeUri uri) { var file = FileFactory.NewForUri(uri); var info = file.QueryInfo("time::modified", FileQueryInfoFlags.None, null); return(info.GetAttributeULong("time::modified")); }
static void Main(string[] args) { Console.Write("NumberParser :"); var input = Console.ReadLine(); try { string fileType = input.Substring(input.LastIndexOf(',') + 1); var fileDataRaw = input.Substring(0, input.LastIndexOf(",")); int[] fileData = FileFactory.sortArry(fileDataRaw); IFile fileInstance = FileFactory.GetFileCreatorClass(fileType.ToLower(), fileData); if (fileInstance != null) { fileInstance.FileCreator(); Console.WriteLine("Operation Completed Successfully"); } else { Console.WriteLine("File Type Not found"); } } catch (Exception ex) { Console.WriteLine("Exception Occured while processing your request.{0}" + Environment.NewLine, ex.Message); Console.Read(); } }
Pixbuf IconFromFile(string name, int width, int height) { Pixbuf pixbuf; string home = Environment.GetFolderPath(Environment.SpecialFolder.Personal); name = name.Replace("~", home); GLib.File iconFile = (name.StartsWith("/")) ? FileFactory.NewForPath(name) : FileFactory.NewForUri(name); try { if (width <= 0 || height <= 0) { pixbuf = new Pixbuf(iconFile.Path); } else { pixbuf = new Pixbuf(iconFile.Path, width, height, true); } } catch (Exception e) { Log <DrawingService> .Warn("Error loading icon from file '" + iconFile.Path + "': " + e.Message); Log <DrawingService> .Debug(e.StackTrace); pixbuf = null; } return(pixbuf); }
public static T?ReadFileData <T>(this Context context, string fileName, IStreamEncoder?encoder = null, Endian?endian = null, Action <T>?onPreSerialize = null, bool removeFileWhenComplete = true) where T : BinarySerializable, new() { PhysicalFile file = encoder == null ? new LinearFile(context, fileName, endian) : new EncodedLinearFile(context, fileName, encoder, endian); if (!File.Exists(file.SourcePath)) { return(null); } context.AddFile(file); try { return(FileFactory.Read <T>(context, fileName, (_, o) => onPreSerialize?.Invoke(o))); } finally { if (removeFileWhenComplete) { context.RemoveFile(file); } } }
public void FromFileNotSupported() { var file = FileFactory.File("11.txt"); Assert.IsFalse(_sut.IsSupported(file.Name)); Assert.Throws <NotSupportedException>(() => _sut.FromFile(file)); }
public static Gnome.Vfs.Uri UniqueName(Gnome.Vfs.Uri path, string shortname) #endif { int i = 1; #if GIO_2_16 GLib.File dest = FileFactory.NewForUri(new System.Uri(path, shortname)); #else Gnome.Vfs.Uri target = path.Clone(); Gnome.Vfs.Uri dest = target.AppendFileName(shortname); #endif while (dest.Exists) { string numbered_name = System.String.Format("{0}-{1}{2}", System.IO.Path.GetFileNameWithoutExtension(shortname), i++, System.IO.Path.GetExtension(shortname)); #if GIO_2_16 dest = FileFactory.NewForUri(new System.Uri(path, numbered_name)); #else dest = target.AppendFileName(numbered_name); #endif } return(dest); }
public void SetUp() { fileFactory = new FileFactory(1); decipher = new RsaFileDecipher(fileFactory); DeleteTestFolder(); Directory.CreateDirectory(testFolder); }
public IActionResult RunXfer(string id, bool dryRun, string sessionID) { string xferDir = FileFactory.ValidateDirectory(directory, XferFactory.FileType.Xfer); XferCore.Core XferCore = new XferCore.Core(); XferCore.SessionID = Guid.Parse(sessionID); XferCore.LogEvent += Core_LogEvent; try { XferCore.ProcessXfer(id, xferDir, dryRun); } catch (Exception ex) { return(Json(new { success = false, msg = ex.Message })); } string result = readLog(sessionID); //Remove the temp log file deleteLog(sessionID); return(Json(new { success = true, log = result })); }
public override void SetFile(string fileName) { var file = FileFactory.GetFile(fileName); if (file == null) { throw new TFUnknownFileTypeException("No se reconoce el tipo del fichero"); } var dbFile = new DbFile { Path = fileName, Hash = Utils.CalculateHash(fileName), Content = File.ReadAllBytes(fileName) }; _repository.InsertFile(dbFile); file.Id = dbFile.Id; using (var ms = new MemoryStream(dbFile.Content)) { file.Read(ms); } if (file.Strings.Count(x => x.Visible) > 0) { Files.Add(file); } else { _repository.DeleteFile(file.Id); } }
void Save(bool export) { this.saveFileDialog1.AddExtension = true; FileFactory ff = new FileFactory(this.mouseMarkerControl1); if (export) { this.saveFileDialog1.Filter = ff.GetExportFilter(); } else { this.saveFileDialog1.Filter = ff.GetSaveFilter(this.mouseMarkerControl1.ChartDataList); } if (DialogResult.OK == this.saveFileDialog1.ShowDialog(this)) { IChartFile icf = ff.GetChartFile(this.saveFileDialog1.FilterIndex); if (icf != null) { using (Stream s = File.Open(this.saveFileDialog1.FileName, FileMode.Create, FileAccess.ReadWrite)) { icf.Save(s, this.mouseMarkerControl1.ChartDataList); } } } }
public void Execute(string dbname, string namespaceName, string path, MySqlDatabase <information_schema> information_schema) { var database = MetadataFromSqlFactory.ParseDatabase(dbname, information_schema.Query()); Console.WriteLine($"Database: {dbname}"); Console.WriteLine($"Table count: {database.Tables.Count}"); Console.WriteLine($"Writing models to: {path}"); var settings = new FileFactorySettings { NamespaceName = namespaceName, UseRecords = true, UseCache = true }; foreach (var file in FileFactory.CreateModelFiles(database, settings)) { var filepath = $"{path}{Path.DirectorySeparatorChar}{file.path}"; Console.WriteLine($"Writing {filepath}"); if (!File.Exists(filepath)) { Directory.CreateDirectory(Path.GetDirectoryName(filepath)); } File.WriteAllText(filepath, file.contents, Encoding.GetEncoding("iso-8859-1")); } }
//private IEnumerable<PropertyDefinition> GetDefinitions(ICustomTypeDescriptor descriptor) { // foreach (PropertyDescriptor prop in descriptor.GetProperties()) { // var def = new PropertyDefinition(); // prop.GetValue(descriptor) // } //} private void Button_Click(object sender, RoutedEventArgs e) { #if DEBUG //rpg.PropertyDefinitions.Clear(); #endif if (index % 2 == 0) { var item = FileRowFactory.Current.CreateFileRow(FileFactory.CreateRegularFile(string.Empty)); _vm.Item = item; } else { var item = new CustomTypeDescriptorWrapper(); for (int i = 0; i < 40; i++) { item.CompositeCustomMemberDecriptor(new SingularityForensic.Ext.ExtGroupDesc(new SingularityForensic.Ext.StExtGroupDesc()) { #if DEBUG InternalDisplayName = i.ToString() #endif }); } _vm.Item = item; } index++; }
public void Add(Uri uri) { if (App.Instance.Container.Resolve <IImageFileFactory> ().HasLoader(uri)) { //Console.WriteLine ("using image loader {0}", uri.ToString ()); Add(new FilePhoto(uri)); } else { var info = FileFactory.NewForUri(uri).QueryInfo("standard::type,standard::content-type", FileQueryInfoFlags.None, null); if (info.FileType == FileType.Directory) { new DirectoryLoader(this, uri); } else { // FIXME ugh... if (info.ContentType == "text/xml" || info.ContentType == "application/xml" || info.ContentType == "application/rss+xml" || info.ContentType == "text/plain") { new RssLoader(this, uri); } } } }
public IActionResult Remove(string id) { FileFactory.RemoveFile(id, XferFactory.FileType.Xfer, directory); FileFactory.RemoveFile(id, XferFactory.FileType.XferMeta, directory); return(RedirectToAction("Index")); }
public static GeneratedModel Create(CodeGenerationOptions options) { GeneratedModel model = new GeneratedModel(); foreach (var kind in options.Kinds) { //if (kind == Kind.Context || kind == Kind.Supervisor) // continue; GeneratedFile modelClassFile = FileFactory.Create(options, FileType.ModelClass, kind); GeneratedFile generatorInterfaceFile = FileFactory.Create(options, FileType.GeneratorInterface, kind); GeneratedFile generatorClassFile = FileFactory.Create(options, FileType.GeneratorClass, kind); GeneratedFile scaffolderInterfaceFile = FileFactory.Create(options, FileType.ScaffolderInterface, kind); GeneratedFile scaffolderClassFile = FileFactory.Create(options, FileType.ScaffolderClass, kind); model.Models.Add(modelClassFile); model.GeneratorInterfaces.Add(generatorInterfaceFile); model.GeneratorClasses.Add(generatorClassFile); model.ScaffolderInterfaces.Add(scaffolderInterfaceFile); model.ScaffolderClasses.Add(scaffolderClassFile); } model.ScaffoldedModelClass = FileFactory.Create(options, FileType.ScaffoldedModelClass); model.ServicesClassFile = FileFactory.Create(options, FileType.ServicesClass); //model.SupervisorClass = FileFactory.Create(options, FileType.SupervisorClass); //model.SupervisorModelClass = FileFactory.Create(options, FileType.SupervisorModelClass); //model.SupervisorInterface = FileFactory.Create(options, FileType.SupervisorInterface); //model.ContextClass = FileFactory.Create(options, FileType.ContextClass); //model.ContextInterface = FileFactory.Create(options, FileType.ContextInterface); //model.ContextModelClass = FileFactory.Create(options, FileType.ContextModelClass); return(model); }
public void DirectoryDeleteTest() { IEntry entry = FileFactory.CreateEntry(@"C:\ForFileManager\ToDeleteByFile1.txt"); MyDirectory.Delete(entry.FullName); Assert.IsFalse(MyDirectory.Exists(@"C:\ForFileManager\ToDeleteByFile1.txt")); }
public SmartphoneOutputStream(FileFactory fileFactory, string fileName) { var guid = Guid.NewGuid().ToString(); file = fileFactory.Create(fileName); fileTemp1 = fileFactory.Create(string.Format(TEMP_NAME, fileName, 1, guid)); fileTemp2 = fileFactory.Create(string.Format(TEMP_NAME, fileName, 2, guid)); fileTemp3 = fileFactory.Create(string.Format(TEMP_NAME, fileName, 3, guid)); Stream = fileTemp1.GetWritingStream(); }
public void TestInitialize() { fileFactory = Substitute.For<FileFactory>(); foo = Substitute.For<File>(); fileFactory.Create("foo").Returns(foo); fooTemp1 = Substitute.For<File>(); fileFactory.Create(Arg.Is<string>(arg => arg.StartsWith("foo_temp1_"))).Returns(fooTemp1); fooTemp2 = Substitute.For<File>(); fileFactory.Create(Arg.Is<string>(arg => arg.StartsWith("foo_temp2_"))).Returns(fooTemp2); fooTemp3 = Substitute.For<File>(); fileFactory.Create(Arg.Is<string>(arg => arg.StartsWith("foo_temp3_"))).Returns(fooTemp3); fooTemp1WritingStream = Substitute.For<System.IO.Stream>(); fooTemp1.GetWritingStream().Returns(fooTemp1WritingStream); fooTemp1ReadingStream = Substitute.For<System.IO.Stream>(); fooTemp1.GetReadingStream().Returns(fooTemp1ReadingStream); foo.Exists.Returns(true); fooTemp1ReadingStream.Length.Returns(1000); sut = new SmartphoneOutputStream(fileFactory, "foo"); }
/// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter FileFactory f = new FileFactory(); new Factories.CommentFactory().LoadAllComments(); rootFrame.Navigate(typeof(MainView), e.Arguments); } // Ensure the current window is active Window.Current.Activate(); }
public PhoneBinaryStreamProvider(FileFactory fileFactory) : base(fileFactory) { }
public CommentFactory() { brojac = 0; _factory = new FileFactory(); }
public NewsFactory() { _factory = new FileFactory(); }
public DroidBinaryStreamProvider(FileFactory fileFactory, Context context) : base(fileFactory) { this.context = context; }
public SmartphoneBinaryStreamProvider(FileFactory fileFactory) { this.fileFactory = fileFactory; }