public DynamicDataFile(DocumentFile activeDocument, DataFile dataFile, Site site) : base(dataFile, dataFile.Metadata) { this.ActiveDocument = activeDocument; this.DataFile = dataFile; this.Site = site; }
public FileNode(DataFile file, int iconIndex) { eX4XcIhHpDXt70u2x3N.k8isAcYzkUOGF(); // ISSUE: explicit constructor call base.\u002Ector(file.Name, iconIndex, iconIndex); this.Ao6uVnnZSa = file; }
public ReindexForm(DataFile file, FileSeries series) { eX4XcIhHpDXt70u2x3N.k8isAcYzkUOGF(); // ISSUE: explicit constructor call base.\u002Ector(); this.RwqhYw1ax(); this.eNxl3I1Gv = file; this.imLuYujEd = series; if (series == null) this.mmigbHbRS.Text = RNaihRhYEl0wUmAftnB.aYu7exFQKN(0); else this.mmigbHbRS.Text = series.Name; this.EErRQuytI.Items.Add((object) new UCyttABvG4oj9bO5jJ(SmartQuant.File.Indexing.Indexer.None)); this.EErRQuytI.Items.Add((object) new UCyttABvG4oj9bO5jJ(SmartQuant.File.Indexing.Indexer.Daily)); this.EErRQuytI.Items.Add((object) new UCyttABvG4oj9bO5jJ(SmartQuant.File.Indexing.Indexer.Monthly)); if (series == null) { this.EErRQuytI.SelectedIndex = 0; } else { bool flag = false; for (int index = 0; index < this.EErRQuytI.Items.Count; ++index) { if ((this.EErRQuytI.Items[index] as UCyttABvG4oj9bO5jJ).Indexer == series.Indexer) { this.EErRQuytI.SelectedIndex = index; flag = true; break; } } if (!flag) throw new ArgumentException(RNaihRhYEl0wUmAftnB.aYu7exFQKN(24) + series.Name, RNaihRhYEl0wUmAftnB.aYu7exFQKN(82)); } }
private static Database CreateDb(Server server, string databaseName, string directory) { Database db = new Database(server, databaseName); db.DatabaseOptions.AutoClose = true; db.DatabaseOptions.AutoShrink = true; db.DatabaseOptions.UserAccess = DatabaseUserAccess.Multiple; FileGroup fileGroup = new FileGroup(db, "PRIMARY"); db.FileGroups.Add(fileGroup); DataFile dataFile = new DataFile(fileGroup, databaseName + "_Data"); fileGroup.Files.Add(dataFile); dataFile.FileName = Path.Combine(Path.GetFullPath(directory), databaseName + ".mdf"); dataFile.Size = 5.0 * 1024.0; dataFile.Growth = 10.0; dataFile.GrowthType = FileGrowthType.Percent; LogFile logFile = new LogFile(db, databaseName + "_Log"); db.LogFiles.Add(logFile); logFile.FileName = Path.Combine(Path.GetFullPath(directory), databaseName + ".ldf"); logFile.Size = 2.5 * 1024.0; logFile.GrowthType = FileGrowthType.Percent; logFile.Growth = 10.0; db.Create(false); return db; }
private void LoadWorld() { foreach(string characterfile in Directory.GetFiles("GameData/Worlds/"+WorldID.ToString()+"/Actors/Dynamic","*",SearchOption.AllDirectories)) { DataFile CharacterData = new DataFile(characterfile); throw new Exception(CharacterData.GetString("name")); //Load Persistant Actors } }
public void GenerateConfig() { if(!Directory.Exists("GameData")) Directory.CreateDirectory("GameData"); File.Create("GameData\\server.config.txt"); DataFile temp = new DataFile("GameData\\server.config.txt"); temp.Add("maxplayers", 5); temp.SaveData(); }
public RegisteredTypesForm(DataFile file) { eX4XcIhHpDXt70u2x3N.k8isAcYzkUOGF(); // ISSUE: explicit constructor call base.\u002Ector(); this.ToBHFtQWwi(); this.pwWHaRsjYg = file; this.ATvHbY9WDd(View.Details); this.F4xHlmYhTc(); }
public DefragmentForm(DataFile file) { eX4XcIhHpDXt70u2x3N.k8isAcYzkUOGF(); // ISSUE: explicit constructor call base.\u002Ector(); this.qr0xlIbQ1m(); this.yEyxyJy3ij = file; this.moexa7EZ2t = file.Series.Count; this.jA5xrJtsOJ.Value = (Decimal) file.DefaultZipLevel; this.WrxxqhtuDd.Value = (Decimal) file.DefaultBlockSize; }
private void saveToolStripMenuItem_Click(object sender, EventArgs e) { SaveRefSettings(); try { DataFile.Resave(c0000); MessageBox.Show("Save successful"); } catch (Exception ex) { MessageBox.Show("Error saving file.\n\n" + ex.ToString()); } }
static public bool Run(string title, DataFile file) { using var form = new DataFileEditorForm { Text = title }; AddTab(form.TabControl, file); bool result = form.ShowDialog() == DialogResult.OK; if (result) { file.ReLoad(); } return(result); }
public ListManagement(DataFile dataFile) { this.dataFile = dataFile; InitializeComponent(); if (!string.IsNullOrEmpty(this.dataFile.Participants.Name)) { this.txtNameList.Text = this.dataFile.Participants.Name; } this.lstParticipants.ItemsSource = this.dataFile.Participants; }
public void TestOnlyHeaderFilesProcessing(string fileName) { string testFolder = GetTestDataFolder(); IFileProcessor fileProcessor = new FileProcessor(); FileTypes fileTypes = FileTypes.GetFileTypes(); DataFile testFile = fileProcessor.FetchAllDataFiles(fileTypes, testFolder) .Find(x => x.FileName.Contains(fileName)); double divergencePercentage = 20; FileProcessStatus fileProcessStatus = fileProcessor.ProcessInputFile(testFile, fileTypes, testFolder, divergencePercentage); Assert.AreEqual(FileProcessStatus.FileOnlyHeaderFound, fileProcessStatus); }
private void TestInitializedFileWithData(DataFile file) { Assert.NotNull(file); Assert.NotNull(file._fileInfo); Assert.NotNull(file._fileType); Assert.NotNull(file.Data); //Assert.True(TestName == file.Name); }
public ClockVMCollection(DataFile df) { MyDataFile = df; SelectedClocks = new ObservableCollection <ClockVM>(); AlarmsTimer = new DispatcherTimer(DispatcherPriority.Send) { Interval = TimeSpan.FromSeconds(0.5) }; AlarmsTimer.Tick += AlarmsTimer_Tick; }
// ReSharper disable once CSharpWarnings::CS1998 public static async Task LoadUniverse(string flPath) { var flFile = new DataFile(Path.Combine(flPath, @"EXE\Freelancer.ini")); var flDataPath = Path.Combine(flPath, @"EXE", flFile.GetSetting("Freelancer", "data path")[0]); Parallel.ForEach(flFile.GetSettings("Data", "goods"), gentry => BaseDB.LoadGoods( new DataFile( flDataPath + Path.DirectorySeparatorChar + gentry[0] ) )); Logger.Info("Loaded {0} goods", BaseDB.UniGoods.Count); foreach (var uset in flFile.GetSettings("Data", "universe")) { var uniFile = new DataFile(flDataPath + Path.DirectorySeparatorChar + uset[0]); //TODO: load loadout //TODO: load factions //TODO: load system //load bases BaseDB.LoadBases(uniFile.GetSections("Base"), flDataPath); Logger.Info("Loaded {0} bases", BaseDB.BaseCount); BaseDB.LoadNews(new DataFile(flDataPath + Path.DirectorySeparatorChar + @"missions" + Path.DirectorySeparatorChar + @"news.ini")); Logger.Info("Loaded news"); BaseDB.LoadMBase(new DataFile(flDataPath + @"\missions\mbases.ini")); Logger.Info("Loaded mbase"); BaseDB.LoadGenericScripts(new DataFile(flDataPath + @"\scripts\gcs\genericscripts.ini")); Logger.Info("Loaded generic scripts"); //load goods //load markets Parallel.ForEach(uniFile.GetSettings("Data", "markets"), mentry => BaseDB.LoadBaseMarketData( new DataFile( flDataPath + Path.DirectorySeparatorChar + mentry[0] ) )); Logger.Info("Loaded markets"); } //TODO: check all the links }
public void SaveUpdate(DataFile rec) { if (rec.Id != Guid.Empty) { WriteLog(VMGlobal.LOG_ACTION.UPDATE, string.Format("{0}{1}", rec.StoredFileName, rec.FileExtension), rec.AccountId); context.Entry(rec).State = EntityState.Modified; return; } object[] storedFileName = new object[] { rec.StoredFileName, rec.FileExtension, rec.OriginalFileName, rec.SourcePath }; WriteLog(VMGlobal.LOG_ACTION.UPLOAD, string.Format("{0}{1}\n{2}\n{3}", storedFileName), rec.AccountId); context.DataFiles.Add(rec); }
internal DataFile GetOrAddFile(string name) { var data = _dic.Files.FirstOrDefault(df => df.Name == name); if (data == null) { data = new DataFile(name); _dic.Files.Add(data); } return(data); }
public FileViewItem(DataFile file, int iconIndex) { eX4XcIhHpDXt70u2x3N.k8isAcYzkUOGF(); // ISSUE: explicit constructor call base.\u002Ector(file.Name, iconIndex); this.a1td0l5P0x = file; this.SubItems.Add(file.Description); this.SubItems.Add(this.YlBdwdd96R((long) file.Series.Count)); this.SubItems.Add(this.YlBdwdd96R(file.DataFileSize)); this.SubItems.Add(this.YlBdwdd96R(file.HeaderFileSize)); this.SubItems.Add(this.YlBdwdd96R(file.IndexFileSize)); }
private static void Main(string[] args) { XTrace.UseConsole(true, true); XTrace.WriteLine("浏览器操作"); int p = XmlConfig <SeleniumConfig> .Current.PiHao; //string ph = DataFile.WtingRead("请输入配置文件 ", "输入的配置路径:", (string path) => (path.IndexOf(".config") == -1 ? false : XmlConfig<SeleniumConfig>.Current.Load(path))); string ph = @"Config\Selenium.config"; XTrace.WriteLine($"加载的配置地址:" + ph); XmlConfig <SeleniumConfig> .Current.Load(ph); XmlConfig <SeleniumConfig> .Current.ConfigFile = ph; XmlConfig <SeleniumConfig> .Current.Load(ph); XmlConfig <SeleniumConfig> .Current.ConfigFile = ph; XmlConfig <SeleniumConfig> .Current.Load(ph); TaskTool.AddHyDataConneStr(XmlConfig <SeleniumConfig> .Current.HyAccountDb); TaskTool.AddJiQiMaConnStr(XmlConfig <SeleniumConfig> .Current.JiQiMaDb); Program.ClearProcess(); Program.SetConsoleCtrlHandler(Program.cancelHandler, true); ModifyHead.LoadPicFileInfo(XmlConfig <SeleniumConfig> .Current.TouXiang); switch (DataFile.WtingReadInt("任务类型 0=刷活跃 1=快速注册 2=文本账号保存到数据库", "输入的任务类型:")) { case 0: { AutoHuoYueCaoZuo huoyue = new AutoHuoYueCaoZuo(); Program.AutoCaoZuo = huoyue; huoyue.Start(); break; } case 1: { int needCount = DataFile.WtingReadInt("需要注册的数量:", "输入的注册数量:"); AutoQuickReg reg = new AutoQuickReg(); Program.AutoCaoZuo = reg; reg.Start(needCount); break; } case 2: { AutoLoginTask Login = new AutoLoginTask(); Program.AutoCaoZuo = Login; Login.Start(); break; } } DataFile.WatingOut(); }
/// <summary> /// Create or replace a device model script. /// </summary> public async Task <DataFile> UpsertAsync(DataFile deviceModelScript) { var id = deviceModelScript.Id; var eTag = deviceModelScript.ETag; try { var item = await this.GetAsync(id); if (item.ETag == eTag) { // Replace a custom device model script deviceModelScript.Created = item.Created; deviceModelScript.Modified = DateTimeOffset.UtcNow; this.log.Debug("Modifying a custom device model script.", () => new { deviceModelScript }); var result = await this.storage.UpdateAsync( STORAGE_COLLECTION, id, JsonConvert.SerializeObject(deviceModelScript), eTag); // Return the new ETag provided by the storage deviceModelScript.ETag = result.ETag; } else { this.log.Error("Invalid ETag.", () => new { CurrentETag = item.ETag, ETagProvided = eTag }); throw new ConflictingResourceException("Invalid ETag. Device model script ETag is:'" + item.ETag + "'."); } } catch (ConflictingResourceException) { throw; } catch (ResourceNotFoundException) { this.log.Info("Creating a new device model script via PUT", () => new { deviceModelScript }); var result = await this.InsertAsync(deviceModelScript); deviceModelScript.ETag = result.ETag; } catch (Exception exception) { this.log.Error("Something went wrong while upserting the device model script.", () => new { deviceModelScript }); throw new ExternalDependencyException("Failed to upsert: " + exception.Message, exception); } return(deviceModelScript); }
public string[] ValidateInputFile(DataFile dataFile, FileTypes fileTypes, ref FileType fileType, string folderPath, ref FileProcessStatus validationStatus) { try { log.Debug("Start ValidateInputFile()"); //Check Blank files if (new FileInfo(folderPath + dataFile.FileName).Length == 0) { log.Warn(dataFile.FileName + " is blank, nothing to read! "); validationStatus = FileProcessStatus.BlankFileDetected; return(Array.Empty <string>()); } else { string[] csvLines = File.ReadAllLines(folderPath + dataFile.FileName); string[] headers = csvLines[0].Split(','); //Get the Column Names for the files and check if they contain the required column names, and check the indexes fileType = fileTypes.FileType.FirstOrDefault(x => x.Identifier == dataFile.FileType); foreach (Items item in fileType.Items) { item.Index = null; for (int i = 0; i < headers.Count(); i++) { if (headers[i] == item.FileHeaderName) { item.Index = i; break; } } if (item.Index == null) { log.Error("Column " + item.FileHeaderName + " is missing in file: " + dataFile.FileName); validationStatus = FileProcessStatus.FileHeadersNotFound; return(Array.Empty <string>()); } } validationStatus = FileProcessStatus.FileValidationSucceeded; return(csvLines); } } catch (Exception) { throw; } }
public void TestToString() { const string expected = "Hello World"; var data = System.Text.Encoding.ASCII.GetBytes(expected); var df = DataFile.From(data); Assert.Equal(expected, df.ToString()); var reader = df.AsStringReader(); Assert.Equal(expected, reader.ReadToEnd()); }
public void ItThrowsExternalDependencyExceptionWhenFailedFetchingDeviceModelScriptInStorage() { // Arrange var deviceModelScript = new DataFile { Id = "id", ETag = "Etag" }; // Act var ex = Record.Exception(() => this.target.UpsertAsync(deviceModelScript).Result); // Assert Assert.IsType <ExternalDependencyException>(ex.InnerException); }
public void CanAddFile() { Repositories.Files.Add(CreateDataFile("name", StatusHelper.Processing)); Repositories.SaveChanges(); IList <DataFile> result = Repositories.Files.FindAll(); Assert.AreEqual(1, result.Count); DataFile actual = result.ElementAt(0); Assert.AreEqual("name", actual.Name); Assert.AreNotEqual(0, actual.Id); }
private void AddDataFile(DataFile dataFile) { this.lstCategory.DataSource = null; if (this.dataFiles.Any(f => f.Key == dataFile.Key)) { this.dataFiles.Remove(this.dataFiles.First(f => f.Key == dataFile.Key)); } this.dataFiles.Add(dataFile); this.lstCategory.DataSource = this.dataFiles; this.lstCategory.ValueMember = "Key"; this.lstCategory.DisplayMember = "DisplayName"; this.lstCategory.SelectedItem = dataFile; }
public void CreateFileMultiPlatform() { string path = new EasyPath().GetPlatformPath(); UserFileHandler handler = new UserFileHandler(); DataFile dataFile = handler.CreateFile(path); if (!File.Exists(path)) { Assert.Fail("File was not created"); } Assert.IsNotNull(dataFile.Stream); }
private static void ProcessFile(DataFile proc, string f) { var xtw = new XmlTextWriter(Stream.Null, Encoding.UTF8); try { proc.Process(f, xtw); } finally { xtw.Close(); } }
public DataFileViewModel(FileInfo file, DataFile processingFile) { Name = file.Name; if (processingFile != null) { Status = processingFile.Status; ProcessingFile = processingFile; } else { Status = (int)StatusHelper.NeverProcessed; } }
public void TestExistingFile() { var data = Properties.Resources.simple_layout; var path = Path.Combine(_mTempdir, "test.file"); File.WriteAllBytes(path, data); var df = DataFile.From(path); Assert.False(df.Empty); Assert.Equal(df.Size, data.Length); Assert.Equal(data, df.Data); }
public DataFile Decompress(DataFile file) { DataFile res; _fileLength = file.Length; var huffmanDecoder = new HuffmanDecoder(file.GetAllBytes()); _coder = huffmanDecoder; res = new DataFile(huffmanDecoder.Decode()); _coder = null; return(res); }
public bool VerifFile(string fileName) { DataFile tmpDataFile = this.ReadFile(fileName); if (tmpDataFile == null) { this._technicalLogger.LogError("Load File", string.Format("The File [{0}] is not a valid FI Station", fileName)); return(false); } this._technicalLogger.LogInfo("Load File", string.Format("The File [{0}] is loaded successfully", fileName)); return(true); }
private string CreateQueryString(DataFile file) { if (file.NameApplication.NumberApplication == null) { return(@"INSERT INTO [_Application] (_workID, _ApplicationTypeID, fileName, body, mimeTypeID, modified) VALUES ('{0}',(SELECT [objID] FROM [_ApplicationType] WHERE code = '{1}'), '{2}', CONVERT(varbinary(max), '{3}'), '{4}', GETDATE())"); } else { return(@"INSERT INTO [_Application] (_workID, _ApplicationTypeID, number, fileName, body, mimeTypeID, modified) VALUES ('{0}',(SELECT [objID] FROM [_ApplicationType] WHERE code = '{1}'), '" + file.NameApplication.NumberApplication + "', '{2}', CONVERT(varbinary(max), '{3}'), '{4}', GETDATE())"); } }
//public List<FlverVertexStructLayout> DEBUG_LIST_VertexStructLayout { get; set; } = new List<FlverVertexStructLayout>(); //public List<FlverMaterial> DEBUG_LIST_Materials { get; set; } = new List<FlverMaterial>(); //public List<FlverVertexGroup> DEBUG_LIST_VertexGroups { get; set; } = new List<FlverVertexGroup>(); //public List<FlverFaceSet> DEBUG_LIST_FaceSets { get; set; } = new List<FlverFaceSet>(); public static FLVEROptimized ReadFromBnd(string bndPath, int modelIndex) { var bnd = DataFile.LoadFromFile <BND>(bndPath); foreach (var entry in bnd) { if (entry.ID == EntityBND.ID_FLVER_START + modelIndex) { return(entry.ReadDataAs <FLVEROptimized>()); } } return(null); }
public void SlideAtEndWhenAtEnd() { var path = TestContext.CurrentContext.TestDirectory + "../../../res/testfile1"; var file = new DataFile(path); var sw = new SlidingWindow(file.GetAllBytes()); for (var i = 0; i < 3; i++) { sw.Slide(); } Assert.IsTrue(sw.AtEnd()); }
public void Add(DataFile data) { using (new Timing("Adding Textures (data)")) { foreach (var txd in data.TXDs) { Add(txd); } foreach (var img in data.IMGs) { Add(img); } } }
/// <summary> /// Gets information about the xml (WaterML) file /// </summary> /// <param name="xmlFileName"></param> /// <returns></returns> private DataFile GetDataFileInfo(string xmlFileName) { //create a 'data file' object DataFile xmlFileInfo = new DataFile(); xmlFileInfo.FileDescription = "WaterML File"; xmlFileInfo.FileName = System.IO.Path.GetFileName(xmlFileName); xmlFileInfo.FilePath = System.IO.Path.GetDirectoryName(xmlFileName); xmlFileInfo.FileType = "xml"; xmlFileInfo.LoadDateTime = DateTime.Now; xmlFileInfo.LoadMethod = "WaterML download"; return(xmlFileInfo); }
private byte[] GetContextFromFile(DataFile file, int i) { if (_maxOrder == 0) { return(new byte[0]); } if (i > _maxOrder) { return(file.GetBytes(i - _maxOrder, _maxOrder)); } return(file.GetBytes(0, i)); }
public static void StartProcessing(DataFile dataFile) { dataFile.Status = (int)StatusHelper.Processing; Factory.Repositories.Files.Update(dataFile); Factory.Repositories.SaveChanges(); var currentName = GetName(dataFile.Id); var newThread = new ThreadOfBatch(currentName); ParameterizedThreadStart pts = newThread.DoWork; var workerThread = new Thread(pts); workerThread.Start(dataFile); Threads.TryAdd(currentName, newThread); }
public void TestMissingColumnFile(string fileName) { string testFolder = GetTestDataFolder(); IFileProcessor fileProcessor = new FileProcessor(); FileTypes fileTypes = FileTypes.GetFileTypes(); DataFile testFile = fileProcessor.FetchAllDataFiles(fileTypes, testFolder) .Find(x => x.FileName.Contains(fileName)); FileType fileType = new FileType(); FileProcessStatus validationSuccess = FileProcessStatus.Undetermined; string[] file = fileProcessor.ValidateInputFile(testFile, fileTypes, ref fileType, testFolder, ref validationSuccess); Assert.AreEqual(validationSuccess, FileProcessStatus.FileHeadersNotFound); }
public Task <(IEnumerable <TradePoint>, Error[])> HandleAsync(DataFile dataFile) { using (var ms = new MemoryStream(dataFile.Content)) { using (var textReader = new StreamReader(ms)) { using (var jsonReader = new JsonTextReader(textReader)) { var serializer = new JsonSerializer(); return(Task.FromResult((serializer.Deserialize <IEnumerable <TradePoint> >(jsonReader), Error.NoError))); } } } }
public Resource(dynamic datafile) { Name = datafile.Name; GatherDuration = Convert.ToDouble(datafile.GatherDuration); Size = new Size(DataFile.ToInt32(datafile.Width, 1), DataFile.ToInt32(datafile.Height, 1)); Passable = true; Texture = datafile.Texture; MaxWorkers = Convert.ToInt32(datafile.MaxWorkers); Tuple <ValueRange <int>, string> classvalues = DataFile.ToNamedIntValueRange(datafile.Holds); ResourceClass = PlarfGame.Instance.ResourceClasses.Single(r => r.Name.EqualsI(classvalues.Item2)); ValueRange = classvalues.Item1; }
public PluginInspector(DataContext context, DataFile file) { Log.Info("Inspecting records in plugin {0}", file.Name); using (var reader = new RecordReader(file.Open(), context)) { var header = reader.ReadHeader(); int masters = header.GetMasterFiles().Count(); byte newRecordPluginNumber = (byte)masters; foreach (var entry in reader.FindRecordsAsync()) { index.Add(entry.FilePosition, entry.FormId); } long newForms = 0; long done = 0; using (var progress = Display.StartProgress("Inspecting records")) { foreach (var item in index) { if (item.Value >> 24 == newRecordPluginNumber) { // Read only the bare minimum of form data (such as EditorID) var record = new DummyRecord(); reader.ReadRecordAt(item.Key, record, true); if (!string.IsNullOrEmpty(record.EditorId)) { var formId = item.Value & 0xFFFFFF; Log.Fine("Found new record {0:X8} '{1}'", formId, record.EditorId); newRecords.Add(new RecordInfo() { FormId = formId, EditorId = record.EditorId }); } newForms++; } done++; progress.Update(done, index.Count, file.Name); } } Log.Info("Found {0} records out of which {1} are new records.", index.Count, newForms); } }
public DataFile GetFile(string name, FileMode mode = FileMode.OpenOrCreate) { lock (this) { var dataFile = GetFromCache(name); if (dataFile == null) { Console.WriteLine($"{DateTime.Now} Opening file : {name}"); dataFile = new DataFile(Path.Combine(this.path, name), this.smanager); dataFile.Open(mode); this.dataFiles.Add(name, dataFile); } return dataFile; } }
void Awake() { if (instance != null && instance != this) { isSetToDestroy = true; Destroy(gameObject); } else { instance = this; } eventRegistery = GetComponentInChildren<EventRegistery>(); saveFile = GetComponentInChildren<SaveFile>(); systemFile = GetComponentInChildren<SystemFile>(); dataFile = GetComponentInChildren<DataFile>(); transitionery = GetComponentInChildren<TransitionManager>(); view = GetComponentInChildren<GlobalView>(); }
public void CreateSnapshot(DbConnectionInfo connectionInfo, string databaseName, string snapshotDatabaseName = null) { if (connectionInfo == null) throw new ArgumentNullException("connectionInfo must be initialized to create a snapshot."); if (string.IsNullOrWhiteSpace(databaseName)) throw new ArgumentNullException("databaseName is required to create a snapshot."); // 1. Initiate db connection Server server = connectionInfo.GetServer(); // 2. Check if DB Exists Database db = server.Databases[databaseName]; if (db == null) throw new ArgumentOutOfRangeException(string.Format("The database {0} does not exists.", databaseName)); var snapshot = db.IsDatabaseSnapshot; var hasSnapshots = db.IsDatabaseSnapshotBase; string dbSnapshotName = string.IsNullOrWhiteSpace(snapshotDatabaseName) ? databaseName + "_" + DateTime.UtcNow.ToString("yyMMdd") : snapshotDatabaseName; Database snapshotDatabase = new Database(server, dbSnapshotName); snapshotDatabase.DatabaseSnapshotBaseName = db.Name; foreach (FileGroup fileGroup in db.FileGroups) { FileGroup fg = new FileGroup(snapshotDatabase, fileGroup.Name); snapshotDatabase.FileGroups.Add(fg); } foreach (FileGroup fileGroup in db.FileGroups) { foreach (DataFile dataFile in fileGroup.Files) { var df = new DataFile(snapshotDatabase.FileGroups[fileGroup.Name], dataFile.Name, Path.Combine(db.PrimaryFilePath, string.Format("{0}_{1}.ss", dataFile.Name, snapshotDatabaseName))); snapshotDatabase.FileGroups[fileGroup.Name].Files.Add(df); } } // 3. snapshotDatabase.Create(); }
public static void Convert(BinaryReader reader, BinaryWriter writer) { Console.WriteLine("Read header."); var header = ReadHeader(reader); Console.WriteLine("Read body."); byte[] bytes = new byte[header.Size]; reader.Read(bytes, 0, header.Size); Console.WriteLine("Convert body."); var doubles = new double[header.Size]; for (var i = 0; i < header.Size; ++i) doubles[i] = bytes[i]; Console.WriteLine("Form and check data file structure."); var body = new Body(doubles); var file = new DataFile(header, body); Console.WriteLine("Write to output."); file.ToBytes(writer); }
private void SetupServer(GameType type) { Console.WriteLine("Setting up server..."); NetPeerConfiguration config = new NetPeerConfiguration("dystopia"); Console.WriteLine("Loading up World"); //MainWorld = IngameObjects.World.Load("Main"); if (!File.Exists("GameData\\server.config.txt")) GenerateConfig(); ServerConfig = new DataFile("GameData\\server.config.txt"); if (type != GameType.Single) { config.EnableMessageType(NetIncomingMessageType.DiscoveryResponse); config.EnableMessageType(NetIncomingMessageType.DiscoveryRequest); Clients = new DysClient[ServerConfig.GetInt32("maxplayers")]; polled = true; keeprunning = false; } else Clients = new DysClient[1]; //config.Port = ServerConfig.GetInt16("port"); config.Port = 28000; server = new NetServer(config); }
private void Create() { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Creating Database: {0}", this.DatabaseItem.ItemSpec)); if (this.CheckDatabaseExists()) { if (this.Force) { this.Delete(); } else { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Database already exists: {0}. Set Force to true to delete an existing Database.", this.DatabaseItem.ItemSpec)); return; } } SMO.Database newDatabase = new SMO.Database(this.sqlServer, this.DatabaseItem.ItemSpec); if (this.DataFilePath != null) { FileGroup fileGroup = new FileGroup(newDatabase, this.FileGroupName); DataFile dataFile = new DataFile(fileGroup, this.DatabaseItem.ItemSpec, this.DataFilePath.GetMetadata("FullPath")); fileGroup.Files.Add(dataFile); newDatabase.FileGroups.Add(fileGroup); } if (this.LogFilePath != null) { if (string.IsNullOrEmpty(this.LogName)) { this.LogName = this.DatabaseItem.ItemSpec + "_log"; } LogFile logFile = new LogFile(newDatabase, this.LogName, this.LogFilePath.GetMetadata("FullPath")); newDatabase.LogFiles.Add(logFile); } if (!string.IsNullOrEmpty(this.Collation)) { newDatabase.Collation = this.Collation; } newDatabase.Create(); }
private async Task testAndCreatedFile(DataFile file) { TestInitializedFileWithData(file); file.Name = "test2" + file._fileInfo.Extension; file.Id = System.IO.Path.Combine(file.Name); file._fileInfo = null; var result = await FileRepo.Create(file); Assert.NotNull(result); Assert.True(System.IO.File.Exists(file.Id)); filesToCleanup.Add(file.Id); }
private void ProcessInputFile(string path) { // if the file is already processed, skip it if (InputFiles.Any(x => x.FullFileName == path)) { return; } var dataFile = new DataFile(path); var dataProvider = DataProvider.CreateDataProvider(dataFile); InputFiles.Add(dataFile); Entities.AddRange(dataProvider.Generate()); }
//------------------------------------------------------------------------- public void update(float elapsed_tm) { if (mWWW == null && mQueDataFile.Count > 0) { mCurrentDataFile = mQueDataFile.Dequeue(); mWWW = new WWW(mCurrentDataFile.datafile_remote_url); CurrentDataFile = Path.GetFileName(mCurrentDataFile.datafile_local_path); CurrentIndex = TotalCount - mQueDataFile.Count; } if (mWWW == null) return; if (mWWW.isDone) { string dir = Path.GetDirectoryName(mCurrentDataFile.datafile_local_path); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } if (string.IsNullOrEmpty(mWWW.error)) { using (MemoryStream ms = new MemoryStream(mWWW.bytes)) { using (FileStream fs = new FileStream(mCurrentDataFile.datafile_local_path, FileMode.Create)) { ms.WriteTo(fs); } } mRetryCount = 0; mWWW = null; } else { EbLog.Error(mWWW.error); mRetryCount++; if (mRetryCount > 3) { mRetryCount = 0; mWWW = null; } else { mWWW = new WWW(mCurrentDataFile.datafile_remote_url); } } } else { // WWW有时会不下载,此处记录超时并重新下载 if (mWWW.progress == 0) { mWWWTimeOut += elapsed_tm; if (mWWWTimeOut > 5f) { mWWWTimeOut = 0f; mWWW = new WWW(mCurrentDataFile.datafile_remote_url); } } else { mWWWTimeOut = 0f; } } }
public FilePortfolioServer(Framework framework, string fileName, string host = null, int port = -1) : base(framework) { this.host = host; this.port = port; this.dataFile= host == null? new DataFile(fileName, framework.StreamerManager): new NetDataFile(fileName, host, port, framework.StreamerManager); }
private void addFile(Project proj, WJPUser curUser, HttpPostedFileBase file, string FileType) { string needExt; if (FileType == "Source") needExt = ".java"; else if (FileType == "Library") needExt = ".jar"; else needExt = ""; if (file != null && file.ContentLength > 0) { if (needExt == "" || Path.GetExtension(file.FileName) == needExt) { string fileName = Path.GetFileName(file.FileName); bool found = false; if (FileType == "Source") foreach (SourceFile f in proj.SourceFiles) { if (f.FileName == fileName) { found = true; break; } } else if (FileType == "Library") foreach (LibraryFile f in proj.LibraryFiles) { if (f.FileName == fileName) { found = true; break; } } else foreach (DataFile f in proj.DataFiles) { if (f.FileName == fileName) { found = true; break; } } if (!found) { string path = Path.Combine( Server.MapPath("~/Projects/") + proj.ProjectID + "/" + FileType, fileName); file.SaveAs(path); ProjectFile f; if (FileType == "Source") f = new SourceFile(); else if (FileType == "Library") f = new LibraryFile(); else f = new DataFile(); f.Adder = curUser; f.Modifier = curUser; f.FileName = fileName; f.Project = proj; curUser.LastChangesDate = DateTime.Now; curUser.LastProject = proj; if (FileType == "Source") { curUser.SourcesAdded++; proj.SourceFiles.Add( (SourceFile)f ); profileDB.SourceFiles.Add( (SourceFile)f ); } else if (FileType == "Library") { curUser.LibrariesAdded++; proj.LibraryFiles.Add((LibraryFile)f); profileDB.LibraryFiles.Add((LibraryFile)f); } else { curUser.DataAdded++; proj.DataFiles.Add((DataFile)f); profileDB.DataFiles.Add((DataFile)f); } proj.LastChangesDate = DateTime.Now; proj.LastChanger = curUser; profileDB.Entry(curUser).State = EntityState.Modified; profileDB.Entry(proj).State = EntityState.Modified; profileDB.SaveChanges(); } else ViewBag.FileTypeError = "File with such name already exists"; } else ViewBag.FileTypeError = "Uploaded file isn't " + FileType + " file"; } }
static void Main(string[] args) { double batchDataSize = 100000; //kB bool showHelp = false; string sourceServerName = null, sourceUsername = null, sourcePassword = null, sourceDatabaseName = null, destinationServerName = null, destinationUsername = null, destinationPassword = null, destinationDatabaseName = null; bool clearDestinationDatabase = false, checkIdentityExists = false; bool periodicBackup = false; string backupFilePath = null; IEnumerable<string> ignoredTables = Enumerable.Empty<string>(); var optionSet = new OptionSet() { { "h|help", "show this message and exit", x => showHelp = x != null}, { "srcserver=", "source server (eg. db000.appharbor.net)", x => sourceServerName = x }, { "srcusername="******"username on source server", x => sourceUsername = x }, { "srcpassword="******"password on source server", x => sourcePassword = x }, { "srcdatabasename=", "source database name", x => sourceDatabaseName = x }, { "dstserver=", "destination server", x => destinationServerName = x }, { "dstusername="******"username on destination server", x => destinationUsername = x }, { "dstpassword="******"password on destination server", x => destinationPassword = x }, { "dstdatabasename=", "destination database name", x => destinationDatabaseName = x }, { "ignoretables=", "names of tables not to copy", x => ignoredTables = x.Split(',') }, { "cleardstdatabase", "clears the destination database before copying the data", x => clearDestinationDatabase = x != null }, { "checkidentityexists", "only reseed identity if table has identity column", x => checkIdentityExists = x != null }, { "periodicBackup", "create full backup version of the source database", x => periodicBackup = x != null }, { "backupFilePath", "backup file path if you want to store on an external backup disc, leave blank for default. If set ensure filepath exists and is writable", x => backupFilePath = x } }; try { optionSet.Parse(args); if (showHelp) { ShowHelp(optionSet); return; } //Use settings from App.config if specified so can be more conveniently configured as a scheduled task sourceServerName = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["sourceServerName"]) ? sourceServerName : ConfigurationSettings.AppSettings["sourceServerName"]; sourceUsername = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["sourceUsername"]) ? sourceUsername : ConfigurationSettings.AppSettings["sourceUsername"]; sourcePassword = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["sourcePassword"]) ? sourcePassword : ConfigurationSettings.AppSettings["sourcePassword"]; sourceDatabaseName = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["sourceDatabaseName"]) ? sourceDatabaseName : ConfigurationSettings.AppSettings["sourceDatabaseName"]; destinationServerName = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["destinationServerName"]) ? destinationServerName : ConfigurationSettings.AppSettings["destinationServerName"]; destinationUsername = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["destinationUsername"]) ? destinationUsername : ConfigurationSettings.AppSettings["destinationUsername"]; destinationPassword = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["destinationPassword"]) ? destinationPassword : ConfigurationSettings.AppSettings["destinationPassword"]; destinationDatabaseName = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["destinationDatabaseName"]) ? destinationDatabaseName : ConfigurationSettings.AppSettings["destinationDatabaseName"]; ignoredTables = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["ignoredTables"]) ? ignoredTables : ConfigurationSettings.AppSettings["ignoredTables"].Split(','); clearDestinationDatabase = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["clearDestinationDatabase"]) ? clearDestinationDatabase : ConfigurationSettings.AppSettings["clearDestinationDatabase"] == "true"; checkIdentityExists = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["checkIdentityExists"]) ? checkIdentityExists : ConfigurationSettings.AppSettings["checkIdentityExists"] == "true"; periodicBackup = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["periodicBackup"]) ? periodicBackup : ConfigurationSettings.AppSettings["periodicBackup"] == "true"; backupFilePath = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["backupFilePath"]) ? backupFilePath : ConfigurationSettings.AppSettings["backupFilePath"]; if (sourceServerName == null) { throw new OptionException("source server not specified", "srcserver"); } if (sourceUsername == null && sourcePassword != null) { throw new OptionException("source username not specified", "srcusername"); } if (sourcePassword == null && sourceUsername != null) { throw new OptionException("source password not specified", "srcpassword"); } if (sourceDatabaseName == null) { throw new OptionException("source database name not specified", "srcdatabasename"); } if (destinationServerName == null) { throw new OptionException("destination server not specified", "dstserver"); } if (destinationUsername == null && destinationPassword != null) { throw new OptionException("destination username not specified", "dstusername"); } if (destinationPassword == null && destinationUsername != null) { throw new OptionException("destination password not specified", "dstpassword"); } if (!periodicBackup && destinationDatabaseName == null) //for periodic backup we create databases daily so not required { throw new OptionException("destination database name not specified", "dstdatabasename"); } } catch (OptionException exception) { Console.Write(string.Format("{0}: ", AppDomain.CurrentDomain.FriendlyName)); Console.WriteLine(exception.Message); Console.WriteLine("Try {0} --help for more information", AppDomain.CurrentDomain.FriendlyName); return; } Console.WriteLine("Retrieving source database table information..."); var usingTrustedConnection = string.IsNullOrEmpty(sourceUsername) && string.IsNullOrEmpty(sourcePassword); var sourceConnection = usingTrustedConnection ? new ServerConnection(sourceServerName) { LoginSecure = true } : new ServerConnection(sourceServerName, sourceUsername, sourcePassword); var sourceServer = new Server(sourceConnection); var sourceDatabase = sourceServer.Databases[sourceDatabaseName]; var tables = sourceDatabase.Tables .OfType<Table>() .Where(x => !x.IsSystemObject) .Select(x => '[' + x.Schema + ']' + ".[" + x.Name + ']') .ToList(); var actualExcludedTables = tables.Intersect(ignoredTables); if (actualExcludedTables.Any()) { Console.WriteLine(string.Format("Ignoring: {0}", string.Join(",", actualExcludedTables))); } tables = tables.Except(ignoredTables).ToList(); Console.WriteLine(string.Format("Copying {0} tables: {1}", tables.Count(), string.Join(",", tables))); var destinationConnectionString = GetConnectionString(destinationServerName, destinationDatabaseName, destinationUsername, destinationPassword); var sourceConnectionString = GetConnectionString(sourceServerName, sourceDatabaseName, sourceUsername, sourcePassword); var watch = Stopwatch.StartNew(); // clear the data before copying if (!periodicBackup && clearDestinationDatabase) //no need to clear if doing backups { using (var connection = new SqlConnection(destinationConnectionString)) { using (SqlCommand command = connection.CreateCommand()) { // http://stackoverflow.com/questions/155246/how-do-you-truncate-all-tables-in-a-database-using-tsql/156813#156813 StringBuilder commandBuilder = new StringBuilder(); commandBuilder.Append( @" -- disable all constraints EXEC sp_msforeachtable ""ALTER TABLE ? NOCHECK CONSTRAINT all"" -- delete data in all tables EXEC sp_msforeachtable ""DELETE FROM ?"" -- enable all constraints exec sp_msforeachtable ""ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"" "); if (checkIdentityExists) { // http://stackoverflow.com/questions/6542061/reseed-sql-server-identity-columns commandBuilder.Append( @"-- reseed (auto increment to 0) on user tables with identity column DECLARE @reseedSql NVARCHAR(MAX); SET @reseedSql = N''; SELECT @reseedSql = @reseedSql + N'DBCC CHECKIDENT(''' + QUOTENAME(OBJECT_SCHEMA_NAME(col.[object_id])) + '.' + QUOTENAME(OBJECT_NAME(col.[object_id])) + ''', RESEED, 0);' + CHAR(13) + CHAR(10) FROM sys.columns as col JOIN sys.tables as tbl ON col.[object_id] = tbl.[object_id] WHERE tbl.[type] = 'U' AND col.[is_identity] = 1; EXEC sp_executesql @reseedSql;"); } else { commandBuilder.Append(@" -- reseed (auto increment to 0) EXEC sp_msforeachtable ""DBCC CHECKIDENT ( '?', RESEED, 0)"" "); } command.CommandText = commandBuilder.ToString(); Console.WriteLine("Clearing the destination database"); connection.Open(); command.ExecuteNonQuery(); } } } /// If we are running to create a periodic backup if(periodicBackup) { Console.WriteLine("Creating backup database with filename format databasename_dd-MMM-HH-mm-ss"); //create a database name based on the date var dateFilename = DateTime.UtcNow.ToString("dd-MMM-HH-mm-ss"); var newDatabaseName = String.Format("{0}_{1}", sourceDatabaseName, dateFilename); var newDatabaseData = String.Format("{0}_{1}_Data", sourceDatabaseName, dateFilename); var mdfPath = String.Format("{0}{1}_{2}.mdf", backupFilePath, sourceDatabaseName, dateFilename); var newDatabaseLog = String.Format("{0}_{1}_log", sourceDatabaseName, dateFilename); var ldfPath = String.Format("{0}{1}_{2}_log.ldf", backupFilePath, sourceDatabaseName, dateFilename); try { using (SqlConnection sourceCon = new SqlConnection(sourceConnectionString)) { ServerConnection sourceServerConnection = new ServerConnection(sourceCon); Server sourceServ = new Server(sourceServerConnection); Database db; db = sourceServ.Databases[sourceDatabaseName]; //Create a new database that is to be destination database. using (SqlConnection destCon = new SqlConnection(destinationConnectionString)) { ServerConnection destinationServerConnection = new ServerConnection(destCon); Server destinationServer = new Server(destinationServerConnection); Database dbCopy; dbCopy = new Database(destinationServer, newDatabaseName); //if being backed up to non default location if (!String.IsNullOrEmpty(backupFilePath)) { //Adding Primary FileGroup dbCopy.FileGroups.Add(new FileGroup(dbCopy, "PRIMARY")); DataFile dtPrimary = new DataFile(dbCopy.FileGroups["PRIMARY"], newDatabaseData, mdfPath); dtPrimary.GrowthType = FileGrowthType.Percent; dtPrimary.Growth = 7; dbCopy.FileGroups["PRIMARY"].Files.Add(dtPrimary); //Adding LogFile LogFile logFile = new LogFile(dbCopy, newDatabaseLog, ldfPath); logFile.GrowthType = FileGrowthType.Percent; logFile.Growth = 7; dbCopy.LogFiles.Add(logFile); } //Create database. dbCopy.Create(); //Define a Transfer object and set the required options and properties. Transfer xfr; xfr = new Transfer(db); // additional options can be set here if required xfr.Options.WithDependencies = true; xfr.Options.ContinueScriptingOnError = true; xfr.DestinationDatabase = newDatabaseName; //if being backed up to non default location if (!String.IsNullOrEmpty(backupFilePath)) { xfr.TargetLogFilePath = ldfPath; xfr.TargetDatabaseFilePath = mdfPath; } xfr.CopyData = false; // not used as we are doing this below and was causing memory issues for me doing it this way with App Harbor db server - but would be simpler xfr.DestinationServer = destinationServer.Name; xfr.DestinationLoginSecure = true; xfr.CopySchema = true; xfr.CopyAllDefaults = true; xfr.CopyAllSchemas = true; xfr.CopyAllStoredProcedures = true; xfr.CopyAllTables = true; xfr.CopyAllUserDefinedAggregates = true; xfr.CopyAllUserDefinedDataTypes = true; xfr.CopyAllUserDefinedFunctions = true; xfr.CopyAllUserDefinedTableTypes = true; xfr.CopyAllUserDefinedTypes = true; xfr.CopyAllViews = true; xfr.Options.Default = true; xfr.Options.Indexes = true; xfr.Options.DriDefaults = true; xfr.Options.DriAllKeys = true; xfr.Options.DriForeignKeys = true; xfr.Options.DriIndexes = true; xfr.Options.DriPrimaryKey = true; xfr.Options.DriUniqueKeys = true; xfr.TransferData(); } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } //reset this to the new database now it's been created destinationConnectionString = GetConnectionString(destinationServerName, newDatabaseName, destinationUsername, destinationPassword); } foreach (var table in tables) { using (var connection = new SqlConnection(sourceConnectionString)) { double rowBatchSize = 10000; double rows = 0; double dataSize; connection.Open(); using (var command = connection.CreateCommand()) { command.CommandText = string.Format("exec sp_spaceused '{0}'", table); using (var reader = command.ExecuteReader()) { reader.Read(); var rowString = (string)reader["rows"]; rows = double.Parse(rowString); var dataSizeString = (string)reader["data"]; dataSize = double.Parse(dataSizeString.Split(' ').First()); //kB if (rows > 0 && dataSize > 0) { double rowSize = dataSize / rows; rowBatchSize = (int)(batchDataSize / rowSize); } } } if (rows > 0) { var columns = GetColumnNames(connection, table); Console.Write(string.Format("Copying {0} - {1} rows, {2:0.00} MB: ", table, rows, dataSize/1024)); using (var command = connection.CreateCommand()) { command.CommandText = string.Format("select * from {0}", table); using (var reader = command.ExecuteReader()) { using (var bulkCopy = new SqlBulkCopy( destinationConnectionString, SqlBulkCopyOptions.KeepIdentity | SqlBulkCopyOptions.TableLock)) { bulkCopy.NotifyAfter = Math.Max((int)rows / 10, 1); bulkCopy.SqlRowsCopied += new SqlRowsCopiedEventHandler(SqlRowsCopied); bulkCopy.DestinationTableName = table; bulkCopy.BatchSize = (int)rowBatchSize; bulkCopy.BulkCopyTimeout = int.MaxValue; foreach (var columnName in columns) { bulkCopy.ColumnMappings.Add(columnName, columnName); } bulkCopy.WriteToServer(reader); } } } Console.WriteLine(); } else { Console.WriteLine(string.Format("{0} had no rows", table)); } } } watch.Stop(); Console.WriteLine("Copy complete, total time {0} s", watch.ElapsedMilliseconds/1000); }
public SeriesManagerForm() { eX4XcIhHpDXt70u2x3N.k8isAcYzkUOGF(); // ISSUE: explicit constructor call base.\u002Ector(); this.MqmD7g3Mk5(); this.kvT1dEnNxu = (DataManager.Server as FileDataServer).File; this.NrYDLZdsHS(View.Details); this.vMvDiP1a34(); }
public DynamicRenderData(DataFile dataFile, Site site) : base(dataFile.SourceRelativePath) { _data = dataFile; _site = site; }
internal void Init(DataFile file, ObjectKey key) { lock (Sync) { this.file = file; this.key = key; key.CompressionLevel = 0; key.CompressionMethod = 0; // Init dataKey list if (this.cachePosition == -1) { this.cache = new IdArray<DataKey>(Math.Max(4096, this.bufferCount)); this.cacheKey = new ObjectKey(file, "", new DataKeyIdArray(this.cache)); } } }
public CsvDataProvider(DataFile dataFile) { _dataFile = dataFile; }
internal static void ValidateAllActivities(DataFile fileState) { // TODO implement }
public ExcelDataProvider(DataFile dataFile) { _dataFile = dataFile; }