public bool SaveXml(string path, string indentation = "\t") { using (var file = new File(Context, path, FileMode.Write)) { return SaveXml(file, indentation); } }
public bool LoadXml(string path) { using (var file = new File(Context, path, FileMode.Read)) { return LoadXml(file); } }
public ClusterBitmap(File file) { _file = file; _bitmap = new Bitmap( _file.OpenStream(AttributeType.Data, null, FileAccess.ReadWrite), Utilities.Ceil(file.Context.BiosParameterBlock.TotalSectors64, file.Context.BiosParameterBlock.SectorsPerCluster)); }
public static void ExtractText(File obj) { var blob = obj.Blob; if (blob != null) { var txt = _textExtractor.GetText(obj.Blob.GetStream(), blob.MimeType); var excerpt = obj.Excerpt; if (string.IsNullOrWhiteSpace(txt)) { if (excerpt != null) { // no excerpt -> delete excerpt object obj.Context.Delete(excerpt); } } else { if (excerpt == null) { excerpt = obj.Excerpt = obj.Context.Create<Excerpt>(); excerpt.File = obj; } excerpt.Text = txt.Trim(); } } }
public MetadataPartition(UdfContext context, LogicalVolumeDescriptor volumeDescriptor, MetadataPartitionMap partitionMap) : base(context, volumeDescriptor) { _partitionMap = partitionMap; PhysicalPartition physical = context.PhysicalPartitions[partitionMap.PartitionNumber]; long fileEntryPos = partitionMap.MetadataFileLocation * (long)volumeDescriptor.LogicalBlockSize; byte[] entryData = Utilities.ReadFully(physical.Content, fileEntryPos, _context.PhysicalSectorSize); if (!DescriptorTag.IsValid(entryData, 0)) { throw new IOException("Invalid descriptor tag looking for Metadata file entry"); } DescriptorTag dt = Utilities.ToStruct<DescriptorTag>(entryData, 0); if (dt.TagIdentifier == TagIdentifier.ExtendedFileEntry) { ExtendedFileEntry efe = Utilities.ToStruct<ExtendedFileEntry>(entryData, 0); _metadataFile = new File(context, physical, efe, _volumeDescriptor.LogicalBlockSize); } else { throw new NotImplementedException("Only EFE implemented for Metadata file entry"); } }
private Folder DirectoryDFS(Folder folder) { try { var files = Directory.GetFiles(folder.Name); foreach (string item in files) { FileInfo fileinfo = new FileInfo(item); File file = new File(item, (int)fileinfo.Length); folder.AddFile(file); } var childFolders = Directory.GetDirectories(folder.Name); foreach (string item in childFolders) { Folder subFolder = new Folder(item); folder.AddFolder(subFolder); DirectoryDFS(subFolder); } } //catches the exceptions given if access restricted folder reached catch (UnauthorizedAccessException) { } return folder; }
public static void CreateTree(FileInfo file) { string path = file.FullName; path = path.Substring(2, path.Length - 2); string[] folders = path.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries); string fileFolder = folders[folders.Length - 2]; for (int i = 0; i < folders.Length - 1; i++) { Folder currentFolder = new Folder(); currentFolder.Name = folders[i]; if (!windowsDirectory.ContainsKey(folders[i])) { windowsDirectory.Add(folders[i], currentFolder); } else { if (!windowsDirectory[folders[i]].ChildFolders.Contains(currentFolder)) { windowsDirectory[folders[i]].AddSubFolder(currentFolder); } } } File currentFile = new File(); currentFile.Name = file.Name; currentFile.Size = file.Length; windowsDirectory[fileFolder].Files.Add(currentFile); }
public void CreateAndSaveLocal() { IKp2aApp app = new TestKp2aApp(); IOConnectionInfo ioc = new IOConnectionInfo {Path = DefaultFilename}; File outputDir = new File(DefaultDirectory); outputDir.Mkdirs(); File targetFile = new File(ioc.Path); if (targetFile.Exists()) targetFile.Delete(); bool createSuccesful = false; //create the task: CreateDb createDb = new CreateDb(app, Application.Context, ioc, new ActionOnFinish((success, message) => { createSuccesful = success; if (!success) Android.Util.Log.Debug("KP2A_Test", message); }), false); //run it: createDb.Run(); //check expectations: Assert.IsTrue(createSuccesful); Assert.IsNotNull(app.GetDb()); Assert.IsNotNull(app.GetDb().KpDatabase); //the create task should create two groups: Assert.AreEqual(2, app.GetDb().KpDatabase.RootGroup.Groups.Count()); //ensure the the database can be loaded from file: PwDatabase loadedDb = new PwDatabase(); loadedDb.Open(ioc, new CompositeKey(), null, new KdbxDatabaseFormat(KdbxFormat.Default)); //Check whether the databases are equal AssertDatabasesAreEqual(loadedDb, app.GetDb().KpDatabase); }
public void Update(int id, File entity) { var existing = GetById(id); existing.FileName = entity.FileName; existing.FilePurpose = entity.FilePurpose; }
public DriveFile(File file, string content) { this.title = file.Title; this.description = file.Description; this.mimeType = file.MimeType; this.content = content; }
public void debugMode() { //初始化全局块组 for (int i = 0; i < Config.GROUPS; i++) VFS.BLOCK_GROUPS[i] = new BlockGroup(i); //初始化目录树 VFS.rootDir = new Directory("/", null); Directory bootDir = new Directory("boot", VFS.rootDir); Directory etcDir = new Directory("etc", VFS.rootDir); Directory libDir = new Directory("lib", VFS.rootDir); Directory homeDir = new Directory("home", VFS.rootDir); Directory rootDir = new Directory("root", VFS.rootDir); Directory tempDir = new Directory("temp", VFS.rootDir); VFS.rootDir.add(bootDir); VFS.rootDir.add(etcDir); VFS.rootDir.add(homeDir); VFS.rootDir.add(libDir); VFS.rootDir.add(rootDir); VFS.rootDir.add(tempDir); File file1 = new File("bashrc", etcDir); File file2 = new File("shadowsocks", etcDir); etcDir.add(file1); etcDir.add(file2); }
private static void FindAllFoldersAndFiles(DirectoryInfo di, Folder root) { try { var files = di.EnumerateFiles(); foreach (var file in files) { var currentFile = new File(file.Name, file.Length); root.Files.Add(currentFile); } var folders = di.EnumerateDirectories(); foreach (var folder in folders) { var currentFolder = new Folder(folder.Name); root.ChildFolders.Add(currentFolder); FindAllFoldersAndFiles(folder, currentFolder); } } catch (UnauthorizedAccessException e) { Console.WriteLine(e.Message); } }
public Index(File file, string name, BiosParameterBlock bpb, UpperCase upCase) { _file = file; _name = name; _bpb = bpb; _isFileIndex = name == "$I30"; _blockCache = new ObjectCache<long, IndexBlock>(); _root = _file.GetStream(AttributeType.IndexRoot, _name).GetContent<IndexRoot>(); _comparer = _root.GetCollator(upCase); using (Stream s = _file.OpenStream(AttributeType.IndexRoot, _name, FileAccess.Read)) { byte[] buffer = Utilities.ReadFully(s, (int)s.Length); _rootNode = new IndexNode(WriteRootNodeToDisk, 0, this, true, buffer, IndexRoot.HeaderOffset); // Give the attribute some room to breathe, so long as it doesn't squeeze others out // BROKEN, BROKEN, BROKEN - how to figure this out? Query at the point of adding entries to the root node? _rootNode.TotalSpaceAvailable += _file.MftRecordFreeSpace(AttributeType.IndexRoot, _name) - 100; } if (_file.StreamExists(AttributeType.IndexAllocation, _name)) { _indexStream = _file.OpenStream(AttributeType.IndexAllocation, _name, FileAccess.ReadWrite); } if (_file.StreamExists(AttributeType.Bitmap, _name)) { _indexBitmap = new Bitmap(_file.OpenStream(AttributeType.Bitmap, _name, FileAccess.ReadWrite), long.MaxValue); } }
private static void TraverseDirDFS(DirectoryInfo directory, Folder folder) { try { var files = directory.GetFiles(); foreach (var file in files) { var myFile = new File(file.Name, file.Length); folder.Files.Add(myFile); } var directories = directory.GetDirectories(); foreach (var dir in directories) { var newFolder = new Folder(dir.Name); TraverseDirDFS(dir, newFolder); folder.Folders.Add(newFolder); } } catch (UnauthorizedAccessException) { return; } }
private static void TraverseAllFilesAndFolders(string curDirPath, Folder curFolder) { try { // add all files to curFolder foreach (var fileName in Directory.GetFiles(curDirPath)) { ulong fileSize = (ulong) (new FileInfo(fileName).Length); File fileToAdd = new File(fileName, fileSize); curFolder.AddFile(fileToAdd); } // add all folders to curFolder foreach (var dirName in Directory.GetDirectories(curDirPath)) { curFolder.AddFolder(new Folder(dirName)); // take the last folder in the current folder and go through the algorithm again TraverseAllFilesAndFolders(dirName, curFolder.ChildFolders[curFolder.ChildFolders.Length - 1]); } } catch (UnauthorizedAccessException ex) { Console.WriteLine(ex.Message); } }
public static Folder TraverseFolders(string path, ref Folder myFolder) { //DirectoryInfo di = new DirectoryInfo(path); //Folder myFolder = new Folder(di.Name); var subFolders = Directory.GetDirectories(path); var files = Directory.GetFiles(path); foreach (var file in files) { FileInfo fi = new FileInfo(file); File fileToAdd = new File(fi.Name, fi.Length); myFolder.AddFile(fileToAdd); } foreach (var subFolder in subFolders) { DirectoryInfo dir = new DirectoryInfo(subFolder); Folder folderToAdd = new Folder(dir.Name); myFolder.AddFolder(folderToAdd); TraverseFolders(subFolder, ref folderToAdd); } return myFolder; }
public static void RecurseDataSet(File f, DataSet ds, string indent) { CSharpDataSet cds = new CSharpDataSet(ds); while(!cds.IsAtEnd()) { DataElement de = cds.GetCurrent(); // Compute VR from the toplevel file, and the currently processed dataset: VR vr = DataSetHelper.ComputeVR(f, ds, de.GetTag() ); if( vr.Compatible( new VR(VR.VRType.SQ) ) ) { uint uvl = (uint)de.GetVL(); // Test cast is ok System.Console.WriteLine( indent + de.GetTag().toString() + ":" + uvl ); // why not ? //SequenceOfItems sq = de.GetSequenceOfItems(); // GetValueAsSQ handle more cases than GetSequenceOfItems SmartPtrSQ sq = de.GetValueAsSQ(); uint n = sq.GetNumberOfItems(); for( uint i = 1; i <= n; i++) // item starts at 1, not 0 { Item item = sq.GetItem( i ); DataSet nested = item.GetNestedDataSet(); RecurseDataSet( f, nested, indent + " " ); } } else { System.Console.WriteLine( indent + de.toString() ); } cds.Next(); } }
private void HTML_Output(File dat) { Overview.NavigateToString("Under construction."); //string H1 = "<h1>{0}</h1>"; //string H2 = "<h2>{0}</h2>"; //var sb = new StringBuilder(); ////PrettyPrint XD //sb.AppendFormat(H1,dat.Filename); //prettyPrint(dat.Header, sb); //sb.AppendFormat(H2,"Section Type 1's"); //foreach (string name in dat.Section1Entries.Keys) //{ // sb.AppendLine(name); // prettyPrint(dat.Section1Entries[name], sb); //} //sb.AppendFormat(H2,"Section Type 2's"); //foreach (string name in dat.Section2Entries.Keys) //{ // sb.AppendLine(name); // prettyPrint(dat.Section2Entries[name], sb); //} //sb.AppendFormat(H2,"FTHeader"); //prettyPrint(dat.FTHeader, sb); //sb.AppendFormat(H2, "Attributes"); //sb.AppendLine("<table>"); //foreach (MeleeLib.Attribute a in dat.Attributes) //{ // sb.AppendFormat("<tr><td>0x{0:X3}</td><td>{1}</td></tr>\n", a.Offset, a.Value); //} //sb.AppendLine("</table>"); //sb.AppendFormat(H2, "Subaction Headers"); //foreach(MeleeLib.Subaction s in dat.Subactions) //{ // prettyPrint(s.Header, sb); //} //Overview.NavigateToString(sb.ToString()); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Bundle bundle = (savedInstanceState ?? Intent.Extras); _requestId = bundle.GetInt(ExtraRequestId, 0); _mediaAction = bundle.GetString(ExtraMediaAction); _mediaType = bundle.GetString(ExtraMediaType); _photoSubDir = bundle.GetString(ExtraPhotosDir); // see if already presented (in case rotation tore down this intermediate activity) _presented = bundle.GetBoolean(PresentedBundleKey); if (!_presented && _mediaAction == SelectMediaAction && _mediaType == PhotoMediaType) StartPickPhotoIntent(); else if (_mediaAction == CreateMediaAction && _mediaType == PhotoMediaType) { if (!_presented) { CreatePhotoDir(); if (_dir == null) { OnMediaPicked(new MediaPickedEventArgs(_requestId, new System.IO.IOException("Unable to create photo directory."))); Finish(); return; } StartTakePhotoIntent(); } else { var path = bundle.GetString(FilePathKey); _file = new File(path); } } }
private static void MapInnerDirectory(Folder folder, string directory) { try { DirectoryInfo directoryInfo = new DirectoryInfo(directory); DirectoryInfo[] subDirectories = directoryInfo.GetDirectories(); folder.SubFolders = new Folder[subDirectories.Length]; for (int i = 0; i < subDirectories.Length; i++) { var newFolder = new Folder(subDirectories[i].Name); folder.SubFolders[i] = newFolder; MapInnerDirectory(newFolder, subDirectories[i].FullName); } FileInfo[] filesInfo = directoryInfo.GetFiles(); folder.Files = new File[filesInfo.Length]; for (int i = 0; i < filesInfo.Length; i++) { var newFile = new File(filesInfo[i].Name, filesInfo[i].Length); folder.Files[i] = newFile; } } catch (Exception e) { Console.WriteLine(e.Message); } }
//获取资料 public void File_Search(HttpContext context) { string Searchkey = context.Request.Params["Searchkey"]; int OCID = Convert.ToInt32(context.Request.Params["OCID"]); int CourseID = Convert.ToInt32(context.Request.Params["CourseID"]); int FolderID = Convert.ToInt32(context.Request.Params["FolderID"]); int FileType = Convert.ToInt32(context.Request.Params["FileType"]); int ShareRange=-1; int UserID = UserService.CurrentUser.UserID; int OwnerUserID = 1; int PageSize = 999999; int PageIndex = 1; File file = new File(); file.Keys = Searchkey; file.OCID = OCID; file.CourseID = CourseID; file.FolderID = FolderID; file.FileType = FileType; file.ShareRange = -1; file.CreateUserID = UserID; file.UploadTime = DateTime.Now.AddMonths(-1000); IES.G2S.Resource.BLL.FileBLL filebll = new IES.G2S.Resource.BLL.FileBLL(); //List<File> filelist = filebll.File_Search(file, PageSize, PageIndex); DataTable dt = IES.Common.ListToDateUtil.ListToDataTable<File>(filebll.File_Search(file, PageSize, PageIndex)); if (dt != null && dt.Rows.Count > 0) { context.Response.Write(Tools.JsonConvert.GetJSON(dt)); } else { context.Response.Write("False"); } }
static void TraverseFilesAndFolders(string path, Folder folder) { try { foreach (var fileName in Directory.GetFiles(path)) { int fileSize = (int)(new FileInfo(fileName)).Length; File file = new File(fileName, fileSize); folder.Files.Add(file); } foreach (var directoryName in Directory.GetDirectories(path)) { folder.ChildFolders.Add(new Folder(directoryName)); TraverseFilesAndFolders(directoryName, folder.ChildFolders[folder.ChildFolders.Count - 1]); } } catch (UnauthorizedAccessException e) { Console.WriteLine(e.Message); } }
public void SpecfileResult_NoErrors_IsNotInvalid() { var file = new File("symitar", "10", "FileName", FileType.RepGen, DateTime.Now, 100); var result = new SpecfileResult(file, "", "", 0, 0); result.InvalidInstall.Should().BeFalse(); }
public void Play(string filePath) { try { if (player == null) { player = new MediaPlayer(); } else { player.Reset(); } // This method works better than setting the file path in SetDataSource. Don't know why. var file = new File(filePath); var fis = new FileInputStream(file); player.SetDataSource(fis.FD); //player.SetDataSource(filePath); player.Prepare(); player.Start(); } catch (Exception ex) { System.Console.Out.WriteLine(ex.StackTrace); } }
public static File InsertFile(DriveService service, string mimeType, string filename, System.IO.Stream stream) { // File's metadata. File body = new File(); body.Title = filename; body.MimeType = mimeType; body.Parents = new List<ParentReference>() { new ParentReference() { Id = "0BySX8GhV2wf8enhxSU56N25Rbnc" } }; try { FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, mimeType); request.Upload(); File file = request.ResponseBody; // Uncomment the following line to print the File ID. // Console.WriteLine("File ID: " + file.Id); return file; } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); return null; } }
public void runServer() { tcpListener.Start(); //Byte[] bytes = new Byte[16]; //Byte[] data = new Byte[16]; while (true) { TcpClient tcpClient = tcpListener.AcceptTcpClient(); NetworkStream stream = tcpClient.GetStream(); string command = new StreamReader(stream).ReadToEnd(); string[] commands = command.Split(seperators); if (commands[0].Contains("GET")) { file = new File(commands[1]); FileStream fs = new FileStream(commands[1], FileMode.Open); int currentPos = 0; while (currentPos < fs.Length) { byte[] bytes = new byte[16]; int data = fs.Read(bytes, currentPos, 16); stream.Write(bytes, 0, 16); currentPos += 16; } } } }
//JAVA TO C# CONVERTER WARNING: 'final' parameters are not allowed in .NET: //ORIGINAL LINE: public VCFWriter(final File location, final OutputStream output, final net.sf.samtools.SAMSequenceDictionary refDict, final boolean enableOnTheFlyIndexing, boolean doNotWriteGenotypes, final boolean allowMissingFieldsInHeader) public VCFWriter(File location, OutputStream output, SAMSequenceDictionary refDict, bool enableOnTheFlyIndexing, bool doNotWriteGenotypes, bool allowMissingFieldsInHeader) : base(writerName(location, output), location, output, refDict, enableOnTheFlyIndexing) { this.doNotWriteGenotypes = doNotWriteGenotypes; this.allowMissingFieldsInHeader = allowMissingFieldsInHeader; this.charset = Charset.forName("ISO-8859-1"); this.writer = new OutputStreamWriter(lineBuffer, charset); }
/// <summary> /// Updates a file /// Documentation: https://developers.google.com/drive/v2/reference/files/update /// </summary> /// <param name="_service">a Valid authenticated DriveService</param> /// <param name="_uploadFile">path to the file to upload</param> /// <param name="_parent">Collection of parent folders which contain this file. /// Setting this field will put the file in all of the provided folders. root folder.</param> /// <param name="_fileId">the resource id for the file we would like to update</param> /// <returns>If upload succeeded returns the File resource of the uploaded file /// If the upload fails returns null</returns> public static File updateFile(DriveService _service, string _uploadFile, string _parent,string _fileId) { if (System.IO.File.Exists(_uploadFile)) { File body = new File(); body.Title = System.IO.Path.GetFileName(_uploadFile); body.Description = "File updated by Diamto Drive Sample"; body.MimeType = GetMimeType(_uploadFile); body.Parents = new List<ParentReference>() { new ParentReference() { Id = _parent } }; // File's content. byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile); System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); try { FilesResource.UpdateMediaUpload request = _service.Files.Update(body, _fileId, stream, GetMimeType(_uploadFile)); request.Upload(); return request.ResponseBody; } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); return null; } } else { Console.WriteLine("File does not exist: " + _uploadFile); return null; } }
private string year; // 4 #endregion Fields #region Constructors public Mp3Tag(File Music) { FileStream fs = System.IO.File.OpenRead(Music.Address()); if (fs.Length >= 128) { byte[] btID = new byte[3]; byte[] btTitle = new byte[30]; byte[] btArtist = new byte[30]; byte[] btAlbum = new byte[30]; byte[] btYear = new byte[4]; byte[] btComment = new byte[30]; byte[] btGenre = new byte[1]; fs.Seek(-128, SeekOrigin.End); fs.Read(btID, 0, 3); fs.Read(btTitle, 0, 30); fs.Read(btArtist, 0, 30); fs.Read(btAlbum, 0, 30); fs.Read(btYear, 0, 4); fs.Read(btComment, 0, 30); fs.Read(btGenre, 0, 1); id = Encoding.Default.GetString(btID); if (id.Equals("TAG")) { title = Encoding.Default.GetString(btTitle); artist = Encoding.Default.GetString(btArtist); album = Encoding.Default.GetString(btAlbum); year = Encoding.Default.GetString(btYear); comment = Encoding.Default.GetString(btComment); genre = Encoding.Default.GetString(btGenre); } fs.Close(); } }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Requires({"name != null", "! ( location == null && output == null )", "! ( enableOnTheFlyIndexing && location == null )"}) protected IndexingVariantContextWriter(final String name, final File location, final OutputStream output, final net.sf.samtools.SAMSequenceDictionary refDict, final boolean enableOnTheFlyIndexing) //JAVA TO C# CONVERTER WARNING: 'final' parameters are not allowed in .NET: protected internal IndexingVariantContextWriter(string name, File location, OutputStream output, SAMSequenceDictionary refDict, bool enableOnTheFlyIndexing) { outputStream = output; this.name = name; this.refDict = refDict; if (enableOnTheFlyIndexing) { try { idxStream = new LittleEndianOutputStream(new FileOutputStream(Tribble.indexFile(location))); //System.out.println("Creating index on the fly for " + location); indexer = new DynamicIndexCreator(IndexFactory.IndexBalanceApproach.FOR_SEEK_TIME); indexer.initialize(location, indexer.defaultBinSize()); positionalOutputStream = new PositionalOutputStream(output); outputStream = positionalOutputStream; } catch (IOException ex) { // No matter what we keep going, since we don't care if we can't create the index file idxStream = null; indexer = null; positionalOutputStream = null; } } }
internal static void Main(string[] args) { System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US"); // Console Size try { int Width = Console.LargestWindowWidth >= 100 ? 100 : Console.LargestWindowWidth; int Height = Console.LargestWindowHeight >= 50 ? 50 : Console.LargestWindowHeight; Console.SetWindowSize(Width, Height); } catch { } // Catch possible SecurityException // Build Dialog OpenFileDialog Dialog = new OpenFileDialog { Filter = "Pop Files|*.pop" }; #if DEBUG Dialog.InitialDirectory = @""; #endif // Get Execution Safety SafetyLevel = Program.Config.ReadBool("bool_unsafe") ? ParserSafetyLevel.UNSAFE : ParserSafetyLevel.SAFE; // Launch Flags for (int i = 0; i < args.Length; i++) { if (args[i] == "-pop") { Dialog.FileName = args[i + 1]; LaunchArguments["-pop"] = args[i + 1]; } if (args[i] == "-log") { PrintColor.InfoLine("=====Log: {f:Cyan}{$0}{r}=====", args[i + 1]); LogWriter = new StreamWriter(new FileStream(args[i + 1], FileMode.Append)); LaunchArguments["-log"] = args[i + 1]; } if (args[i] == "--no_menu") { NoMenu = true; LaunchArguments["--no_menu"] = "1"; } if (args[i] == "--auto_close") { AutoClose = true; LaunchArguments["--auto_close"] = "1"; } if (args[i] == "--AF") { Secret = true; LaunchArguments["--AF"] = "1"; } if (args[i] == "--time") { ShowStopWatch = true; LaunchArguments["--time"] = "1"; } if (args[i] == "--unsafe") { SafetyLevel = ParserSafetyLevel.UNSAFE; LaunchArguments["--unsafe"] = "1"; } if (args[i] == "--safe") { SafetyLevel = ParserSafetyLevel.SAFE; LaunchArguments["--safe"] = "1"; } } // Show Dialog if (SafetyLevel == ParserSafetyLevel.UNSAFE) { PrintColor.InfoLine("P3 v2.1.0 {b:White}{f:Black} UNSAFE MODE {r}"); } else { PrintColor.InfoLine("P3 v2.1.0"); } while (Dialog.FileName == "") { PrintColor.InfoLine("Select your Pop file"); Dialog.ShowDialog(); } FullPopFileDirectory = Path.GetDirectoryName(Dialog.FileName); FullPopFilePath = Dialog.FileName; LaunchArguments["-pop"] = Dialog.FileName; Console.Title = "P3 - " + Path.GetFileName(FullPopFilePath); var StopWatch = System.Diagnostics.Stopwatch.StartNew(); LineCount += File.ReadLines(FullPopFilePath).Count(); //string FileContents = File.ReadAllText(FullPopFilePath); // Legacy input method //AntlrInputStream inputstream = new AntlrInputStream(FileContents); FileStream FS = new FileStream(FullPopFilePath, FileMode.Open); AntlrInputStream inputstream = new AntlrInputStream(FS); FS.Close(); PopulationLexer lexer = new PopulationLexer(inputstream); lexer.RemoveErrorListeners(); lexer.AddErrorListener(new PopulationLexerErrorListener <int>()); CommonTokenStream tokenstream = new CommonTokenStream(lexer); PopulationParser parser = new PopulationParser(tokenstream); parser.RemoveErrorListeners(); parser.AddErrorListener(new PopulationErrorListener()); parser.ErrorHandler = new PopulationErrorStrategy(); ItemDatabase.Build(); AttributeDatabase.Build(); PrintColor.InfoLine("Pop File - {f:Cyan}{$0}{r}", FullPopFilePath); PopulationParser.PopfileContext context = parser.popfile(); PopulationVisitor visitor = new PopulationVisitor(); visitor.Visit(context, tokenstream); Program.PopFile = visitor.GetPopFile(); PopAnalyzer = new PopulationAnalyzer(Program.PopFile); PrintColor.InfoLine("\tDone Parsing Pop File - {f:Cyan}{$0}{r}", Path.GetFileName(FullPopFilePath)); StopWatch.Stop(); // Ending Statement Console.Write("\n"); if (Error.Errors > 0) { PrintColor.WriteLine("{f:Black}{b:Red}Finished with {$0} errors and {$1} warnings.{r}", Error.Errors.ToString(), Warning.Warnings.ToString()); } else if (Warning.Warnings > 0) { PrintColor.WriteLine("{f:Black}{b:Yellow}Finished with {$0} warnings.{r}", Warning.Warnings.ToString()); } else { PrintColor.WriteLine("{f:Black}{b:Green}Finished cleanly.{r}"); } // Execution Time if (ShowStopWatch) { PrintColor.InfoLine("Execution time: {f:Cyan}{$1} lines{r} in {f:Cyan}{$0}ms{r}", StopWatch.ElapsedMilliseconds.ToString(), LineCount.ToString()); } if (Secret) { List <string> tokens = new List <string>(); foreach (IToken t in tokenstream.GetTokens()) { tokens.Add(t.Text); } try { AprilFools.DoTheThing(tokens); } catch { PrintColor.InfoLine("Better luck next time! (an error occurred)"); } } if (AutoClose) { // Avoid everything } else if (!NoMenu) { Menu.Capture(); } else { PrintColor.InfoLine("Press any key to continue."); Console.ReadKey(); } if (LogWriter != null) { LogWriter.Write("\n=========================\n\n"); LogWriter.Close(); } }
public static Mod FromZip(string path) { // Various wacky Changed, Renamed, Removed events eventually lead to this. // C# Optionals when. if (!File.Exists(path)) { return(null); } var mod = new Mod { ModPath = path }; try { using (var zip = ZipFile.Open(path, ZipArchiveMode.Read)) { var meta = zip.GetEntry(MetaFile); if (meta == null) { mod.Title = Path.GetFileNameWithoutExtension(path); return(mod); } try { var stream = meta.Open(); var doc = XDocument.Load(stream); foreach (var element in doc.Root.Elements()) { if (element.Name == "title") { mod.Title = element.Value; } else if (element.Name == "description" || element.Name == "desc") { mod.Description = element.Value; } else if (element.Name == "author") { mod.Author = element.Value; } else if (element.Name == "version") { mod.Version = element.Value; } } } catch (FileNotFoundException) { } } } // On the weird off chance that you are currently still copying the folder // to the mods directory, it will be "opened by another process" and crash // the program horribly, to the point of not even responding to Task Manager. catch (IOException) { for (int i = 0; i < 10; ++i) { Thread.Sleep(1000); try { var again = FromZip(path); return(again); } catch (IOException) { } } // F**k it, give up on this file. return(null); } catch (UnauthorizedAccessException e) { throw e; } return(mod); }
// Jovana 29.11.21 - ne koristi se //private void password_Enter(object sender, EventArgs e) //{ // PasswordTextBox.Text = ""; //} //private void username_Enter(object sender, EventArgs e) //{ // UsernameTextBox.Text = ""; //} private void UsernameTextBox_Leave(object sender, EventArgs e) { //pictureBox1.Visible = false; aliasDatabase = new Dictionary <string, string>(); cmbBaze.Items.Clear(); CmbOrg.Items.Clear(); CmbOrg.Visible = false; lblGrupa.Visible = false; cmbBaze.Visible = false; lblBaza.Visible = false; if (UsernameTextBox.Text != "") { //var fileReader = File.ReadAllText(Application.StartupPath + @"\XmlLat\xxxx.ini"); Console.WriteLine(Application.StartupPath); //Djora 30.11.20 //var fileReader = File.ReadAllText(Application.StartupPath+ @"\xxxx.ini"); //ivana 15.10.2021. da ne bi pucao, mozda treba obraditi else var fileReader = ""; if (System.IO.File.Exists(@"\\192.168.1.4\Repozitorijum\ISBankom\XXXX\xxxx.ini")) { fileReader = File.ReadAllText(@"\\192.168.1.4\Repozitorijum\ISBankom\XXXX\xxxx.ini"); } else { MessageBox.Show("xxxx.ini Nedostupan."); return; } string[] separators11 = new[] { "[", "]" }; int n = 0; string struser = UsernameTextBox.Text.ToLower(); string strobrada = ""; string[] words = fileReader.Split(separators11, StringSplitOptions.RemoveEmptyEntries); for (n = 0; n < words.Length; n++) { string cc = words[n].ToLower(); if (strobrada != "") { strobrada = words[n]; break; } if (cc == struser) { strobrada = words[n]; } if (cc == "logovanje") { string pom = words[n + 1]; char[] separators1 = { '#' }; pom = pom.Replace("\r\n", "#").Replace("\r", "").Replace("\n", ""); var result1 = pom.Split(separators1, StringSplitOptions.None); for (int j = 0; j < result1.Length; j++) { //steva 04.03.2021. if (result1[j].Contains("RptSlike=")) { ReportSlike = result1[j].Substring(result1[j].IndexOf("=") + 1); // break; } if (result1[j].Contains("Report=")) { ReportServer = result1[j].Substring(result1[j].IndexOf("=") + 1); // break; } //kraj steva 04.03.2021. //Jovana 19.02.21 Console.WriteLine(result1[j]); if (result1[j].Contains("Server=")) { if (result1[j].IndexOf("Server=") == 0) { ImeServera = result1[j].Substring(result1[j].IndexOf("=") + 1); } else { FileServer = result1[j].Substring(result1[j].IndexOf("=") + 1); } //break; } //tamara 22.4.2021. if (result1[j].Contains("SlikaZaposlenog=")) { SlikePutanja = result1[j].Substring(result1[j].IndexOf("=") + 1); } if ((result1[j].Length > 8 && result1[j].Substring(0, 9) == "Dokumenti")) { gDokumenti = result1[j].Substring(result1[j].IndexOf("=") + 3); } } } } //Jovana 19.02.21 gDokumenti = "\\" + FileServer + gDokumenti; // char[] separators = { '#','=' }; char[] separators = { '#' }; strobrada = strobrada.Replace("\r\n", "#").Replace("\r", "").Replace("\n", ""); //ivana 18.10.2021. aliasDatabase.Clear(); var result = strobrada.Split(separators, StringSplitOptions.None); int k = -1; for (n = 0; n < result.Length; n++) { if (result[n] != "") { if (result[n] == "IzborBaze=1") { strIzborBaze = result[n]; } //tamara 12.7.21. else if (result[n] == "IzborBaze=0") { strIzborBaze = result[n]; } if (result[n] == "IzborOrganizacionogDela=1") { strIzborOrganizacionogDela = result[n]; } //tamara 12.7.21. else if (result[n] == "IzborOrganizacionogDela=0") { strIzborOrganizacionogDela = result[n]; } if (result[n].Length > 4 && result[n].Substring(0, 4) == "Baza") { k++; if (result[n].Substring(0, 5) == "Baza1") { indexCurrentbaza = k; strCurrentbaza = result[n].Substring(result[n].IndexOf("=") + 1); } aliasDatabase.Add(result[n].Substring(result[n].IndexOf("-") + 1), result[n].Substring(result[n].IndexOf("=") + 1, result[n].IndexOf("-") - result[n].IndexOf("=") - 1)); cmbBaze.Items.Add(result[n].Substring(result[n].IndexOf("-") + 1)); } if ((result[n].Length > 15 && result[n].Substring(0, 16) == "OrganizacioniDeo")) { strOrgDefaultText = result[n].Substring(result[n].IndexOf("=") + 1); //grupa.AddItem(result[n].Substring(result[n].IndexOf("=") + 1)); } } } switch (strIzborBaze) { case "IzborBaze=0": //tamara 12.7.21. lblBaza.Visible = true; cmbBaze.Visible = true; cmbBaze.Enabled = false; cmbBaze.SelectedIndex = k > -1 ? indexCurrentbaza : -1; break; case "IzborBaze=1": lblBaza.Visible = true; cmbBaze.Visible = true; //ivana 13.10.2021. //cmbBaze.SelectedIndex = indexCurrentbaza; cmbBaze.SelectedIndex = k > -1 ? indexCurrentbaza : -1; break; } switch (strIzborOrganizacionogDela) { case "IzborOrganizacionogDela=0": CmbOrg.Items.Add(strOrgDefaultText); //tamara 12.7.21. lblGrupa.Visible = true; CmbOrg.Visible = true; CmbOrg.Enabled = false; CmbOrg.SelectedIndex = 0; break; case "IzborOrganizacionogDela=1": //ivana 8.12.2021. dodala sam Ccopy = 0 zbog 3. i 4. org.struk., jer su iste var query = "SELECT Naziv FROM OrganizacionaStruktura where Ccopy = 0"; var dataTable = DB.ReturnDataTable(query); for (int i = 0; i < dataTable.Rows.Count; i++) { if (dataTable.Rows[i][0].ToString() == strOrgDefaultText) { indexOrgDefault = i; } CmbOrg.Items.Add(dataTable.Rows[i][0].ToString()); } lblGrupa.Visible = true; CmbOrg.Visible = true; CmbOrg.SelectedIndex = indexOrgDefault; break; } //novo 08.12.2020. zajedno CmbOrg.Items.Clear(); var query1 = "SELECT Naziv FROM OrganizacionaStruktura "; var databaseBroker = new DataBaseBroker(); var dataTable1 = databaseBroker.ReturnDataTable(query1); for (int i = 0; i < dataTable1.Rows.Count; i++) { if (dataTable1.Rows[i][0].ToString() == strOrgDefaultText) { indexOrgDefault = i; } if (dataTable1.Rows[i][0].ToString() != "") { CmbOrg.Items.Add(dataTable1.Rows[i][0].ToString()); } } Console.WriteLine(cmbBaze.Text); Console.WriteLine(CmbOrg.Text); DataSet IdOrg = DB.ReturnDS( " select o.*,o.ID_Zemlja,os.NazivJavni as Firma ,os.NazivStampaca, os.PutanjaStampaca,os.Pib from OrganizacionaStruktura as o WITH (NOLOCK) ,organizacionastrukturastablo os WITH (NOLOCK) where o.Naziv='" + CmbOrg.Text + "' And o.ID_OrganizacionaStrukturaStablo=os.ID_OrganizacionaStrukturaStablo ;"); DataView dv = IdOrg.Tables[0].DefaultView; var zemlja = dv[0]["ID_Zemlja"]; string str = "select v.ID_Sifrarnikvaluta,OznVal,ID_Zemlja from sifrarnikvaluta as v WITH (NOLOCK) ,Zemlja as z WITH (NOLOCK) where z.ID_Zemlja=" + Convert.ToString(dv[0]["ID_Zemlja"]); str += " AND v.SifraZemlje=z.SifraZemlje"; DataTable RsValuta = DB.ReturnDataTable(str); dv.Dispose(); dv = RsValuta.DefaultView; if (RsValuta.Rows.Count == 0) { Program.DomacaValuta = "RSD"; Program.ID_DomacaValuta = 1; Program.ID_MojaZemlja = 4; } else { Program.DomacaValuta = Convert.ToString(dv[0]["OznVal"]); Program.ID_DomacaValuta = Convert.ToInt32(dv[0]["ID_SifrarnikValuta"]); Program.ID_MojaZemlja = Convert.ToInt32(dv[0]["ID_Zemlja"]); } //ivana 8.10.2021. izmenila sam ceo ovaj deo //var upit = "SELECT ID_Radnik FROM KadrovskaEvidencija WHERE Suser = @param0"; var upit = "SELECT ID_KadrovskaEvidencija FROM KadrovskaEvidencija WHERE Suser = @param0"; var prDok = DB.ParamsQueryDT(upit, UsernameTextBox.Text); //if (prDok.Rows.Count != 0 && prDok.Rows[0]["ID_Radnik"] != System.DBNull.Value) if (prDok.Rows.Count != 0 && prDok.Rows[0]["ID_KadrovskaEvidencija"] != System.DBNull.Value) { //int ID_Radnik = Convert.ToInt32(prDok.Rows[0]["ID_Radnik"]); int Id_ke = Convert.ToInt32(prDok.Rows[0]["ID_KadrovskaEvidencija"]); //upit = "SELECT ID_Firma,mbr FROM Radnik where ID = @param0"; upit = "SELECT ID_Firma,mbr FROM Radnik where ID_KadrovskaEvidencija = @param0"; //prDok = DB.ParamsQueryDT(upit, ID_Radnik); prDok = DB.ParamsQueryDT(upit, Id_ke); if (prDok.Rows.Count != 0) { int ID_Firma = Convert.ToInt32(prDok.Rows[0]["ID_Firma"]); int mbr = Convert.ToInt32(prDok.Rows[0]["mbr"]); //tamara 22.4.2021. if (File.Exists(SlikePutanja + ID_Firma + "-" + mbr + ".jpg")) { pictureBox1.Image = Image.FromFile(SlikePutanja + ID_Firma + "-" + mbr + ".jpg"); pictureBox1.Visible = true; } else { //pictureBox1.Visible = false; pictureBox1.Image = Image.FromFile(SlikePutanja + "default.jpg"); } pictureBox1.Refresh(); } else { pictureBox1.Image = Image.FromFile(SlikePutanja + "default.jpg"); } } else { pictureBox1.Image = Image.FromFile(SlikePutanja + "default.jpg"); } } }
//获取高度图 private static void SaveHeightMap(Transform rootTrans, SceneInfoInEditor mapInfo, string fullPathName) { EditorUtility.DisplayProgressBar("提示", "正在生成高度图", 1.0f); Transform SceneHeightRoot = GameObject.Find("HeightMap").transform; if (SceneHeightRoot == null) { Debug.LogError("没有高度物体"); mapInfo.ConsiderHeightMap = false; return; } int count = 1024; Texture2D heightMap = new Texture2D(count, count, TextureFormat.RG16, false, false); float xMin = mapInfo.heightMapOriX; float xMax = mapInfo.heightMapSizeX + xMin; float yMin = mapInfo.heightMapMinY; float yMax = float.MinValue; float zMin = mapInfo.heightMapOriZ; float zMax = zMin + mapInfo.heightMapSizeZ; List <Transform> transList = new List <Transform>(SceneHeightRoot.GetComponentsInChildren <Transform>()); foreach (var meshCollider in SceneHeightRoot.GetComponentsInChildren <MeshCollider>()) { Mesh mesh = meshCollider.sharedMesh; if (mesh == null) { continue; } Transform trans = meshCollider.transform; foreach (var vertex in mesh.vertices) { Vector3 worldPos = trans.TransformPoint(vertex); if (worldPos.x < xMin) { xMin = worldPos.x; } else if (worldPos.x > xMax) { xMax = worldPos.x; } if (worldPos.y < yMin) { yMin = worldPos.y; } else if (worldPos.y > yMax) { yMax = worldPos.y; } if (worldPos.z < zMin) { zMin = worldPos.z; } else if (worldPos.z > zMax) { zMax = worldPos.z; } } } foreach (var collider in SceneHeightRoot.GetComponentsInChildren <Collider>()) { if (collider is MeshCollider) { continue; } Vector3 minPos = collider.bounds.min; Vector3 maxPos = collider.bounds.max; if (minPos.x < xMin) { xMin = minPos.x; } if (maxPos.x > xMax) { xMax = maxPos.x; } if (minPos.y < yMin) { yMin = minPos.y; } if (maxPos.y > yMax) { yMax = maxPos.y; } if (minPos.z < zMin) { zMin = minPos.z; } if (maxPos.z > zMax) { zMax = maxPos.z; } } float deltaX = (xMax - xMin) / count; float deltaZ = (zMax - zMin) / count; float height = yMax - yMin; if (mapInfo != null) { mapInfo.heightMapOriX = xMin; mapInfo.heightMapOriZ = zMin; mapInfo.heightMapSizeX = xMax - xMin; mapInfo.heightMapSizeZ = zMax - zMin; mapInfo.heightMapMinY = yMin; mapInfo.heightMapSizeY = height; } bool[] isFindArr = new bool[count * count]; Color[] resetArr = new Color[count * count]; for (int z = 0; z < count; z++) { for (int x = 0; x < count; x++) { Vector3 pos = new Vector3(xMin + (x + 0.5f) * deltaX, yMax + 1.0f, zMin + (z + 0.5f) * deltaZ); heightMap.SetPixel(x, z, new Color(0, 0, 0)); RaycastHit[] hitArr = Physics.RaycastAll(pos, Vector3.down, height + 2.0f); isFindArr[x + z * count] = false; if (hitArr != null) { float maxHeight = yMin; foreach (var hit in hitArr) { if (transList.Contains(hit.transform)) { if (hit.point.y > maxHeight) { maxHeight = hit.point.y; isFindArr[x + z * count] = true; } } } float heightValue = (maxHeight - yMin) / height; ushort shortValue = (ushort)(heightValue * 65535.0f); byte[] byteArr = BitConverter.GetBytes(shortValue); //float rValue = (((int)(heightValue * 65536)) / 256) / 256.0f; //float gValue = (((int)(heightValue * 65536)) % 256) / 256.0f; heightMap.SetPixel(x, z, new Color32(byteArr[0], byteArr[1], 0, 0)); } } } //没有采样到高度信息的,值设置为周围2格有高度信息的,以避免边界误差 for (int z = 0; z < count; z++) { for (int x = 0; x < count; x++) { if (!isFindArr[x + z * count]) //如果这个像素没获取到高度 { Vector4 heightValue = Vector4.zero; int findCount = 0; for (int zNear = z - 5; zNear <= z + 5; zNear++) { if (zNear < 0 || zNear >= count) { continue; } for (int xNear = x - 5; xNear <= x + 5; xNear++) { if (xNear < 0 || xNear >= count) { continue; } if (isFindArr[xNear + zNear * count]) { heightValue += new Vector4(heightMap.GetPixel(xNear, zNear).r, heightMap.GetPixel(xNear, zNear).g, heightMap.GetPixel(xNear, zNear).b, 1); findCount++; } } } if (findCount > 1) { heightValue = heightValue / (float)findCount; } resetArr[x + z * count] = heightValue; } } } for (int z = 0; z < count; z++) { for (int x = 0; x < count; x++) { if (!isFindArr[x + z * count] && resetArr[x + z * count].r > 0.001f) { heightMap.SetPixel(x, z, resetArr[x + z * count]); } } } byte[] bytes = heightMap.EncodeToPNG(); string fullPath = Application.dataPath; fullPath = fullPath.Remove(fullPath.IndexOf("Assets")); fullPath = fullPath + fullPathName; File.WriteAllBytes(fullPathName, bytes); AssetDatabase.Refresh(); TextureImporter texImporter = TextureImporter.GetAtPath(fullPathName) as TextureImporter; if (texImporter != null) { TextureImporterPlatformSettings setting = new TextureImporterPlatformSettings(); setting.format = TextureImporterFormat.RG16; texImporter.SetPlatformTextureSettings(setting); texImporter.isReadable = true; texImporter.SaveAndReimport(); AssetDatabase.ImportAsset(fullPathName); } EditorUtility.ClearProgressBar(); }
/* uses badsource and badsink */ public override void Bad() { double data; if (privateFive == 5) { data = double.MinValue; /* Initialize data */ { File.Create("data.txt").Close(); StreamReader sr = null; try { /* read string from file into data */ sr = new StreamReader("data.txt"); /* FLAW: Read data from a file */ /* This will be reading the first "line" of the file, which * could be very long if there are little or no newlines in the file */ string stringNumber = sr.ReadLine(); if (stringNumber != null) /* avoid NPD incidental warnings */ { try { data = double.Parse(stringNumber.Trim()); } catch (FormatException exceptNumberFormat) { IO.Logger.Log(NLog.LogLevel.Warn, exceptNumberFormat, "Number format exception parsing data from string"); } } } catch (IOException exceptIO) { IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading"); } finally { /* Close stream reading objects */ try { if (sr != null) { sr.Close(); } } catch (IOException exceptIO) { IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error closing StreamReader"); } } } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = 0.0d; } { /* POTENTIAL FLAW: Convert data to a int, possibly causing a truncation error */ IO.WriteLine((int)data); } }
static void Main(string[] args) { var configuration = Environment.GetEnvironmentVariable("config"); configuration = string.IsNullOrEmpty(configuration) ? "debug" : configuration; Target("ci", DependsOn("connection", "default", "pack")); Target("default", DependsOn("mocha", "test", "storyteller")); Target("clean", () => EnsureDirectoriesDeleted("results", "artifacts")); Target("connection", () => File.WriteAllText("src/Marten.Testing/connection.txt", Environment.GetEnvironmentVariable("connection"))); Target("install", () => RunNpm("install")); Target("mocha", DependsOn("install"), () => RunNpm("run test")); Target("compile", DependsOn("clean"), () => Run("dotnet", $"build src/Marten.Testing/Marten.Testing.csproj --framework netcoreapp2.1 --configuration {configuration}")); Target("compile-noda-time", DependsOn("clean"), () => Run("dotnet", $"build src/Marten.NodaTime.Testing/Marten.NodaTime.Testing.csproj --framework netcoreapp2.1 --configuration {configuration}")); Target("test-noda-time", DependsOn("compile-noda-time"), () => Run("dotnet", $"test src/Marten.NodaTime.Testing/Marten.NodaTime.Testing.csproj --framework netcoreapp2.1 --configuration {configuration} --no-build")); Target("test-marten", DependsOn("compile", "test-noda-time"), () => Run("dotnet", $"test src/Marten.Testing/Marten.Testing.csproj --framework netcoreapp2.1 --configuration {configuration} --no-build")); Target("test", DependsOn("test-marten", "test-noda-time")); Target("storyteller", DependsOn("compile"), () => Run("dotnet", $"run --framework netcoreapp2.1 --culture en-US", "src/Marten.Storyteller")); Target("open_st", DependsOn("compile"), () => Run("dotnet", $"storyteller open --framework netcoreapp2.1 --culture en-US", "src/Marten.Storyteller")); Target("docs-restore", () => Run("dotnet", "restore", "tools/stdocs")); Target("docs", DependsOn("docs-restore"), () => RunStoryTellerDocs($"run -d ../../documentation -c ../../src -v {BUILD_VERSION}")); // Exports the documentation to jasperfx.github.io/marten - requires Git access to that repo though! Target("publish", () => { const string docTargetDir = "doc-target"; Run("git", $"clone -b gh-pages https://github.com/jasperfx/marten.git {InitializeDirectory(docTargetDir)}"); // if you are not using git --global config, un-comment the block below, update and use it // Run("git", "config user.email user_email", docTargetDir); // Run("git", "config user.name user_name", docTargetDir); RunStoryTellerDocs( $"export ../../{docTargetDir} ProjectWebsite -d ../../documentation -c ../../src -v {BUILD_VERSION} --project marten"); Run("git", "add --all", docTargetDir); Run("git", $"commit -a -m \"Documentation Update for {BUILD_VERSION}\" --allow-empty", docTargetDir); Run("git", "push origin gh-pages", docTargetDir); }); Target("benchmarks", () => Run("dotnet", "run --project src/MartenBenchmarks --configuration Release")); Target("recordbenchmarks", () => { var profile = Environment.GetEnvironmentVariable("profile"); if (!string.IsNullOrEmpty(profile)) { CopyDirectory("BenchmarkDotNet.Artifacts/results", InitializeDirectory($"benchmarks/{profile}")); } }); Target("pack", DependsOn("compile"), ForEach("./src/Marten", "./src/Marten.CommandLine", "./src/Marten.NodaTime"), project => Run("dotnet", $"pack {project} -o ./../../artifacts --configuration Release")); RunTargetsAndExit(args); }
/// <summary> /// Загружает настройки программы /// </summary> public static void LoadSettings() { if (AppSettings.TargetLanguage.IsNullOrEmpty()) AppSettings.TargetLanguage = "ru"; if (AppSettings.OnlineTranslator == Guid.Empty) AppSettings.OnlineTranslator = TranslateService.OnlineTranslators.First().Key; if (AppSettings.TranslatorServicesKeys == null) AppSettings.TranslatorServicesKeys = new Dictionary<Guid, string>(); if (AppSettings.LanguageOfApp.IsNullOrEmpty()) { SetLanguageOfApp( TranslateService.SupportedProgramLangs.FirstOrDefault(lang => lang == GetCurrentLanguage()) ?? TranslateService.SupportedProgramLangs.First() ); } else { SetLanguageOfApp(AppSettings.LanguageOfApp); } if (AppSettings.XmlRules == null || AppSettings.XmlRules.Count == 0) { AppSettings.XmlRules = new List<string> { "android:text", "android:title", "android:summary", "android:dialogTitle", "android:summaryOff", "android:summaryOn", "value" }; } if (AppSettings.AvailToEditFiles == null || AppSettings.AvailToEditFiles.Count == 0) { AppSettings.AvailToEditFiles = new List<string> {".xml", ".smali"}; } if (AppSettings.ImageExtensions == null || AppSettings.ImageExtensions.Count == 0 || AppSettings.ImageExtensions.Count == 1 && AppSettings.ImageExtensions[0].IsNullOrEmpty()) { AppSettings.ImageExtensions = new List<string> {".png", ".jpg", ".jpeg"}; } if (AppSettings.OtherExtensions == null) AppSettings.OtherExtensions = new List<string>(); if (AppSettings.XmlRules != null) XmlFile.XmlRules = AppSettings.XmlRules.Select(it => new Regex(it)).ToList(); if (AppSettings.Theme.IsNullOrEmpty() || GlobalVariables.Themes.All(theme => theme.name != AppSettings.Theme)) AppSettings.Theme = GlobalVariables.Themes.First().name; ThemeUtils.ChangeTheme(AppSettings.Theme); string apktoolVersion = AppSettings.ApktoolVersion; if (apktoolVersion.IsNullOrEmpty() || !File.Exists(Path.Combine(GlobalVariables.PathToApktoolVersions, $"apktool_{apktoolVersion}.jar"))) { if (Directory.Exists(GlobalVariables.PathToApktoolVersions)) { string vers = Directory.EnumerateFiles(GlobalVariables.PathToApktoolVersions, "*.jar").LastOrDefault(); if (vers != null) { AppSettings.ApktoolVersion = Path.GetFileNameWithoutExtension(vers).SplitRemove("apktool_")[0]; } } } TranslateService.ReloadItems(); UpdateApiKeys(); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: public void verifyContent(java.io.File storeFile) throws java.io.IOException public override void VerifyContent( File storeFile ) { PageCache pageCache = _pageCacheRule.getPageCache( GlobalFs.get() ); using ( GBPTree<MutableLong, MutableLong> tree = ( new GBPTreeBuilder<MutableLong, MutableLong>( pageCache, storeFile, Layout ) ).build() ) { { // WHEN reading from the tree // THEN initial keys should be there tree.ConsistencyCheck(); using ( RawCursor<Hit<MutableLong, MutableLong>, IOException> cursor = tree.Seek( Layout.key( 0 ), Layout.key( long.MaxValue ) ) ) { foreach ( long? expectedKey in _initialKeys ) { AssertHit( cursor, expectedKey ); } assertFalse( cursor.Next() ); } } { // WHEN writing more to the tree // THEN we should not see any format conflicts using ( Writer<MutableLong, MutableLong> writer = tree.Writer() ) { while ( _keysToAdd.Count > 0 ) { int next = _random.Next( _keysToAdd.Count ); Put( writer, _keysToAdd[next] ); _keysToAdd.RemoveAt( next ); } } } { // WHEN reading from the tree again // THEN all keys including newly added should be there tree.ConsistencyCheck(); using ( RawCursor<Hit<MutableLong, MutableLong>, IOException> cursor = tree.Seek( Layout.key( 0 ), Layout.key( 2 * INITIAL_KEY_COUNT ) ) ) { foreach ( long? expectedKey in _allKeys ) { AssertHit( cursor, expectedKey ); } assertFalse( cursor.Next() ); } } { // WHEN randomly removing half of tree content // THEN we should not see any format conflicts using ( Writer<MutableLong, MutableLong> writer = tree.Writer() ) { int size = _allKeys.Count; while ( _allKeys.Count > size / 2 ) { int next = _random.Next( _allKeys.Count ); MutableLong key = Layout.key( _allKeys[next] ); writer.Remove( key ); _allKeys.RemoveAt( next ); } } } { // WHEN reading from the tree after remove // THEN we should see everything that is left in the tree tree.ConsistencyCheck(); using ( RawCursor<Hit<MutableLong, MutableLong>, IOException> cursor = tree.Seek( Layout.key( 0 ), Layout.key( 2 * INITIAL_KEY_COUNT ) ) ) { foreach ( long? expectedKey in _allKeys ) { AssertHit( cursor, expectedKey ); } assertFalse( cursor.Next() ); } } } }
//Converts the csv file into a 2d array public void InitialiseGrid(bool isAssay) { //ASSAY is just _pc and Other, and is used with simplex grid = SplitCsvGrid(csvFile); int gridHeight = 1 + grid.GetUpperBound(1); bool CompilingDatabase = false; if (CompilingDatabase) { StringBuilder sb = new StringBuilder(); Debug.Log("<color/red>making the database</color>"); bool itIsAssay = false; for (int y = 1; y <= grid.GetUpperBound(1); y++) { string sample = grid[0, y]; string assayWeight = grid[1, y]; string combiWeight = grid[24, y]; if (itIsAssay) { sb.AppendLine(""); sb.AppendLine("mineralComp = \"" + sample + "\";"); sb.AppendLine("AMC = new AssayMineralComposition(mineralComp);"); sb.AppendLine("assayMineralDict.Add(mineralComp, AMC);"); sb.AppendLine("FillAMCDatabase(AMC, new double[] { " + grid[2, y] + ", " + grid[3, y] + ", " + grid[4, y] + ", " + grid[5, y] + ", " + grid[6, y] + ", " + grid[7, y] + ", " + grid[8, y] + ", " + grid[9, y] + ", " + grid[10, y] + ", " + grid[11, y] + ", " + grid[12, y] + ", " + grid[13, y] + ", " + grid[14, y] + ", " + grid[15, y] + ", " + grid[16, y] + ", " + grid[17, y] + ", " + grid[18, y] + ", " + grid[19, y] + ", " + grid[20, y] + ", " + grid[21, y] + ", " + grid[22, y] + " });"); sb.AppendLine("AMC.weight = " + assayWeight + ";"); } else { sb.AppendLine(""); sb.AppendLine("mineralComp = \"" + sample + "\";"); sb.AppendLine("CMC = new CombiMineralComposition(mineralComp);"); sb.AppendLine("combiMineralDict.Add(mineralComp, CMC);"); sb.AppendLine("FillCMCDatabase(CMC, new double[] { " + grid[2, y] + ", " + grid[3, y] + ", " + grid[4, y] + ", " + grid[5, y] + ", " + grid[6, y] + ", " + grid[7, y] + ", " + grid[8, y] + ", " + grid[9, y] + ", " + grid[10, y] + ", " + grid[11, y] + ", " + grid[12, y] + ", " + grid[13, y] + ", " + grid[14, y] + ", " + grid[15, y] + ", " + grid[16, y] + ", " + grid[17, y] + ", " + grid[18, y] + ", " + grid[19, y] + ", " + grid[20, y] + ", " + grid[21, y] + ", " + grid[22, y] + " });"); sb.AppendLine("CMC.weight = " + combiWeight + ";"); } } string filename = System.Environment.CurrentDirectory + "/thing.txt"; Debug.Log(filename); using (StreamWriter sw = File.CreateText(filename)) { sw.Write(sb.ToString()); } return; } //GetElements(grid); //ppm //GetChemicals(grid); //pc or wt% GetSamples(grid); //Debug.Log("elements/chemicals/samples: " + ElementCheckFailed + "/" + ChemicalCheckFailed + "/" + SampleCheckFailed); assayMode = isAssay; both.Initialise(isAssay); //Debug.Log("size = " + (1 + grid.GetUpperBound(0)) + "," + (gridHeight)); //NorthValues = new float[gridHeight - 1]; //EastValues = new float[gridHeight - 1]; //ElevValues = new float[gridHeight - 1]; /*for (int y = 0; y <= grid.GetUpperBound(1); y++) { Debug.Log("line " + y + ": "); DebugRow(grid, y); }*/ //DebugOutputGrid(grid); //GetUTMCoords(grid); //if (UTMCheckFailed) // return; //GetElements(grid); //if (ElementCheckFailed) // return; //GetListOfMaterials(grid); //GetListOfDeposits(grid); //GetUniqueIDs(grid); }
public static void Import(CarSystemDbContext dbContext) { var carsToAdd = Directory .GetFiles(Directory.GetCurrentDirectory() + "/JsonFiles/") .Where(f => f.EndsWith(".json")) .Select(f => File.ReadAllText(f)) .SelectMany(str => JsonConvert.DeserializeObject <IEnumerable <CarJsonModel> >(str)) .ToList(); var citiesToAdd = new HashSet <string>(); var manufacturerToAdd = new HashSet <string>(); var DealarsToAdd = new HashSet <string>(); foreach (var car in carsToAdd) { citiesToAdd.Add(car.Dealer.City); manufacturerToAdd.Add(car.ManufacturerName); DealarsToAdd.Add(car.Dealer.Name); } foreach (var cityName in citiesToAdd) { var city = new City() { Name = cityName }; dbContext.Cities.Add(city); } foreach (var manufactureName in manufacturerToAdd) { var manufacturer = new Manufacturer() { Name = manufactureName }; dbContext.Manufacturers.Add(manufacturer); } foreach (var dealerName in DealarsToAdd) { var dealer = new Dealer() { Name = dealerName }; dbContext.Dealers.Add(dealer); } dbContext.SaveChanges(); var counter = 0; foreach (var carToAdd in carsToAdd) { dbContext.Configuration.AutoDetectChangesEnabled = false; dbContext.Configuration.ValidateOnSaveEnabled = false; var dbCity = dbContext.Cities.Where(c => c.Name == carToAdd.Dealer.City).SingleOrDefault(); var dbDealer = dbContext.Dealers.Where(d => d.Name == carToAdd.Dealer.Name).SingleOrDefault(); if (!dbDealer.Cities.Any(c => c.Name == dbCity.Name)) { dbDealer.Cities.Add(dbCity); } var car = new Car { Model = carToAdd.Model, Manufacturer = dbContext.Manufacturers.Where(m => m.Name == carToAdd.ManufacturerName).SingleOrDefault(), Transmitiontype = (TransmitionType)carToAdd.TransmissionType, Year = carToAdd.Year, Price = carToAdd.Price, Dealer = dbDealer }; dbContext.Cars.Add(car); counter++; if (counter % 100 == 0) { System.Console.Write("*"); } } dbContext.SaveChanges(); }
private (int, string) InterpretScriptClasses() { List<string> importedClasses = new List<string>(); List<string> importedEnums = new List<string>(); string output = ""; using (StringWriter sw = new StringWriter()) { // usings and namespace sw.WriteLine(header); FileInfo[] projectScriptFiles = m_projectinfo.GetFiles("*.ws", SearchOption.AllDirectories); sw.WriteLine("\tpublic static partial class Enums"); sw.WriteLine("\t{\r\n"); // interpret enums #region Enums foreach (var file in projectScriptFiles) { int depth = 0; bool isReading = false; string enumname = ""; string enumstring = ""; var lines = File.ReadLines(file.FullName); foreach (var line in lines) { // check if should start reading if (line.Contains("enum ")) { // interpret line string intline = InterpretEnumLine(line, ref enumname); if (!string.IsNullOrEmpty(intline)) { // check if enum is vanilla if (AssemblyDictionary.EnumExists(enumname)) continue; if (importedEnums.Contains(enumname)) continue; enumstring += $"\t{intline}\r\n"; isReading = true; } // increment or decrement the depth depth += line.Count(_ => _ == '{'); depth -= line.Count(_ => _ == '}'); continue; } // if reading, interpret results if (isReading) { // increment or decrement the depth depth += line.Count(_ => _ == '{'); depth -= line.Count(_ => _ == '}'); // only interpret variables at depth 1 (from the class depth) if (depth == 1) { if (!string.IsNullOrEmpty(line)) { var iline = InterpretEnumVarLine(line); if (!string.IsNullOrEmpty(iline)) { enumstring += $"\t\t\t{iline}\r\n"; } } } // if depth is 0 again, stop reading and write to output if (depth == 0) { sw.WriteLine(enumstring); sw.WriteLine("\t\t}"); isReading = false; enumstring = ""; importedEnums.Add(enumname); } } } } #endregion Enums sw.WriteLine("\t}\r\n"); // interpret classes #region Classes foreach (var file in projectScriptFiles) { int depth = 0; bool isReading = false; int varcounter = 0; string classname = ""; string classstring = ""; var lines = File.ReadLines(file.FullName); foreach (var line in lines) { // check if should start reading if (line.Contains("class ")) { // interpret line string intline = InterpretClassLine(line, ref classname); if (!string.IsNullOrEmpty(intline)) { // check if class is vanilla if (AssemblyDictionary.TypeExists(classname)) continue; if (importedClasses.Contains(classname)) continue; classstring += $"{intline}\r\n"; isReading = true; } // increment or decrement the depth depth += line.Count(_ => _ == '{'); depth -= line.Count(_ => _ == '}'); continue; } // if reading, interpret results if (isReading) { // increment or decrement the depth depth += line.Count(_ => _ == '{'); depth -= line.Count(_ => _ == '}'); // only interpret variables at depth 1 (from the class depth) if (depth == 1) { string intline = InterpretVarLine(line, varcounter, importedEnums); if (!string.IsNullOrEmpty(intline)) { classstring += $"{intline}"; varcounter++; } } // if depth is 0 again, stop reading and write to output if (depth == 0) { sw.WriteLine(classstring); sw.WriteLine(funcCtor(classname)); sw.WriteLine(footer); varcounter = 0; isReading = false; classstring = ""; importedClasses.Add(classname); } } } } #endregion Classes // namespace end sw.WriteLine("}"); output = sw.ToString(); } if (importedClasses.Count > 0) { _loggerService.LogString($"Sucessfully parsed {importedClasses.Count} custom classes: " + $"{string.Join(", ", importedClasses)}", Logtype.Success); } return (importedClasses.Count, output); }
public async Task Configure(DeviceProvisioningMethod method, Option <string> agentImage, string hostname, string deviceCaCert, string deviceCaPk, string deviceCaCerts, LogLevel runtimeLogLevel) { agentImage.ForEach( image => { Console.WriteLine($"Setting up iotedged with agent image {image}"); }, () => { Console.WriteLine("Setting up iotedged with agent image 1.0"); }); const string YamlPath = "/etc/iotedge/config.yaml"; Task <string> text = File.ReadAllTextAsync(YamlPath); var doc = new YamlDocument(await text); method.ManualConnectionString.Match( cs => { doc.ReplaceOrAdd("provisioning.device_connection_string", cs); return(string.Empty); }, () => { doc.Remove("provisioning.device_connection_string"); return(string.Empty); }); method.Dps.ForEach( dps => { doc.ReplaceOrAdd("provisioning.source", "dps"); doc.ReplaceOrAdd("provisioning.global_endpoint", dps.EndPoint); doc.ReplaceOrAdd("provisioning.scope_id", dps.ScopeId); switch (dps.AttestationType) { case DPSAttestationType.SymmetricKey: doc.ReplaceOrAdd("provisioning.attestation.method", "symmetric_key"); doc.ReplaceOrAdd("provisioning.attestation.symmetric_key", dps.SymmetricKey.Expect(() => new ArgumentException("Expected symmetric key"))); break; case DPSAttestationType.X509: var certUri = new Uri(dps.DeviceIdentityCertificate.Expect(() => new ArgumentException("Expected path to identity certificate"))); var keyUri = new Uri(dps.DeviceIdentityPrivateKey.Expect(() => new ArgumentException("Expected path to identity private key"))); doc.ReplaceOrAdd("provisioning.attestation.method", "x509"); doc.ReplaceOrAdd("provisioning.attestation.identity_cert", certUri.AbsoluteUri); doc.ReplaceOrAdd("provisioning.attestation.identity_pk", keyUri.AbsoluteUri); break; default: doc.ReplaceOrAdd("provisioning.attestation.method", "tpm"); break; } dps.RegistrationId.ForEach(id => { doc.ReplaceOrAdd("provisioning.attestation.registration_id", id); }); }); agentImage.ForEach(image => { doc.ReplaceOrAdd("agent.config.image", image); }); doc.ReplaceOrAdd("hostname", hostname); foreach (RegistryCredentials c in this.credentials) { doc.ReplaceOrAdd("agent.config.auth.serveraddress", c.Address); doc.ReplaceOrAdd("agent.config.auth.username", c.User); doc.ReplaceOrAdd("agent.config.auth.password", c.Password); } doc.ReplaceOrAdd("agent.env.RuntimeLogLevel", runtimeLogLevel.ToString()); if (this.httpUris.HasValue) { HttpUris uris = this.httpUris.OrDefault(); doc.ReplaceOrAdd("connect.management_uri", uris.ConnectManagement); doc.ReplaceOrAdd("connect.workload_uri", uris.ConnectWorkload); doc.ReplaceOrAdd("listen.management_uri", uris.ListenManagement); doc.ReplaceOrAdd("listen.workload_uri", uris.ListenWorkload); } else { UriSocks socks = this.uriSocks; doc.ReplaceOrAdd("connect.management_uri", socks.ConnectManagement); doc.ReplaceOrAdd("connect.workload_uri", socks.ConnectWorkload); doc.ReplaceOrAdd("listen.management_uri", socks.ListenManagement); doc.ReplaceOrAdd("listen.workload_uri", socks.ListenWorkload); } if (!string.IsNullOrEmpty(deviceCaCert) && !string.IsNullOrEmpty(deviceCaPk) && !string.IsNullOrEmpty(deviceCaCerts)) { doc.ReplaceOrAdd("certificates.device_ca_cert", deviceCaCert); doc.ReplaceOrAdd("certificates.device_ca_pk", deviceCaPk); doc.ReplaceOrAdd("certificates.trusted_ca_certs", deviceCaCerts); } this.proxy.ForEach(proxy => doc.ReplaceOrAdd("agent.env.https_proxy", proxy)); this.upstreamProtocol.ForEach(upstreamProtocol => doc.ReplaceOrAdd("agent.env.UpstreamProtocol", upstreamProtocol.ToString())); string result = doc.ToString(); FileAttributes attr = 0; if (File.Exists(YamlPath)) { attr = File.GetAttributes(YamlPath); File.SetAttributes(YamlPath, attr & ~FileAttributes.ReadOnly); } await File.WriteAllTextAsync(YamlPath, result); if (attr != 0) { File.SetAttributes(YamlPath, attr); } }
public static string[] ChangeName(int location, string[] menuItems, string newName, string menu) { WriteLine($"Replacing {menuItems[location].Trim()} with {newName} now..."); string text = ""; menu = menu.ToLower(); int size = 0; foreach (var item in menuItems) { if (item.Length > size) { size = item.Length; } } size += 5; for (var i = 1; i < menuItems.Length; i++) { int numSpaces = 0; var item = menuItems[i].Trim(); string space = ""; if (i == location) { numSpaces = size - newName.Length; if (numSpaces == 0) { size += 5; numSpaces = 5; } for (var j = 0; j < numSpaces; j++) { space += " "; } text += "-" + newName + space; menuItems[i] = newName + space; } else { space = ""; numSpaces = size - item.Length; if (numSpaces == 0) { size += 5; numSpaces = 5; } for (var j = 0; j < numSpaces; j++) { space += " "; } text += "-" + item + space; } } if (menu == "breakfast") { File.WriteAllText(@"C:\Users\Kiosk Records\Menus and Prices\Breakfast Items.txt", text); } else if (menu == "lunch") { File.WriteAllText(@"C:\Users\Kiosk Records\Menus and Prices\Lunch Items.txt", text); } else if (menu == "dinner") { File.WriteAllText(@"C:\Users\Kiosk Records\Menus and Prices\Dinner Items.txt", text); } WriteLine("The name has been changed."); return(menuItems); }
private void lvwOutbox_DrawSubItem(object sender, DrawListViewSubItemEventArgs e) { TextFormatFlags flags = TextFormatFlags.Left; using (StringFormat sf = new StringFormat()) { // Store the column text alignment, letting it default // to Left if it has not been set to Center or Right. switch (e.Header.TextAlign) { case HorizontalAlignment.Center: sf.Alignment = StringAlignment.Center; flags = TextFormatFlags.HorizontalCenter; break; case HorizontalAlignment.Right: sf.Alignment = StringAlignment.Far; flags = TextFormatFlags.Right; break; } if (((e.ItemState & ListViewItemStates.Focused) != 0) && ((e.ItemState & ListViewItemStates.Selected) != 0) && (lvwOutbox.SelectedIndices.Count > 0) ) { //e.DrawBackground(); e.Graphics.DrawString(e.SubItem.Text, this.Font, Brushes.White, e.Bounds, sf); } else { e.Graphics.DrawString(e.SubItem.Text, this.Font, Brushes.Black, e.Bounds, sf); } if (e.ColumnIndex == 0) { // Draw the subitem text in red to highlight it. //e.Graphics.DrawString(e.SubItem.Text, this.Font, Brushes.Red, e.Bounds, sf); if (e.Item.ImageIndex != -1) { e.Graphics.DrawImage(e.Item.ImageList.Images[e.Item.ImageIndex], e.SubItem.Bounds.Location); } ShuratHaklada shurat_haklada = (ShuratHaklada)lvwOutbox.Items[e.ItemIndex].Tag; if (File.Exists(shurat_haklada.Attachment)) { Point pt = new Point(e.SubItem.Bounds.Location.X + e.Item.ImageList.Images[0].Width, e.SubItem.Bounds.Location.Y); e.Graphics.DrawImage(e.Item.ImageList.Images[5], pt); } } else { // Draw normal text for a subitem with a nonnegative // or nonnumerical value. //e.DrawText(flags); } } //TextFormatFlags flags = TextFormatFlags.Left; //using (StringFormat sf = new StringFormat()) //{ // // Store the column text alignment, letting it default // // to Left if it has not been set to Center or Right. // switch (e.Header.TextAlign) // { // case HorizontalAlignment.Center: // sf.Alignment = StringAlignment.Center; // flags = TextFormatFlags.HorizontalCenter; // break; // case HorizontalAlignment.Right: // sf.Alignment = StringAlignment.Far; // flags = TextFormatFlags.Right; // break; // } // // Unless the item is selected, draw the standard // // background to make it stand out from the gradient. // //if ((e.ItemState & ListViewItemStates.Selected) == 0) // //{ // // e.DrawBackground(); // //} // //if (e.ColumnIndex == 0) // //{ // if (((e.ItemState & ListViewItemStates.Focused) != 0) && // ((e.ItemState & ListViewItemStates.Selected) != 0) && // (lvwOutbox.SelectedIndices.Count > 0) // ) // { // // Draw the subitem text in red to highlight it. // e.Graphics.DrawString(e.SubItem.Text, lvwOutbox.Font, Brushes.Red, e.Bounds, sf); // if (e.Item.ImageIndex != -1) // { // e.Graphics.DrawImage(e.Item.ImageList.Images[e.Item.ImageIndex], e.SubItem.Bounds.Location); // } // ShuratHaklada shurat_haklada = (ShuratHaklada)lvwOutbox.Items[e.ItemIndex].Tag; // if (File.Exists(shurat_haklada.Attachment)) // { // Point pt = new Point(e.SubItem.Bounds.Location.X + e.Item.ImageList.Images[0].Width, e.SubItem.Bounds.Location.Y); // e.Graphics.DrawImage(e.Item.ImageList.Images[5], pt); // } // } // else // { // // Draw normal text for a subitem // //e.DrawText(flags); // } //} }
private void DumpStacktrace(ZipArchive package) { var stacktraceRequsted = GetQueryStringValue("stacktrace"); if (stacktraceRequsted != null) { var stacktrace = package.CreateEntry("stacktraces.txt", CompressionLevel.Optimal); var jsonSerializer = JsonExtensions.CreateDefaultJsonSerializer(); jsonSerializer.Formatting = Formatting.Indented; using (var stacktraceStream = stacktrace.Open()) { string ravenDebugDir = null; try { if (Debugger.IsAttached) { throw new InvalidOperationException("Cannot get stacktraces when debugger is attached"); } ravenDebugDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); var ravenDebugExe = Path.Combine(ravenDebugDir, "Raven.Debug.exe"); var ravenDebugOutput = Path.Combine(ravenDebugDir, "stacktraces.txt"); Directory.CreateDirectory(ravenDebugDir); if (Environment.Is64BitProcess) { ExtractResource("Raven.Database.Util.Raven.Debug.x64.Raven.Debug.exe", ravenDebugExe); } else { ExtractResource("Raven.Database.Util.Raven.Debug.x86.Raven.Debug.exe", ravenDebugExe); } var process = new Process { StartInfo = new ProcessStartInfo { Arguments = string.Format("-pid={0} /stacktrace -output={1}", Process.GetCurrentProcess().Id, ravenDebugOutput), FileName = ravenDebugExe, WindowStyle = ProcessWindowStyle.Hidden, } }; process.Start(); process.WaitForExit(); if (process.ExitCode != 0) { throw new InvalidOperationException("Raven.Debug exit code is: " + process.ExitCode); } using (var stackDumpOutputStream = File.Open(ravenDebugOutput, FileMode.Open)) { stackDumpOutputStream.CopyTo(stacktraceStream); } } catch (Exception ex) { var streamWriter = new StreamWriter(stacktraceStream); jsonSerializer.Serialize(streamWriter, new { Error = "Exception occurred during getting stacktraces of the RavenDB process. Exception: " + ex }); streamWriter.Flush(); } finally { if (ravenDebugDir != null && Directory.Exists(ravenDebugDir)) { IOExtensions.DeleteDirectory(ravenDebugDir); } } stacktraceStream.Flush(); } } }
/// <summary> /// Save title and description of media file info. /// </summary> /// <param name="fileName">File name</param> /// <param name="title">Title</param> /// <param name="description">Description</param> private bool metaDataEditor_Save(string fileName, string title, string description) { bool saved = false; if (mediaFileInfo != null) { try { if (mediaFileInfo.FileName != fileName) { // Get original file path string extension = mediaFileInfo.FileExtension; // New file path string newPath = DirectoryHelper.CombinePath(Path.GetDirectoryName(mediaFileInfo.FilePath), fileName + extension); string newFullPath = MediaFileInfoProvider.GetMediaFilePath(mediaFileInfo.FileLibraryID, newPath); string newExtension = Path.GetExtension(newPath); if (!String.IsNullOrEmpty(newExtension)) { newExtension = newExtension.TrimStart('.'); } if (!MediaLibraryHelper.IsExtensionAllowed(newExtension)) { // New extension is not allowed metaDataEditor.ShowError(GetString("dialogs.filesystem.NotAllowedExtension").Replace("%%extensions%%", MediaLibraryHelper.GetAllowedExtensions(SiteName).TrimEnd(';').Replace(";", ", "))); return false; } // Rename file if (!File.Exists(newFullPath)) { MediaFileInfoProvider.MoveMediaFile(SiteName, mediaFileInfo.FileLibraryID, mediaFileInfo.FilePath, newPath); // Move preview file if exists if (MediaLibraryHelper.HasPreview(SiteName, mediaFileInfo.FileLibraryID, mediaFileInfo.FilePath)) { MediaLibraryHelper.MoveMediaFilePreview(mediaFileInfo, fileName + extension); } } else { // File already exists. metaDataEditor.ShowError(GetString("img.errors.fileexists")); return false; } mediaFileInfo.FileName = fileName; string subFolderPath = null; int lastSlash = mediaFileInfo.FilePath.LastIndexOfCSafe('/'); if (lastSlash > 0) { subFolderPath = mediaFileInfo.FilePath.Substring(0, lastSlash); } if (!string.IsNullOrEmpty(subFolderPath)) { mediaFileInfo.FilePath = String.Format("{0}/{1}{2}", subFolderPath, fileName, extension); } else { mediaFileInfo.FilePath = fileName + extension; } } mediaFileInfo.FileTitle = title; mediaFileInfo.FileDescription = description; // Save new data mediaFileInfo.EnsureUniqueFileName(false); MediaFileInfo.Provider.Set(mediaFileInfo); saved = true; } catch (Exception ex) { metaDataEditor.ShowError(GetString("metadata.errors.processing")); Service.Resolve<IEventLogService>().LogException("Metadata editor", "SAVE", ex); } } return saved; }
public void Save() { File.WriteAllText(ConfigPath, JsonConvert.SerializeObject(this, Formatting.Indented)); }
public async Task <HttpResponseMessage> Restore() { if (EnsureSystemDatabase() == false) { return(GetMessageWithString("Restore is only possible from the system database", HttpStatusCode.BadRequest)); } var restoreStatus = new RestoreStatus { State = RestoreStatusState.Running, Messages = new List <string>() }; var restoreRequest = await ReadJsonObjectAsync <DatabaseRestoreRequest>(); DatabaseDocument databaseDocument = null; var databaseDocumentPath = MaintenanceActions.FindDatabaseDocument(restoreRequest.BackupLocation); if (File.Exists(databaseDocumentPath)) { var databaseDocumentText = File.ReadAllText(databaseDocumentPath); databaseDocument = RavenJObject.Parse(databaseDocumentText).JsonDeserialization <DatabaseDocument>(); } var databaseName = !string.IsNullOrWhiteSpace(restoreRequest.DatabaseName) ? restoreRequest.DatabaseName : databaseDocument == null ? null : databaseDocument.Id; if (string.IsNullOrWhiteSpace(databaseName)) { var errorMessage = (databaseDocument == null || String.IsNullOrWhiteSpace(databaseDocument.Id)) ? "Database.Document file is invalid - database name was not found and not supplied in the request (Id property is missing or null). This is probably a bug - should never happen." : "A database name must be supplied if the restore location does not contain a valid Database.Document file"; restoreStatus.Messages.Add(errorMessage); DatabasesLandlord.SystemDatabase.Documents.Put(RestoreStatus.RavenRestoreStatusDocumentKey, null, RavenJObject.FromObject(new { restoreStatus }), new RavenJObject(), null); return(GetMessageWithString(errorMessage, HttpStatusCode.BadRequest)); } if (databaseName == Constants.SystemDatabase) { return(GetMessageWithString("Cannot do an online restore for the <system> database", HttpStatusCode.BadRequest)); } var existingDatabase = Database.Documents.GetDocumentMetadata("Raven/Databases/" + databaseName, null); if (existingDatabase != null) { return(GetMessageWithString("Cannot do an online restore for an existing database, delete the database " + databaseName + " and restore again.", HttpStatusCode.BadRequest)); } var ravenConfiguration = new RavenConfiguration { DatabaseName = databaseName, IsTenantDatabase = true }; if (databaseDocument != null) { foreach (var setting in databaseDocument.Settings) { ravenConfiguration.Settings[setting.Key] = setting.Value; } } if (File.Exists(Path.Combine(restoreRequest.BackupLocation, BackupMethods.Filename))) { ravenConfiguration.DefaultStorageTypeName = typeof(Raven.Storage.Voron.TransactionalStorage).AssemblyQualifiedName; } else if (Directory.Exists(Path.Combine(restoreRequest.BackupLocation, "new"))) { ravenConfiguration.DefaultStorageTypeName = typeof(Raven.Storage.Esent.TransactionalStorage).AssemblyQualifiedName; } ravenConfiguration.CustomizeValuesForDatabaseTenant(databaseName); ravenConfiguration.Initialize(); string documentDataDir; ravenConfiguration.DataDirectory = ResolveTenantDataDirectory(restoreRequest.DatabaseLocation, databaseName, out documentDataDir); restoreRequest.DatabaseLocation = ravenConfiguration.DataDirectory; string anotherRestoreResourceName; if (IsAnotherRestoreInProgress(out anotherRestoreResourceName)) { if (restoreRequest.RestoreStartTimeout.HasValue) { try { using (var cts = new CancellationTokenSource()) { cts.CancelAfter(TimeSpan.FromSeconds(restoreRequest.RestoreStartTimeout.Value)); var token = cts.Token; do { await Task.Delay(500, token); }while (IsAnotherRestoreInProgress(out anotherRestoreResourceName)); } } catch (OperationCanceledException) { return(GetMessageWithString(string.Format("Another restore is still in progress (resource name = {0}). Waited {1} seconds for other restore to complete.", anotherRestoreResourceName, restoreRequest.RestoreStartTimeout.Value), HttpStatusCode.ServiceUnavailable)); } } else { return(GetMessageWithString(string.Format("Another restore is in progress (resource name = {0})", anotherRestoreResourceName), HttpStatusCode.ServiceUnavailable)); } } Database.Documents.Put(RestoreInProgress.RavenRestoreInProgressDocumentKey, null, RavenJObject.FromObject(new RestoreInProgress { Resource = databaseName }), new RavenJObject(), null); DatabasesLandlord.SystemDatabase.Documents.Delete(RestoreStatus.RavenRestoreStatusDocumentKey, null, null); bool defrag; if (bool.TryParse(GetQueryStringValue("defrag"), out defrag)) { restoreRequest.Defrag = defrag; } var task = Task.Factory.StartNew(() => { try { MaintenanceActions.Restore(ravenConfiguration, restoreRequest, msg => { restoreStatus.Messages.Add(msg); DatabasesLandlord.SystemDatabase.Documents.Put(RestoreStatus.RavenRestoreStatusDocumentKey, null, RavenJObject.FromObject(restoreStatus), new RavenJObject(), null); }); if (databaseDocument == null) { return; } databaseDocument.Settings[Constants.RavenDataDir] = documentDataDir; if (restoreRequest.IndexesLocation != null) { databaseDocument.Settings[Constants.RavenIndexPath] = restoreRequest.IndexesLocation; } if (restoreRequest.JournalsLocation != null) { databaseDocument.Settings[Constants.RavenTxJournalPath] = restoreRequest.JournalsLocation; } bool replicationBundleRemoved = false; if (restoreRequest.DisableReplicationDestinations) { replicationBundleRemoved = TryRemoveReplicationBundle(databaseDocument); } databaseDocument.Id = databaseName; DatabasesLandlord.Protect(databaseDocument); DatabasesLandlord .SystemDatabase .Documents .Put("Raven/Databases/" + databaseName, null, RavenJObject.FromObject(databaseDocument), new RavenJObject(), null); restoreStatus.Messages.Add("The new database was created"); restoreStatus.State = RestoreStatusState.Completed; DatabasesLandlord.SystemDatabase.Documents.Put(RestoreStatus.RavenRestoreStatusDocumentKey, null, RavenJObject.FromObject(restoreStatus), new RavenJObject(), null); if (restoreRequest.GenerateNewDatabaseId) { GenerateNewDatabaseId(databaseName); } if (replicationBundleRemoved) { AddReplicationBundleAndDisableReplicationDestinations(databaseName); } } catch (Exception e) { restoreStatus.State = RestoreStatusState.Faulted; restoreStatus.Messages.Add("Unable to restore database " + e.Message); DatabasesLandlord.SystemDatabase.Documents.Put(RestoreStatus.RavenRestoreStatusDocumentKey, null, RavenJObject.FromObject(restoreStatus), new RavenJObject(), null); throw; } finally { Database.Documents.Delete(RestoreInProgress.RavenRestoreInProgressDocumentKey, null, null); } }, TaskCreationOptions.LongRunning); long id; Database.Tasks.AddTask(task, new TaskBasedOperationState(task), new TaskActions.PendingTaskDescription { StartTime = SystemTime.UtcNow, TaskType = TaskActions.PendingTaskType.RestoreDatabase, Payload = "Restoring database " + databaseName + " from " + restoreRequest.BackupLocation }, out id); return(GetMessageWithObject(new { OperationId = id })); }
private void ImportWizardVirtualEnvWorker( PythonVersion python, string venvModuleName, string expectedFile, bool brokenBaseInterpreter ) { var mockService = new MockInterpreterOptionsService(); mockService.AddProvider(new MockPythonInterpreterFactoryProvider("Test Provider", new MockPythonInterpreterFactory(python.Id, "Test Python", python.Configuration) )); using (var wpf = new WpfProxy()) { var settings = wpf.Create(() => new ImportSettings(mockService)); var sourcePath = TestData.GetTempPath(randomSubPath: true); // Create a fake set of files to import File.WriteAllText(Path.Combine(sourcePath, "main.py"), ""); Directory.CreateDirectory(Path.Combine(sourcePath, "A")); File.WriteAllText(Path.Combine(sourcePath, "A", "__init__.py"), ""); // Create a real virtualenv environment to import using (var p = ProcessOutput.RunHiddenAndCapture(python.InterpreterPath, "-m", venvModuleName, Path.Combine(sourcePath, "env"))) { Console.WriteLine(p.Arguments); p.Wait(); Console.WriteLine(string.Join(Environment.NewLine, p.StandardOutputLines.Concat(p.StandardErrorLines))); Assert.AreEqual(0, p.ExitCode); } if (brokenBaseInterpreter) { var cfgPath = Path.Combine(sourcePath, "env", "Lib", "orig-prefix.txt"); if (File.Exists(cfgPath)) { File.WriteAllText(cfgPath, string.Format("C:\\{0:N}", Guid.NewGuid())); } else if (File.Exists((cfgPath = Path.Combine(sourcePath, "env", "pyvenv.cfg")))) { File.WriteAllLines(cfgPath, File.ReadAllLines(cfgPath) .Select(line => { if (line.StartsWith("home = ")) { return(string.Format("home = C:\\{0:N}", Guid.NewGuid())); } return(line); }) ); } } Console.WriteLine("All files:"); foreach (var f in Directory.EnumerateFiles(sourcePath, "*", SearchOption.AllDirectories)) { Console.WriteLine(CommonUtils.GetRelativeFilePath(sourcePath, f)); } Assert.IsTrue( File.Exists(Path.Combine(sourcePath, "env", expectedFile)), "Virtualenv was not created correctly" ); settings.SourcePath = sourcePath; string path = CreateRequestedProject(settings); Assert.AreEqual(settings.ProjectPath, path); var proj = XDocument.Load(path); // Does not include any .py files from the virtualenv AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Compile")).Select(x => x.Attribute("Include").Value), "main.py", "A\\__init__.py" ); // Does not contain 'env' AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Folder")).Select(x => x.Attribute("Include").Value), "A" ); var env = proj.Descendant("Interpreter"); Assert.AreEqual("env\\", env.Attribute("Include").Value); Assert.AreEqual("lib\\", env.Descendant("LibraryPath").Value, true); if (brokenBaseInterpreter) { Assert.AreEqual("env", env.Descendant("Description").Value); Assert.AreEqual("", env.Descendant("InterpreterPath").Value); Assert.AreEqual("", env.Descendant("WindowsInterpreterPath").Value); Assert.AreEqual(Guid.Empty.ToString("B"), env.Descendant("BaseInterpreter").Value); Assert.AreEqual("", env.Descendant("PathEnvironmentVariable").Value); } else { Assert.AreEqual("env (Test Python)", env.Descendant("Description").Value); Assert.AreEqual("scripts\\python.exe", env.Descendant("InterpreterPath").Value, true); // The mock configuration uses python.exe for both paths. Assert.AreEqual("scripts\\python.exe", env.Descendant("WindowsInterpreterPath").Value, true); Assert.AreEqual(python.Id.ToString("B"), env.Descendant("BaseInterpreter").Value, true); Assert.AreEqual("PYTHONPATH", env.Descendant("PathEnvironmentVariable").Value, true); } } }
public void Save() { File.WriteAllText(appSettings.UserSettingsFile, JsonConvert.SerializeObject(this, Formatting.Indented, converters)); }
private void Car_ModeMakeroutes(string dbPath, string csvPath) { List <string> idArray = new List <string>(); if (csvPath.IndexOf('+') == 0) { string conStr = @"Data Source =" + dbPath; m_dbConnection = new SQLiteConnection(conStr); m_dbConnection.Open(); string csvName = null; csvName = csvPath; string sql = "SELECT count(*) FROM path_data WHERE origin_city = '" + csvName + "'"; SQLiteCommand cmd = m_dbConnection.CreateCommand(); cmd.CommandText = sql; SQLiteDataAdapter dao = new SQLiteDataAdapter(cmd); dt = new DataTable(); dao.Fill(dt); SQLiteCommand cmd2 = m_dbConnection.CreateCommand(); string sql2 = "SELECT origin_city ,origin_region FROM path_data WHERE origin_city = '" + csvName + "' limit 0,1"; cmd2.CommandText = sql2; SQLiteDataReader reader = cmd2.ExecuteReader(); reader.Read(); if (reader["origin_city"].ToString() != reader["origin_region"].ToString()) { csvName = reader[1].ToString() + reader[0].ToString(); } FileStream csvFile = null; StreamWriter csvSw = null; if (File.Exists(System.IO.Path.GetDirectoryName(dbPath) + "\\" + csvName + ".csv")) { csvFile = new FileStream(System.IO.Path.GetDirectoryName(dbPath) + "\\" + csvName + ".csv", FileMode.Open); var utf8WithoutBom = new System.Text.UTF8Encoding(false); csvSw = new StreamWriter(csvFile, utf8WithoutBom); csvSw.BaseStream.Seek(0, SeekOrigin.End); } else { csvFile = new FileStream(System.IO.Path.GetDirectoryName(dbPath) + "\\" + csvName + ".csv", FileMode.Create); var utf8WithoutBom = new System.Text.UTF8Encoding(false); csvSw = new StreamWriter(csvFile, utf8WithoutBom); } int count = int.Parse(dt.Rows[0][0].ToString()); int arrayNum = count / 500 + 1; DataTable dtArray = null; for (int i = 0; i < arrayNum; i++) { dtArray = new DataTable(); string sqlStr = "SELECT * FROM path_data WHERE origin_city = '" + csvName + "' limit " + (i * 500).ToString() + "," + 500.ToString(); SQLiteCommand command = m_dbConnection.CreateCommand(); command.CommandText = sqlStr; SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter(command); dataAdapter.Fill(dtArray); for (int j = 0; j < dtArray.Rows.Count; j++) { for (int k = 0; k < 7; k++) { csvSw.Write(dtArray.Rows[j][k] + ","); } csvSw.WriteLine("\"" + dtArray.Rows[j][7] + "\""); } } csvSw.Close(); csvFile.Close(); } else { string conStr = @"Data Source =" + dbPath; m_dbConnection = new SQLiteConnection(conStr); m_dbConnection.Open(); int index = csvPath.IndexOf('+'); string origin_lng = csvPath.Substring(index + 1, csvPath.Length - index - 1); string origin_lat = csvPath.Substring(0, index); string CalculateNumSql = "SELECT count(*) FROM path_data WHERE origin_lat = '" + origin_lat + "' AND origin_lng = '" + origin_lng + "'"; SQLiteCommand cmd1 = m_dbConnection.CreateCommand(); cmd1.CommandText = CalculateNumSql; SQLiteDataReader reader = cmd1.ExecuteReader(); reader.Read(); FileStream csvFile = null; StreamWriter csvSw = null; if (File.Exists(System.IO.Path.GetDirectoryName(dbPath) + "\\" + csvPath + ".csv")) { //csvFile = new FileStream(System.IO.Path.GetDirectoryName(dbPath) + "\\" + csvPath + "routes"+ ".csv", FileMode.Open); //var utf8WithoutBom = new System.Text.UTF8Encoding(false); //csvSw = new StreamWriter(csvFile, utf8WithoutBom); //csvSw.BaseStream.Seek(0, SeekOrigin.End); File.Delete(System.IO.Path.GetDirectoryName(dbPath) + "\\" + csvPath + ".csv"); } csvFile = new FileStream(System.IO.Path.GetDirectoryName(dbPath) + "\\" + csvPath + "_routes" + ".csv", FileMode.Create); var utf8WithoutBom = new System.Text.UTF8Encoding(false); csvSw = new StreamWriter(csvFile, utf8WithoutBom); int count = int.Parse(reader[0].ToString()); int arrayNum = count / 500 + 1; DataTable dtArray = null; for (int i = 0; i < arrayNum; i++) { dtArray = new DataTable(); string sqlStr = "SELECT * FROM path_data WHERE origin_lat = '" + origin_lat + "' AND origin_lng = '" + origin_lng + "'" + " limit " + (i * 500).ToString() + "," + 500.ToString(); SQLiteCommand command = m_dbConnection.CreateCommand(); command.CommandText = sqlStr; SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter(command); dataAdapter.Fill(dtArray); for (int j = 0; j < dtArray.Rows.Count; j++) { for (int k = 0; k < dtArray.Columns.Count; k++) { csvSw.Write(dtArray.Rows[j][k] + ","); } csvSw.WriteLine(); idArray.Add(dtArray.Rows[j][0].ToString()); } } csvSw.Close(); csvFile.Close(); CarModeReadsubPaths(dbPath, csvPath, idArray); idArray.Clear(); } }
private void BtnReadAdditionFile_Click(object sender, EventArgs e) { OpenFileDialog dialog = new OpenFileDialog(); dialog.Title = "请选择附加路径文件"; dialog.Filter = "txt文件(*.txt)|*.txt"; if (dialog.ShowDialog() != System.Windows.Forms.DialogResult.OK) { return; } OpenFileDialog dialog2 = new OpenFileDialog(); dialog2.Title = "请选择文件"; dialog2.Filter = "db文件(*.db)|*.db"; if (dialog2.ShowDialog() != System.Windows.Forms.DialogResult.OK) { return; } string dbPath = dialog2.FileName; string conStr = @"Data Source =" + dbPath; m_dbConnection = new SQLiteConnection(conStr); m_dbConnection.Open(); string txtPath = dialog.FileName; FileStream txtFS = new FileStream(txtPath, FileMode.Open); var utf8WithoutBom = new System.Text.UTF8Encoding(false); StreamReader txtSR = new StreamReader(txtFS, utf8WithoutBom); StreamWriter txtSW = new StreamWriter(txtFS, utf8WithoutBom); string aryLine = null; myRoadStruct tempStruct = new myRoadStruct(); string[] tempStrarray = null; string sql = null; DataTable dtTemp = null; FileStream csvFS = null; StreamWriter csvSW = null; string csvName = null; DialogResult dr = MessageBox.Show("是否是百度模式的数据!", "重要选择", MessageBoxButtons.YesNoCancel); while ((aryLine = txtSR.ReadLine()) != null) { //if (aryLine == " ") // continue; tempStrarray = aryLine.Split(','); tempStruct.id = int.Parse(tempStrarray[0]); //if(tempStruct.id < 56953) // continue; tempStruct.origin_city = tempStrarray[1 + 4]; tempStruct.origin_region = tempStrarray[3 + 4]; tempStruct.dest_city = tempStrarray[2 + 4]; tempStruct.dest_region = tempStrarray[4 + 4]; if (tempStruct.origin_city != tempStruct.origin_region) { csvName = tempStruct.origin_city + '+' + tempStruct.origin_region; } else { csvName = tempStruct.origin_city; } if (File.Exists(System.IO.Path.GetDirectoryName(dbPath) + "\\" + csvName + ".csv") == false) { continue; } SQLiteCommand cmd = m_dbConnection.CreateCommand(); sql = "select * from path_data where id = " + tempStruct.id.ToString(); cmd.CommandText = sql; SQLiteDataAdapter dao = new SQLiteDataAdapter(cmd); dtTemp = new DataTable(); dao.Fill(dtTemp); if (dtTemp.Rows.Count == 0) { continue; } csvFS = new FileStream(System.IO.Path.GetDirectoryName(dbPath) + "\\" + csvName + ".csv", FileMode.Open); csvSW = new StreamWriter(csvFS, utf8WithoutBom); csvSW.BaseStream.Seek(0, SeekOrigin.End); if (dr == DialogResult.OK) { for (int k = 0; k < 11; k++) { csvSW.Write(dtTemp.Rows[0][k] + ","); } csvSW.WriteLine("\"" + dtTemp.Rows[0][11] + "\""); } else { for (int k = 0; k < 5; k++) { csvSW.Write(dtTemp.Rows[0][k] + ","); } csvSW.Write(tempStruct.origin_city + ","); csvSW.Write(tempStruct.dest_city + ","); csvSW.Write(tempStruct.origin_region + ","); csvSW.Write(tempStruct.dest_region + ","); csvSW.Write(dtTemp.Rows[0][5] + ","); csvSW.Write(dtTemp.Rows[0][6] + ","); if (dtTemp.Rows[0][7].ToString().Length > 100) { csvSW.WriteLine("\"" + dtTemp.Rows[0][7] + "\""); } else { csvSW.WriteLine("\"" + dtTemp.Rows[0][8] + "\""); } csvSW.Flush(); csvSW.Close(); csvFS.Close(); } } txtSW.Close(); txtSR.Close(); txtFS.Close(); MessageBox.Show("补充完毕"); }
public void Dispose() { File.Delete(Path); }
private bool LoadSkyDomeModel(string skyDomeModelFileName) { skyDomeModelFileName = DSystemConfiguration.ModelFilePath + skyDomeModelFileName; try { // Open the model file. string[] lines = File.ReadAllLines(skyDomeModelFileName); // Read up to the value of vertex count. int lineIndex = 0; bool found = false; while (!found) { if (lines[lineIndex].StartsWith("Vertex Count:")) found = true; else lineIndex++; } // Read in the vertex count, the second column after the ':' of the first row in the file. string stringVertexCount = lines[lineIndex].Split(':')[1]; VertexCount = int.Parse(stringVertexCount); // Set the number of indices to be the same as the vertex count. IndexCount = VertexCount; // Create the model using the vertex count that was read in. Model = new DModelType[VertexCount]; // Before continueing with the line parsing ensure we are starting one line after the "Data" portion of the file. int lineDataIndex = ++lineIndex; found = false; while (!found) { if (lines[lineDataIndex].Equals("Data:")) found = true; else lineDataIndex++; } // Procced to the next line for Vertex data. lineDataIndex++; // Read up to the beginning of the data. int vertexWriteIndex = 0; for (int i = lineDataIndex; i < lines.Length; i++) { // Ignor blank lines. if (string.IsNullOrEmpty(lines[i])) continue; // break out segments of this line. string[] segments = lines[i].Split(' '); //Model[vertexWriteIndex] = new DModelType() //{ // Read in the vertex data, First X, Y & Z positions. Model[vertexWriteIndex].x = float.Parse(segments[0]); Model[vertexWriteIndex].y = float.Parse(segments[1], NumberStyles.Float); Model[vertexWriteIndex].z = float.Parse(segments[2], NumberStyles.Float); // Read in the Tu and Yv tecture coordinate values. Model[vertexWriteIndex].tu = float.Parse(segments[3], NumberStyles.Float); Model[vertexWriteIndex].tv = float.Parse(segments[4], NumberStyles.Float); // Read in the Normals X, Y & Z values. Model[vertexWriteIndex].nx = float.Parse(segments[5], NumberStyles.Float); Model[vertexWriteIndex].ny = float.Parse(segments[6], NumberStyles.Float); Model[vertexWriteIndex].nz = float.Parse(segments[7], NumberStyles.Float, CultureInfo.InvariantCulture); vertexWriteIndex++; } } catch (Exception) { return false; } return true; }
static async Task Main(string[] args) { var rsa = new BigIntRsa(); try { var options = new ProgressBarOptions { ProgressCharacter = '#', }; using (var bar = new ProgressBar(1, "Preparing...", options)) { await rsa.Prepare(); bar.Tick(); } Console.WriteLine($"Public key: [{rsa.Egg}, {rsa.N}]"); Console.WriteLine($"Private key: [{rsa.D}, {rsa.N}]"); //var TestMessage = "hee hoo pee nut"; //var TestMessage = "One of the basic pieces of furniture, a chair is a type of seat. Its primary features are two pieces of a durable material, attached as back and seat to one another at a 90° or slightly greater angle, with usually the four corners of the horizontal seat attached in turn to four legs—or other parts of the seat's underside attached to three legs or to a shaft about which a four-arm turnstile on rollers can turn—strong enough to support the weight of a person who sits on the seat (usually wide and broad enough to hold the lower body from the buttocks almost to the knees) and leans against the vertical back (usually high and wide enough to support the back to the shoulder blades). The legs are typically high enough for the seated person's thighs and knees to form a 90° or lesser angle.[1][2] Used in a number of rooms in homes (e.g. in living rooms, dining rooms, and dens), in schools and offices (with desks), and in various other workplaces, chairs may be made of wood, metal, or synthetic materials, and either the seat alone or the entire chair may be padded or upholstered in various colors and fabrics. Chairs vary in design. An armchair has armrests fixed to the seat;[3] a recliner is upholstered and under its seat is a mechanism that allows one to lower the chair's back and raise into place a fold-out footrest;[4] a rocking chair has legs fixed to two long curved slats; and a wheelchair has wheels fixed to an axis under the seat.[5]"; var builder = new StringBuilder(); foreach (var file in Directory.EnumerateFiles("shonkspeare")) { builder.Append(await File.ReadAllTextAsync(file)); } var TestMessage = builder.ToString(); var encoded = new List<int>(); using (var bar = new ProgressBar(1, "Encoding...", options)) { foreach (var b in Encoding.Unicode.GetBytes(TestMessage)) { encoded.Add(b); } bar.Tick(); } var encrypted = new BigInteger[encoded.Count]; using (var bar = new ProgressBar(encoded.Count, "Encrypting...", options)) { Parallel.For(0, encoded.Count, i => { encrypted[i] = rsa.Encrypt(new BigInteger(encoded[i])); bar.Tick(); }); } /*foreach (var i in encoded) { encrypted.Add(rsa.Encrypt(new BigInteger(i))); }*/ var decrypted = new byte[encrypted.Length]; string decoded; using (var bar = new ProgressBar(encrypted.Length, "Decrypting...", options)) { Parallel.For(0, encrypted.Length, i => { decrypted[i] = (byte) rsa.Decrypt(encrypted[i]).IntValue(); bar.Tick(); }); } /*foreach (var i in encrypted) { decrypted.Add((byte) rsa.Decrypt(i).IntValue()); }*/ using (var bar = new ProgressBar(1, "Decoding...", options)) { decoded = Encoding.Unicode.GetString(decrypted.ToArray()); bar.Tick(); } Console.WriteLine(decoded); } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); } /*var stopwatch = new Stopwatch(); stopwatch.Start(); var (p, q) = GetPrimeNumbers(); if (p < q) { var temp = p; p = q; q = temp; } var n = p * q; var phi = (p - 1) * (q - 1); long e = 65537; // prime number recommended by article while (Gcd(phi, e) != 1) { if (Gcd(e, phi) == 1) break; if (e < phi) e++; } long d; long tempD; for (var i = 2;; i++) { d = (phi * i + 1) / e; tempD = (phi * i + 1) % e; if (tempD == 0) { break; } } PublicKey = new Tuple<long, long>(e, n); PrivateKey = new Tuple<long, long>(d, n); stopwatch.Stop(); //Console.WriteLine($"{n1} | {n2}"); Console.WriteLine($"key generation took {stopwatch.Elapsed}"); var test = new BigInteger(69); var test2 = Crypt(test, PublicKey.Item1, PublicKey.Item2); var test3 = Crypt(test, PrivateKey.Item1, PrivateKey.Item2); Console.WriteLine($"before: {test}"); Console.WriteLine($"encrypted: {test2}"); Console.WriteLine($"after: {test3}");*/ /*stopwatch.Reset(); var TestMessage = "hee hoo pee nut"; stopwatch.Start(); var encoded = new List<int>(); var encrypted = new List<int>(); foreach (var s in TestMessage.ToCharArray()) { var bytes = Encoding.Unicode.GetBytes(s.ToString()); if (BitConverter.IsLittleEndian) Array.Reverse(bytes); if (bytes.Length < 4) { var list = new List<byte>(bytes); while (list.Count < 4) { list.Insert(0, 0); } bytes = list.ToArray(); } encoded.Add(BitConverter.ToInt32(bytes, 0)); Console.WriteLine(s); } foreach (var i in encoded) { encrypted.Add(Crypt(i, PublicKey.Item1, PublicKey.Item2)); } stopwatch.Stop(); Console.WriteLine($"encryption took {stopwatch.Elapsed}"); stopwatch.Reset(); var decrypted = ""; stopwatch.Start(); foreach (var i in encrypted) { var j = Crypt(i, PrivateKey.Item1, PrivateKey.Item2); var bytes = BitConverter.GetBytes(j); //Console.WriteLine(bytes.Length); if (BitConverter.IsLittleEndian) Array.Reverse(bytes); decrypted += Encoding.Unicode.GetString(bytes); //Console.WriteLine(Encoding.Unicode.GetString(bytes)); } stopwatch.Stop(); Console.WriteLine(decrypted); Console.WriteLine($"decryption took {stopwatch.Elapsed}");*/ }
public string GetContents() { return File.ReadAllText(Path); }
private void tbInputDir_TextChanged(object sender, EventArgs e) { panelPack.Enabled = false; btnUnpack.Enabled = Directory.Exists(tbInputDir.Text) || File.Exists(tbInputDir.Text); }
protected static string GetConfigVariable(string name) { if (String.IsNullOrEmpty(name)) { return(null); } if (_configVariables == null) { try { string configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin", "config.json"); // check to see if environment specific config exists and use that instead if (File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..\\", "config.json"))) { configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..\\", "config.json"); } if (!File.Exists(configPath)) { _configVariables = new Dictionary <string, string>(); return(null); } _configVariables = JsonConvert.DeserializeObject <Dictionary <string, string> >(File.ReadAllText(configPath)); } catch (Exception) { _configVariables = new Dictionary <string, string>(); return(null); } } return(_configVariables.ContainsKey(name) ? _configVariables[name] : null); }
public static void Init(string excelpath) { evaluatorEnv = new Dictionary <string, IFormulaEvaluator>(); allBooks = new List <CustomWorkbook>(); int totalCount = 0; // 启用公式重算的接口 evaluateSheets = new List <string>(); string evaConfPath = new FileInfo(Application.ExecutablePath).Directory.FullName + Path.DirectorySeparatorChar + "evaconfig"; if (File.Exists(evaConfPath)) { evaluateSheets = new List <string>(File.ReadAllLines(evaConfPath)); } // 遍历导出目录 List <string> readfiles = new List <string>(); foreach (var file in new DirectoryInfo(excelpath).GetFiles()) { if (file.Name.StartsWith("~$") || (file.Extension != ".xlsx" && file.Extension != ".xls")) { continue; } foreach (var fname in Cache.GetNoCacheAbout(file)) { if (!readfiles.Contains(fname)) { readfiles.Add(fname); } } } foreach (var fname in readfiles) { var file = new FileInfo(excelpath + "/" + fname); CustomWorkbook book = new CustomWorkbook(file); book.type = CustomWorkbookType.Export; totalCount++; } // 引用表 string refConfPath = new FileInfo(Application.ExecutablePath).Directory.FullName + Path.DirectorySeparatorChar + "refconfig"; if (File.Exists(refConfPath)) { foreach (string reffile in File.ReadAllLines(refConfPath)) { var file = new FileInfo(reffile); CustomWorkbook book = new CustomWorkbook(file); book.type = CustomWorkbookType.Referenced; totalCount++; } } // 等待完成 while (allBooks.Count < totalCount) { Thread.Sleep(TimeSpan.FromSeconds(0.01)); } // 设置公式环境 foreach (var book in allBooks) { book.evaluator.SetupReferencedWorkbooks(evaluatorEnv); } Cache.PrepareToExport(); }
public virtual bool Exists(string filePath) { return(File.Exists(filePath)); }