public static FileUtils getInstance() { if (null == instance) { instance = new FileUtils(); } return instance; }
public static void SynthesizeMainEntryForSythesizedValidators(string inputFolder, string outputFile, string entryClassName) { FileUtils fileUtils = new FileUtils(); fileUtils.SetHowDeepToScan(1); fileUtils.ProcessDir(inputFolder, 1, false, "", ".cs", null); List<string> testNames = fileUtils.GetFileNames(); StringBuilder sb_using = new StringBuilder(); StringBuilder sb_body = new StringBuilder(); sb_using.AppendLine("using System;"); sb_body.AppendLine("namespace AutomatonToCode"); sb_body.AppendLine("{"); sb_body.AppendLine("class " + entryClassName); sb_body.AppendLine("{"); sb_body.AppendLine("public static void InvokeAllRandomTests()"); sb_body.AppendLine("{"); for (int i = 0; i < testNames.Count; i++) { TextReader tr2 = new StreamReader(testNames[i]); String line = tr2.ReadLine(); string className = ""; while (line != null) { if (line.StartsWith("using ")) sb_using.AppendLine(line); else if (line.StartsWith("public partial class ")) { className = line.Substring(line.IndexOf("_"), line.Length - line.IndexOf("_")); sb_body.AppendLine(className + " " + className + "_object = new " + className + "();"); } else if (line.StartsWith("public void ")) { string methodName = line.Substring(line.IndexOf("Method"), line.LastIndexOf("(") - line.IndexOf("Method")); sb_body.AppendLine("try"); sb_body.AppendLine("{"); sb_body.AppendLine(className + "_object." + methodName + "();"); sb_body.AppendLine("}"); sb_body.AppendLine("catch (Exception e)"); sb_body.AppendLine("{"); sb_body.AppendLine("Console.Out.WriteLine(e.Message);"); sb_body.AppendLine("}"); } line = tr2.ReadLine(); } Console.Out.WriteLine("Construct " + i + "/" + testNames.Count); } sb_body.AppendLine("}"); sb_body.AppendLine("}"); sb_body.AppendLine("}"); FileUtils.WriteTxt(sb_using.ToString() + sb_body.ToString(), outputFile); }
public void InstrumentAllAcceptCharInFolder(string folder) { FileUtils fileutil = new FileUtils(); fileutil.SetHowDeepToScan(1); fileutil.ProcessDir(folder, 1, true, "", ".cs", null); List<String> fileNames = fileutil.GetFileNames(); for(int i=0;i<fileNames.Count;i++){ if (!fileNames[i].Contains("RegexIsMatch_")) { string newfile = fileNames[i].Replace("automaton.cs", "automaton.cs.instrumented"); InstrumentAcceptChar(fileNames[i], newfile); } } }
public static void Main(string[] args) { if (string.IsNullOrWhiteSpace(args[0]) || string.IsNullOrWhiteSpace(args[1])) { Console.WriteLine("Missing Source or destination directories"); } var sourceDir = args[0]; var destDir = args[1]; FileUtils helper = new FileUtils(sourceDir, destDir); var startTime = DateTime.Now; Task.WaitAll(helper.ProcessDir(sourceDir).ToArray()); //helper.processDirSync(sourceDir); Console.WriteLine("Processing Complete"); Console.WriteLine(String.Format("Total time: {0}", DateTime.Now - startTime)); Console.ReadLine(); }
public void CreateDownloadedPostOnDisk(Post post, string weblogName) { string filename = FileUtils.SafeFilename(post.Title); var folder = Path.Combine(WeblogAddinConfiguration.Current.PostsFolder, "Downloaded", weblogName, filename); if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } var outputFile = Path.Combine(folder, StringUtils.ToCamelCase(filename) + ".md"); bool isMarkdown = false; string body = post.Body; string featuredImage = null; if (post.CustomFields != null) { var cf = post.CustomFields.FirstOrDefault(custf => custf.Id == "mt_markdown"); if (cf != null) { body = cf.Value; isMarkdown = true; } cf = post.CustomFields.FirstOrDefault(custf => custf.Id == "wp_post_thumbnail"); if (cf != null) { featuredImage = cf.Value; } } if (!isMarkdown) { if (!string.IsNullOrEmpty(post.mt_text_more)) { // Wordpress ReadMore syntax - SERIOUSLY??? if (string.IsNullOrEmpty(post.mt_excerpt)) { post.mt_excerpt = HtmlUtils.StripHtml(post.Body); } body = MarkdownUtilities.HtmlToMarkdown(body) + "\n\n<!--more-->\n\n" + MarkdownUtilities.HtmlToMarkdown(post.mt_text_more); } else { body = MarkdownUtilities.HtmlToMarkdown(body); } } string categories = null; if (post.Categories != null && post.Categories.Length > 0) { categories = string.Join(",", post.Categories); } // Create the new post by creating a file with title preset var meta = new WeblogPostMetadata() { Title = post.Title, MarkdownBody = body, Categories = categories, Keywords = post.mt_keywords, Abstract = post.mt_excerpt, PostId = post.PostId.ToString(), WeblogName = weblogName, FeaturedImageUrl = featuredImage }; string newPostMarkdown = NewWeblogPost(meta); File.WriteAllText(outputFile, newPostMarkdown); mmApp.Configuration.LastFolder = Path.GetDirectoryName(outputFile); if (isMarkdown) { string html = post.Body; string path = mmApp.Configuration.LastFolder; // do this synchronously so images show up :-< ShowStatus("Downloading post images..."); SaveMarkdownImages(html, path); ShowStatus("Post download complete.", 5000); //new Action<string,string>(SaveImages).BeginInvoke(html,path,null, null); } Model.Window.OpenTab(outputFile); }
private static int MainInner(string[] args) { var presets = args.Where(x => x.EndsWith(".pu-preset")).ToList(); var actualList = new List <string>(); foreach (var preset in presets) { try { actualList.AddRange( File.ReadAllLines(preset) .Where(x => !x.StartsWith("#")) .Select(x => x.Split(new[] { " #" }, StringSplitOptions.None)[0].Trim()) .Where(x => x.Length > 0)); } catch (Exception e) { Console.Error.WriteLine($"Can't load preset {preset}: {e.Message}."); } } actualList.AddRange(args.ApartFrom(presets)); var options = new Options(); if (!Parser.Default.ParseArguments(actualList.ToArray(), options)) { return(1); } if (options.ColorGradingFilename != null && presets.Count > 0 && !File.Exists(options.ColorGradingFilename)) { var locations = presets.Select(Path.GetDirectoryName).ToList(); var current = Environment.CurrentDirectory; foreach (var location in locations) { Environment.CurrentDirectory = location; var path = Path.GetFullPath(options.ColorGradingFilename); if (File.Exists(path)) { options.ColorGradingFilename = path; } } Environment.CurrentDirectory = current; } var acRoot = options.AcRoot == null?AcRootFinder.TryToFind() : Path.GetFullPath(options.AcRoot); if (acRoot == null) { Console.Error.WriteLine("Can't find AC root directory, you need to specify it manually."); Console.ReadLine(); return(1); } var ids = options.Ids.ApartFrom(presets).ToList(); if (ids.Count == 0) { Console.Error.WriteLine("You forgot to specify what cars to update: either list their IDs or filters."); Console.Error.WriteLine("To process all cars, use filter \"*\"."); Console.ReadLine(); return(1); } IFilter <string> filter; try { filter = Filter.Create(new CarTester(acRoot), ids.Select(x => "(" + (x.EndsWith("/") ? x.Substring(0, x.Length - 1) : x) + ")").JoinToString("|"), true); if (options.FilterTest) { Console.WriteLine(Directory.GetDirectories(FileUtils.GetCarsDirectory(acRoot)) .Select(Path.GetFileName).Where(x => filter.Test(x)).JoinToString(", ")); return(0); } if (options.Verbose) { Console.WriteLine("Filter: " + filter); } } catch (Exception e) { Console.Error.WriteLine("Can't parse filter: " + e.Message + "."); Console.ReadLine(); return(2); } if (options.Verbose) { Console.WriteLine("AC root: " + acRoot); Console.WriteLine("ImageMagick: " + ImageUtils.IsMagickSupported); Console.WriteLine("Starting shoting..."); } var sw = Stopwatch.StartNew(); int i = 0, j = 0; using (var thing = new DarkPreviewsUpdater(acRoot, new DarkPreviewsOptions { PreviewName = options.FileName, Showroom = options.Showroom, AlignCar = options.AlignCar, AlignCameraHorizontally = options.AlignCamera, AlignCameraHorizontallyOffset = options.AlignCameraOffset.Split(',').Select(x => FlexibleParser.TryParseDouble(x) ?? 0d).ToArray()[0], // TODO SsaaMultiplier = options.SsaaMultiplier, UseFxaa = options.UseFxaa, UseMsaa = options.UseMsaa, SoftwareDownsize = options.SoftwareDownsize, MsaaSampleCount = options.MsaaSampleCount, PreviewWidth = options.PreviewWidth, PreviewHeight = options.PreviewHeight, BloomRadiusMultiplier = options.BloomRadiusMultiplier, FlatMirror = options.FlatMirror, WireframeMode = options.WireframeMode, MeshDebugMode = options.MeshDebugMode, SuspensionDebugMode = options.SuspensionDebugMode, HeadlightsEnabled = options.HeadlightsEnabled, BrakeLightsEnabled = options.BrakeLightsEnabled, LeftDoorOpen = options.LeftDoorOpen, RightDoorOpen = options.RightDoorOpen, SteerDeg = options.SteerAngle, CameraPosition = options.CameraPosition.Split(',').Select(x => FlexibleParser.TryParseDouble(x) ?? 0d).ToArray(), CameraLookAt = options.LookAt.Split(',').Select(x => FlexibleParser.TryParseDouble(x) ?? 0d).ToArray(), CameraFov = options.Fov, BackgroundColor = ParseColor(options.BackgroundColor), LightColor = ParseColor(options.LightColor), AmbientUp = ParseColor(options.AmbientUp), AmbientDown = ParseColor(options.AmbientDown), AmbientBrightness = options.AmbientBrightness, LightBrightness = options.LightBrightness, DelayedConvertation = !options.SingleThread, UseSslr = options.UseSslr, UseAo = options.UseSsao, UsePcss = options.UsePcss, EnableShadows = options.EnableShadows, ShadowMapSize = options.ShadowMapSize, MaterialsReflectiveness = options.ReflectionMultiplier, ReflectionCubemapAtCamera = options.ReflectionCubemapAtCamera, ReflectionsWithShadows = !options.NoShadowsWithReflections, FlatMirrorBlurred = options.FlatMirrorBlurred, FlatMirrorReflectiveness = options.FlatMirrorReflectiveness, LightDirection = options.LightDirection.Split(',').Select(x => FlexibleParser.TryParseDouble(x) ?? 0d).ToArray(), })) { foreach (var carId in Directory.GetDirectories(FileUtils.GetCarsDirectory(acRoot)) .Select(Path.GetFileName).Where(x => filter.Test(x))) { Console.WriteLine($" {carId}..."); j++; foreach (var skinId in Directory.GetDirectories(FileUtils.GetCarSkinsDirectory(acRoot, carId)) .Where(x => !options.WithoutPreviews || !File.Exists(Path.Combine(x, options.FileName))) .Select(Path.GetFileName)) { var success = false; for (var a = 0; a < options.AttemptsCount || a == 0; a++) { try { if (options.Verbose) { Console.Write($" {skinId}... "); } thing.Shot(carId, skinId); success = true; break; } catch (Exception e) { Console.Error.WriteLine(e.Message); if (options.Verbose) { Console.Error.WriteLine(e.StackTrace); } } } if (success) { i++; if (options.Verbose) { Console.WriteLine("OK"); } } } if (options.Verbose && j % 10 == 0) { Console.WriteLine( $"At this moment done: {i} skins ({sw.Elapsed.TotalMilliseconds / j:F1} ms per car; {sw.Elapsed.TotalMilliseconds / i:F1} ms per skin)"); Console.WriteLine($"Time taken: {ToMillisecondsString(sw.Elapsed)}"); } } Console.Write("Finishing convertation... "); } Console.WriteLine("OK"); Console.WriteLine($"Done: {i} skins ({sw.Elapsed.TotalMilliseconds / j:F1} ms per car; {sw.Elapsed.TotalMilliseconds / i:F1} ms per skin)"); Console.WriteLine($"Time taken: {ToMillisecondsString(sw.Elapsed)}"); return(0); }
public void Shot(string outputDirectory, [CanBeNull] IProgress <double> progress, CancellationToken cancellation) { if (!Initialized) { Initialize(); } using (var replacement = FileUtils.RecycleOriginal(Path.Combine(outputDirectory, "body_shadow.png"))) { // body shadow PrepareBuffers(BodySize + BodyPadding * 2, 1024); SetBodyShadowCamera(); Draw(BodyMultiplier, BodySize, BodyPadding, Fade ? 0.5f : 0f, progress.SubrangeDouble(0.01, 0.59), cancellation); if (cancellation.IsCancellationRequested) { return; } SaveResultAs(replacement.Filename, BodySize, BodyPadding); } // wheels shadows if (_flattenNodesFix != null) { foreach (var tuple in _flattenNodesFix) { tuple.Item1.ParentMatrix = tuple.Item2; } } PrepareBuffers(WheelSize + WheelPadding * 2, 128); SetWheelShadowCamera(); _wheelMode = true; var nodes = new[] { "WHEEL_LF", "WHEEL_RF", "WHEEL_LR", "WHEEL_RR" }; var list = nodes.Select(x => CarNode.GetDummyByName(x)).NonNull().Select((x, i) => new { Node = x, GlobalMatrix = x.Matrix, Matrix = Matrix.Translation(-(CarData?.GetWheelGraphicOffset(x.Name) ?? Vector3.Zero) + new Vector3(0f, x.Matrix.GetTranslationVector().Y - (x.BoundingBox?.Minimum.Y ?? 0f), 0f)), FileName = $"tyre_{i}_shadow.png", Progress = progress.SubrangeDouble(0.6 + i * 0.1, 0.099) }).ToList(); foreach (var entry in list) { using (var replacement = FileUtils.RecycleOriginal(Path.Combine(outputDirectory, entry.FileName))) { var m = Matrix.Invert(entry.GlobalMatrix); _flattenNodes = list.SelectMany(x => { x.Node.ParentMatrix = Matrix.Identity; x.Node.LocalMatrix = entry.Matrix * x.GlobalMatrix * m; return(Flatten(x.Node).OfType <Kn5RenderableDepthOnlyObject>()); }).ToArray(); Draw(WheelMultiplier, WheelSize, WheelPadding, 1f, entry.Progress, cancellation); if (cancellation.IsCancellationRequested) { return; } SaveResultAs(replacement.Filename, WheelSize, WheelPadding); } } }
private Hashtable GetCoverageList_TestedMethod(string foldername) { Hashtable ht = new Hashtable(); FileUtils fileutil = new FileUtils(); fileutil.SetHowDeepToScan(1); fileutil.ProcessDir(foldername, 1, false, "", ".html", null); List<String> fileNames = fileutil.GetFileNames(); for (int i = 0; i < fileNames.Count; i++) { string[] method_ratio = ExtractCoverageInfo_TestedMethod(fileNames[i]); if (method_ratio[0].Length > 0) { ht.Add(method_ratio[0], (float)System.Convert.ToSingle(method_ratio[1])); Console.WriteLine(i + "/" + fileNames.Count + " MethodName: " + method_ratio[0] + " BranchCoverage: " + (float)System.Convert.ToSingle(method_ratio[1])); } } fileutil.CleanFileNames(); return ht; }
public string GetMD5(FileUtils.HashProgress handler = null) { try { return FileUtils.FileMD5(this.FullPath, handler); } catch (IOException e) { throw new BackupOperationException(this.RelPath, e.Message); } catch (UnauthorizedAccessException e) { throw new BackupOperationException(this.RelPath, e.Message); } }
public void GetAutomataCoverage(string ratioFile, string reportFolder, string outputfile) { FileUtils fileutil = new FileUtils(); fileutil.SetHowDeepToScan(2); fileutil.ProcessDir(reportFolder, 1, true, "RegExpChecker_", ".xml", null); List<String> fileNames = fileutil.GetFileNames(); StreamReader tr = new StreamReader(ratioFile); string line = tr.ReadLine(); HashSet<String> methodSet = new HashSet<String>(); while (line != null) { if (line.StartsWith("Method") && !line.StartsWith("MethodName") && !line.StartsWith("Method_amount")) methodSet.Add(line.Substring(0, line.IndexOf("\t"))); line = tr.ReadLine(); } StringBuilder sb = new StringBuilder(); float sum = 0; float count = 0; for (int i = 0; i < fileNames.Count; i++) { tr = new StreamReader(fileNames[i]); line = tr.ReadLine(); while (line != null) { if (line.StartsWith("<method name=\"Method")) { string method = line.Substring(line.IndexOf("\"Method") + 1, line.IndexOf("\" type=") - line.IndexOf("\"Method") - 1); if (!methodSet.Contains(method)) break; else { while (line != null) { if (line.StartsWith("<method name=\"AcceptChar\"")) { while (line != null) { if (line.StartsWith("<coverage ")) { string cov = line.Substring(line.IndexOf("coveredRatio="), line.Length-line.IndexOf("coveredRatio=")); cov = cov.Substring(cov.IndexOf("\"")+1, cov.IndexOf("\"/>")-cov.IndexOf("\"") - 1); sb.Append(method + ".AcceptChar\t" + cov + "\n"); sum = sum + float.Parse(cov); count++; methodSet.Remove(method); break; } line = tr.ReadLine(); } break; } line = tr.ReadLine(); } } break; } line = tr.ReadLine(); } } sb.Append("Sum:\t" + sum + "\n"); sb.Append("Count:\t" + count + "\n"); sb.Append("Average:\t"+sum/count + "\n"); sb.Append("Left:\n"); for (int i = 0; i < methodSet.Count; i++) sb.Append(methodSet.ElementAt(i)+"\n"); FileUtils.WriteTxt(sb.ToString(), outputfile); fileutil.CleanFileNames(); }
/// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.runStrip = new System.Windows.Forms.ToolStrip(); this.buttonPreview = new System.Windows.Forms.ToolStripButton(); this.buttonEditColumns = new System.Windows.Forms.ToolStripButton(); this.toolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.toolStripButton2 = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.buttonJumpLink = new System.Windows.Forms.ToolStripButton(); this.toolStripButtonEditMode = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripButtonLoadTableFile = new System.Windows.Forms.ToolStripButton(); this.toolStripButtonSaveTableToXML = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripButtonInsert = new System.Windows.Forms.ToolStripButton(); this.toolStripButtonNumber = new System.Windows.Forms.ToolStripButton(); this.richTextBox1 = new System.Windows.Forms.RichTextBox(); this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog(); this.label1 = new System.Windows.Forms.Label(); this.panel1 = new System.Windows.Forms.Panel(); this.dataGrid1 = new DataGridNoKeyPressIrritation(); this.runStrip.SuspendLayout(); this.panel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit(); this.SuspendLayout(); // // runStrip // this.runStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.buttonPreview, this.buttonEditColumns, this.toolStripButton1, this.toolStripButton2, this.toolStripSeparator1, this.buttonJumpLink, this.toolStripButtonEditMode, this.toolStripSeparator2, this.toolStripButtonLoadTableFile, this.toolStripButtonSaveTableToXML, this.toolStripSeparator3, this.toolStripButtonInsert, this.toolStripButtonNumber }); this.runStrip.Location = new System.Drawing.Point(0, 0); this.runStrip.Name = "runStrip"; this.runStrip.Size = new System.Drawing.Size(530, 25); this.runStrip.TabIndex = 2; this.runStrip.Text = "toolStrip1"; // // buttonPreview // this.buttonPreview.Image = FileUtils.GetImage_ForDLL("zoom.png"); this.buttonPreview.ImageTransparentColor = System.Drawing.Color.Magenta; this.buttonPreview.Name = "buttonPreview"; this.buttonPreview.Size = new System.Drawing.Size(23, 22); this.buttonPreview.ToolTipText = Loc.Instance.GetString("Preview"); this.buttonPreview.Click += new System.EventHandler(this.previewclick); // // buttonEditColumns // this.buttonEditColumns.Image = FileUtils.GetImage_ForDLL("table_edit.png"); this.buttonEditColumns.ImageTransparentColor = System.Drawing.Color.Magenta; this.buttonEditColumns.Name = "buttonEditColumns"; this.buttonEditColumns.Size = new System.Drawing.Size(23, 22); this.buttonEditColumns.ToolTipText = Loc.Instance.GetString("Edit Columns"); this.buttonEditColumns.Click += new System.EventHandler(this.buttonEditColumns_Click); // // toolStripButton1 // this.toolStripButton1.Image = FileUtils.GetImage_ForDLL("script_edit.png"); this.toolStripButton1.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton1.Name = "toolStripButton1"; this.toolStripButton1.Size = new System.Drawing.Size(23, 22); this.toolStripButton1.ToolTipText = Loc.Instance.GetString("Import List"); this.toolStripButton1.Click += new System.EventHandler(this.ImportListClick); // // toolStripButton2 // this.toolStripButton2.Image = FileUtils.GetImage_ForDLL("page_copy.png"); this.toolStripButton2.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton2.Name = "toolStripButton2"; this.toolStripButton2.Size = new System.Drawing.Size(23, 22); this.toolStripButton2.ToolTipText = Loc.Instance.GetString("Copy To Clipboard"); this.toolStripButton2.Click += new System.EventHandler(this.CopyToClipboardClick); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25); // // buttonJumpLink // this.buttonJumpLink.Image = FileUtils.GetImage_ForDLL("link_go.png"); this.buttonJumpLink.ImageTransparentColor = System.Drawing.Color.Magenta; this.buttonJumpLink.Name = "buttonJumpLink"; this.buttonJumpLink.Size = new System.Drawing.Size(23, 22); this.buttonJumpLink.ToolTipText = Loc.Instance.GetString("Follow Link"); this.buttonJumpLink.Click += new System.EventHandler(this.buttonJumpLink_Click); // // toolStripButtonEditMode // this.toolStripButtonEditMode.Checked = true; this.toolStripButtonEditMode.CheckOnClick = true; this.toolStripButtonEditMode.CheckState = System.Windows.Forms.CheckState.Checked; this.toolStripButtonEditMode.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButtonEditMode.Image = FileUtils.GetImage_ForDLL("tag_blue.png"); this.toolStripButtonEditMode.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButtonEditMode.Name = "toolStripButtonEditMode"; this.toolStripButtonEditMode.Size = new System.Drawing.Size(23, 22); this.toolStripButtonEditMode.Text = Loc.Instance.GetString("Toggle Safe Edit Mode ** REMOVE? **"); this.toolStripButtonEditMode.Click += new System.EventHandler(this.toggleSafeEditModeClick); // does not appear necessary now that we use a GridView instead of a grid this.toolStripButtonEditMode.Visible = false; // // toolStripSeparator2 // this.toolStripSeparator2.Name = "toolStripSeparator2"; this.toolStripSeparator2.Size = new System.Drawing.Size(6, 25); // // toolStripButtonLoadTableFile // this.toolStripButtonLoadTableFile.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButtonLoadTableFile.Image = FileUtils.GetImage_ForDLL("table_add.png"); this.toolStripButtonLoadTableFile.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButtonLoadTableFile.Name = "toolStripButtonLoadTableFile"; this.toolStripButtonLoadTableFile.Size = new System.Drawing.Size(23, 22); this.toolStripButtonLoadTableFile.Text = "toolStripButton3"; this.toolStripButtonLoadTableFile.ToolTipText = Loc.Instance.GetString("Load a xml based datatable"); this.toolStripButtonLoadTableFile.Click += new System.EventHandler(this.toolStripButtonLoadTableFile_Click); // // toolStripButtonSaveTableToXML // this.toolStripButtonSaveTableToXML.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButtonSaveTableToXML.Image = FileUtils.GetImage_ForDLL("table_save.png"); this.toolStripButtonSaveTableToXML.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButtonSaveTableToXML.Name = "toolStripButtonSaveTableToXML"; this.toolStripButtonSaveTableToXML.Size = new System.Drawing.Size(23, 22); this.toolStripButtonSaveTableToXML.Text = "toolStripButton3"; this.toolStripButtonSaveTableToXML.ToolTipText = Loc.Instance.GetString("Save table to an XML file"); this.toolStripButtonSaveTableToXML.Click += new System.EventHandler(this.toolStripButtonSaveTableToXML_Click); // // toolStripSeparator3 // this.toolStripSeparator3.Name = "toolStripSeparator3"; this.toolStripSeparator3.Size = new System.Drawing.Size(6, 25); // // toolStripButtonInsert // this.toolStripButtonInsert.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButtonInsert.Image = FileUtils.GetImage_ForDLL("basket_add.png"); this.toolStripButtonInsert.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButtonInsert.Name = "toolStripButtonInsert"; this.toolStripButtonInsert.Size = new System.Drawing.Size(23, 22); this.toolStripButtonInsert.Text = "toolStripButton3"; this.toolStripButtonInsert.ToolTipText = Loc.Instance.GetString("Insert row"); this.toolStripButtonInsert.Click += new System.EventHandler(this.toolStripButtonInsert_Click); // // toolStripButtonNumber // this.toolStripButtonNumber.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButtonNumber.Image = FileUtils.GetImage_ForDLL("tag.png"); this.toolStripButtonNumber.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButtonNumber.Name = "toolStripButtonNumber"; this.toolStripButtonNumber.Size = new System.Drawing.Size(23, 22); this.toolStripButtonNumber.Text = "Auto number"; this.toolStripButtonNumber.ToolTipText = Loc.Instance.GetString("Auto number rows"); this.toolStripButtonNumber.Click += new System.EventHandler(this.AutoNumberClick); // // richTextBox1 // this.richTextBox1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this.richTextBox1.Dock = System.Windows.Forms.DockStyle.Fill; this.richTextBox1.Location = new System.Drawing.Point(0, 13); this.richTextBox1.Name = "richTextBox1"; this.richTextBox1.ReadOnly = true; this.richTextBox1.Size = new System.Drawing.Size(163, 263); this.richTextBox1.TabIndex = 3; this.richTextBox1.Text = "a"; // // openFileDialog1 // this.openFileDialog1.FileName = "openFileDialog1"; // // label1 // this.label1.AutoSize = true; this.label1.Dock = System.Windows.Forms.DockStyle.Top; this.label1.ForeColor = System.Drawing.SystemColors.ActiveCaption; this.label1.Location = new System.Drawing.Point(0, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(78, 13); this.label1.TabIndex = 4; this.label1.Text = "Result Preview"; // // panel1 // this.panel1.Controls.Add(this.richTextBox1); this.panel1.Controls.Add(this.label1); this.panel1.Dock = System.Windows.Forms.DockStyle.Left; this.panel1.Location = new System.Drawing.Point(0, 25); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(163, 276); this.panel1.TabIndex = 5; // // dataGrid1 // //this.dataGrid1.AlternatingBackColor = System.Drawing.Color.WhiteSmoke; this.dataGrid1.BackColor = System.Drawing.Color.Gainsboro; this.dataGrid1.BackgroundColor = System.Drawing.Color.DarkGray; this.dataGrid1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; //this.dataGrid1.CaptionBackColor = System.Drawing.Color.DarkKhaki; //this.dataGrid1.CaptionFont = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold); //this.dataGrid1.CaptionForeColor = System.Drawing.Color.Black; //this.dataGrid1.CaptionVisible = false; //this.dataGrid1.DataMember = global::Worgan2006.Header.Blank; this.dataGrid1.Dock = System.Windows.Forms.DockStyle.Fill; //this.dataGrid1.FlatMode = true; this.dataGrid1.Font = new System.Drawing.Font("Times New Roman", 9F); this.dataGrid1.ForeColor = System.Drawing.Color.Black; // this.dataGrid1.GridLineColor = System.Drawing.Color.Silver; // this.dataGrid1.HeaderBackColor = System.Drawing.Color.Black; // this.dataGrid1.HeaderFont = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold); // this.dataGrid1.HeaderForeColor = System.Drawing.Color.White; // this.dataGrid1.LinkColor = System.Drawing.Color.DarkSlateBlue; this.dataGrid1.Location = new System.Drawing.Point(163, 25); this.dataGrid1.Name = "dataGrid1"; // this.dataGrid1.ParentRowsBackColor = System.Drawing.Color.LightGray; // this.dataGrid1.ParentRowsForeColor = System.Drawing.Color.Black; // this.dataGrid1.PreferredColumnWidth = 150; this.dataGrid1.SafeEditMode = true; // this.dataGrid1.SelectionBackColor = System.Drawing.Color.Firebrick; // this.dataGrid1.SelectionForeColor = System.Drawing.Color.White; this.dataGrid1.Size = new System.Drawing.Size(367, 276); this.dataGrid1.TabIndex = 0; this.dataGrid1.CurrentCellChanged += new System.EventHandler(this.dataGrid1_CurrentCellChanged); // // tablePanel // //this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); //this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoSize = true; this.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.Controls.Add(this.dataGrid1); this.Controls.Add(this.panel1); this.Controls.Add(this.runStrip); this.Name = "tablePanel"; this.Size = new System.Drawing.Size(530, 301); this.runStrip.ResumeLayout(false); this.runStrip.PerformLayout(); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); }
//---------------------------------------------------------------- public static bool ParseConfigFile(string filePath, FileUtils.ConfigFileEntryParseCallback callback) { return FileUtils.ParseConfigFile(filePath, callback, null); }
public static void loadStats(List<Sprite> l, String target) { String path = "Content/Stats/"; List<UnitStats> tempList = new List<UnitStats>(); FileUtils myFileUtil = new FileUtils(); tempList = myFileUtil.FileToSprite(path + target); for (int i = 0; i < l.Count; ++i) l[i].setParam(tempList[i], (int)Vector2.Zero.X, (int)Vector2.Zero.Y); }
public override void DeleteWithoutConfirmation(SharpTreeNode[] nodes) { CancellationTokenSource tokenSource = new CancellationTokenSource(); List<MediaFileItem> mediaFilesToDelete = new List<MediaFileItem>(); foreach (Location location in nodes) { try { FileUtils.iterateFilesInDirectory(new DirectoryInfo(location.FullName), getFiles, mediaFilesToDelete, true); MediaFileState.delete(mediaFilesToDelete, tokenSource.Token); FileUtils fileUtils = new FileUtils(); fileUtils.deleteDirectory(location.FullName); location.Parent.Children.Remove(location); } catch (Exception e) { Logger.Log.Error("Error deleting directory: " + location.FullName, e); MessageBox.Show("Error deleting directory: " + location.FullName + "\n\n" + e.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } } }
public static void SynthesizeTestsForSythesizedValidators(string ratioFile, string filename, string outputFolder) { StreamReader tr = new StreamReader(ratioFile); string ration_line = tr.ReadLine(); HashSet<String> methodSet = new HashSet<String>(); while (ration_line != null) { if (ration_line.StartsWith("Method") && !ration_line.StartsWith("MethodName") && !ration_line.StartsWith("Method_amount")) methodSet.Add(ration_line.Substring(0, ration_line.IndexOf("\t"))); ration_line = tr.ReadLine(); } FileUtils fileUtils = new FileUtils(); fileUtils.SetHowDeepToScan(1); fileUtils.ProcessDir(@"C:\RegExpTesting_workspace\AutomatonToCode\subjects\testable", 1, false, "", ".cs", null); List<string> subNames = fileUtils.GetFileNames(); for (int i = 0; i < subNames.Count; i++) { string allInfo = subNames[i].Substring(subNames[i].LastIndexOf("\\") + 1, subNames[i].Length - subNames[i].LastIndexOf("\\") - 1); string namespaceName = "RegExpChecker" + allInfo.Substring(allInfo.IndexOf("_10_26_2008"), allInfo.IndexOf(".cs") - allInfo.IndexOf("_10_26_2008")); string className = namespaceName.Replace("RegExpChecker", "_1_1_20"); string methodName = "Method" + className.Substring(className.LastIndexOf("_") + 1, className.Length - className.LastIndexOf("_") - 1); if (methodSet.Contains(methodName)) { TextReader tr2 = new StreamReader(filename); String line = tr2.ReadLine(); StringBuilder sb = new StringBuilder(); sb.AppendLine("using " + namespaceName + ";\n"); sb.AppendLine("namespace " + namespaceName); sb.AppendLine("{"); sb.AppendLine("public partial class " + className); sb.AppendLine("{"); int count = 0; while (line != null) { count++; sb.AppendLine("public void " + methodName + "_" + count + "()"); sb.AppendLine("{"); sb.AppendLine("this." + methodName + "(\"" + line + "\");"); sb.AppendLine("}\n"); line = tr2.ReadLine(); } sb.AppendLine("}"); sb.AppendLine("}"); // close the stream tr2.Close(); Console.Out.WriteLine("Print " + allInfo); FileUtils.WriteTxt(sb.ToString(), outputFolder + "\\" + allInfo); } } fileUtils.CleanFileNames(); }
private Names(TextAsset text) { this.textAsset = text; this.names = FileUtils.readTextAsset(this.textAsset, true).ToArray(); }
private static void TryToRunAppSafely() { var tryingToRunFlag = Path.Combine(ApplicationDataDirectory, "Trying to run.flag"); FileUtils.EnsureFileDirectoryExists(tryingToRunFlag); var failedLastTime = File.Exists(tryingToRunFlag); if (failedLastTime) { FileUtils.TryToDelete(tryingToRunFlag); App.CreateAndRun(true); return; } var createdOnce = false; DpiAwareWindow.NewWindowCreated += OnWindowCreated; App.CreateAndRun(false); void OnWindowCreated(object sender, EventArgs args) { if (App.IsSoftwareRenderingModeEnabled()) { DpiAwareWindow.NewWindowCreated -= OnWindowCreated; return; } var window = (DpiAwareWindow)sender; if (TryToCreate()) { if (window.Content == null) { window.Content = new Border(); } window.ContentRendered += OnWindowRendered; } } async void OnWindowRendered(object sender, EventArgs args) { var window = (DpiAwareWindow)sender; window.ContentRendered -= OnWindowRendered; await Task.Yield(); if (!_crashed) { FileUtils.TryToDelete(tryingToRunFlag); } } bool TryToCreate() { if (createdOnce || File.Exists(tryingToRunFlag)) { return(false); } createdOnce = true; File.WriteAllBytes(tryingToRunFlag, new byte[0]); DpiAwareWindow.NewWindowCreated -= OnWindowCreated; return(true); } }
public static bool ParseConfigFile(string filePath, FileUtils.ConfigFileEntryParseCallback callback, object userData) { if (callback == null) { Debug.LogWarning("FileUtils.ParseConfigFile() - no callback given"); return false; } if (!File.Exists(filePath)) { Debug.LogWarning(string.Format("FileUtils.ParseConfigFile() - file {0} does not exist", filePath)); return false; } int num = 1; using (StreamReader streamReader = File.OpenText(filePath)) { string baseKey = string.Empty; while (streamReader.Peek() != -1) { string text = streamReader.ReadLine().Trim(); if (text.Length >= 1) { if (text.ToCharArray()[0] != ';') { if (text.ToCharArray()[0] == '[') { if (text.ToCharArray()[(text.Length - 1)] != ']') { Debug.LogWarning(string.Format("FileUtils.ParseConfigFile() - bad key name \"{0}\" on line {1} in file {2}", text, num, filePath)); } else { baseKey = text.Substring(1, text.Length - 2); } } else { if (!text.Contains("=")) { Debug.LogWarning(string.Format("FileUtils.ParseConfigFile() - bad value pair \"{0}\" on line {1} in file {2}", text, num, filePath)); } else { string[] array = text.Split(new char[] { '=' }); string subKey = array[0].Trim(); string text2 = array[1].Trim(); if (text2.ToCharArray()[0] == '"' && text2.ToCharArray()[(text2.Length - 1)] == '"') { text2 = text2.Substring(1, text2.Length - 2); } callback(baseKey, subKey, text2, userData); } } } } } } return true; }
public static bool IsTrackOutdated(Track track) { if (track.FileSize == null || track.FileSize != FileUtils.SizeInBytes(track.Path) || track.DateFileModified < FileUtils.DateModifiedTicks(track.Path)) { return(true); } else { return(false); } }
private static void DeleteFile(File storeDir, string fileName) { File metadataStore = new File(storeDir, fileName); FileUtils.deleteFile(metadataStore); }
public void SelectTests(string testFolder, string ratioFile, string destinationFolder) { FileUtils fileutil = new FileUtils(); fileutil.SetHowDeepToScan(2); fileutil.ProcessDir(testFolder, 1, true, "", ".cs", null); List<String> fileNames = fileutil.GetFileNames(); StreamReader tr = new StreamReader(ratioFile); string line = tr.ReadLine(); HashSet<String> methodSet = new HashSet<String>(); while (line != null) { if (line.StartsWith("Method") && !line.StartsWith("MethodName") && !line.StartsWith("Method_amount")) methodSet.Add(line.Substring(0, line.IndexOf("\t"))); line = tr.ReadLine(); } for (int i = 0; i < fileNames.Count; i++) { string methodNum = fileNames[i].Substring(fileNames[i].IndexOf("Method"), fileNames[i].Length - fileNames[i].IndexOf("Method")); methodNum = methodNum.Substring(0, methodNum.IndexOf("_")); if (methodSet.Contains(methodNum)) { File.Copy(fileNames[i], fileNames[i].Replace(fileNames[i].Substring(0, fileNames[i].LastIndexOf("\\")), destinationFolder)); } } fileutil.CleanFileNames(); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: private static void deleteStoreDirectory(java.io.File storeDir, String directoryName) throws java.io.IOException private static void DeleteStoreDirectory(File storeDir, string directoryName) { File directory = new File(storeDir, directoryName); FileUtils.deleteRecursively(directory); }
/// <summary> /// Returns true if deleted file was imported otherwise false /// </summary> /// <returns></returns> public bool delete_WLock() { bool isImported = false; if (ItemState == MediaItemState.DELETED) { return (isImported); } FileUtils fileUtils = new FileUtils(); if (ItemState != MediaItemState.FILE_NOT_FOUND) { fileUtils.deleteFile(Location); } if (Metadata != null && Metadata.IsImported) { using (MetadataDbCommands metadataCommands = new MetadataDbCommands()) { metadataCommands.delete(Metadata); } Metadata = null; isImported = true; } ItemState = MediaItemState.DELETED; //Factory.deleteFromDictionary(location); Logger.Log.Info("Deleted: " + Location); return (isImported); }
public async Task ExportAsync(List <IClusterableMatch> matches, string exportFileName) { if (string.IsNullOrEmpty(exportFileName) || matches.Count == 0) { return; } _progressData.Reset("Exporting matches", matches.Count); using (var p = new ExcelPackage()) { await Task.Run(() => { var ws = p.Workbook.Worksheets.Add("matches"); // Start at the top left of the sheet var row = 1; var col = 1; // Rotate the entire top row by 90 degrees ws.Row(row).Style.TextRotation = 90; // Fixed columns var writers = new IColumnWriter[] { new NameWriter(false), matches.Any(match => !string.IsNullOrEmpty(match.Match.TestGuid)) ? new TestIdWriter() : null, !string.IsNullOrEmpty(_testTakerTestId) ? new LinkWriter(_testTakerTestId, _ancestryHostName) : null, new SharedCentimorgansWriter(), matches.Any(match => match.Match.SharedSegments > 0) ? new SharedSegmentsWriter() : null, matches.Any(match => match.Match.LongestBlock > 0) ? new LongestBlockWriter() : null, matches.Any(match => !string.IsNullOrEmpty(match.Match.TreeUrl)) ? new TreeUrlWriter(_testTakerTestId) : null, matches.Any(match => match.Match.TreeType != SavedData.TreeType.Undetermined) ? new TreeTypeWriter() : null, matches.Any(match => match.Match.TreeSize > 0) ? new TreeSizeWriter() : null, matches.Any(match => match.Match.CommonAncestors?.Count > 0) ? new CommonAncestorsWriter() : null, matches.Any(match => match.Match.Starred) ? new StarredWriter() : null, matches.Any(match => match.Match.HasHint) ? new SharedAncestorHintWriter() : null, new NoteWriter(), }.Where(writer => writer != null).ToArray(); var columnWriters = new ColumnWritersCollection(p, ws, writers, _testTakerTestId); col = columnWriters.WriteHeaders(row, col); var firstMatrixDataRow = row + 1; var firstMatrixDataColumn = col; // One row for each match foreach (var match in matches) { row++; // Row headers col = 1; col = columnWriters.WriteColumns(row, col, match, null); _progressData.Increment(); } col = 1; col = columnWriters.FormatColumns(row, col); // Freeze the column and row headers ws.View.FreezePanes(firstMatrixDataRow, firstMatrixDataColumn); }); FileUtils.Save(p, exportFileName); } }
private void InitBizDir() { FileUtils.CreateDir(KK.CapturesDir()); FileUtils.CreateDir(KK.FlashScreenDir()); }
private void btnLuuKH_ItemClick(object sender, ItemClickEventArgs e) { rowselect = dgvDSKhachHang.FocusedRowHandle; DateTime ngayHienTai = Commons.ConvertStringToDate(DateTime.Now.ToString("dd/MM/yyyy")); DateTime ngaySinh = Commons.ConvertStringToDate(dENgaySinh.Text.ToString().Substring(0, 10)); TimeSpan ngay = ngayHienTai.Subtract(ngaySinh); string maKH = txtMaKH.EditValue.ToString(); string tenNV = Commons.FormatHoTen(txtTenKH.EditValue.ToString()); string diaChi = txtDiaChi.EditValue.ToString(); string gioiTinh = cboGioiTinh.EditValue.ToString(); string sdt = txtSDT.EditValue.ToString(); string cmnd = txtCMND.EditValue.ToString(); string email = txtEmail.EditValue.ToString(); string duongDanHinh = ""; if (string.IsNullOrEmpty(txtTenKH.Text.ToString())) { MessageBox.Show("Tên khách hàng không thể để trống ", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error); errorProvider1.SetError(txtTenKH, "Tên khách hàng không được để trống"); txtTenKH.Focus(); return; } if (!(ngay.Days >= 6570)) { MessageBox.Show("Ngày sinh không hợp lệ, khách hàng phải đủ 18 tuổi", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error); dENgaySinh.EditValue = Commons.ConvertStringToDate("01/01/1990"); dENgaySinh.Focus(); return; } if (string.IsNullOrEmpty(txtSDT.Text.ToString())) { MessageBox.Show("Số điện thoại không được để trống", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error); errorProvider1.SetError(txtSDT, "Số điện thoại không được để trống"); txtSDT.Focus(); return; } if (string.IsNullOrEmpty(txtEmail.Text.ToString())) { MessageBox.Show("Email không được để trống", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error); errorProvider1.SetError(txtEmail, "Email không được để trống"); txtEmail.Focus(); return; } if (khachHang.KiemTraSDT(sdt, maKH)) { MessageBox.Show("Số điện thoại này đã tồn tại", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error); errorProvider1.SetError(txtSDT, "Số điện thoại đã có người sử dụng"); txtSDT.Focus(); return; } if (!Commons.KiemTraEmailHopLe(txtEmail.Text.ToString())) { MessageBox.Show("Email không hợp lệ", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error); txtEmail.Focus(); return; } if (khachHang.KiemTraEmail(email, maKH)) { MessageBox.Show("Email này đã tồn tại", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error); errorProvider1.SetError(txtEmail, "Email này đã tồn tại"); txtEmail.Focus(); return; } if (khachHang.KiemTraCMND(cmnd, maKH)) { MessageBox.Show("Chứng minh nhân đã tồn tại", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error); errorProvider1.SetError(txtCMND, "Chứng minh nhân đã tồn tại"); txtCMND.Focus(); return; } if (string.IsNullOrEmpty(diaChi)) { MessageBox.Show("Bạn chưa nhập địa chỉ", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error); errorProvider1.SetError(txtDiaChi, "Bạn chưa nhập địa chỉ"); txtDiaChi.Focus(); return; } KhachHangModel nv = new KhachHangModel(); nv.MaKH = maKH; nv.HoTenKH = tenNV; nv.DiaChi = diaChi; nv.GioiTinh = gioiTinh; nv.NgaySinh = ngaySinh; nv.SDT = sdt; nv.CMND = cmnd; nv.Email = email; nv.TinhTrang = 1; if (!string.IsNullOrEmpty(duongDanHinh)) { nv.DuongDanHinh = duongDanHinh; } if (check) { if (!khachHang.themKhachHang(nv)) { MessageBox.Show("Thêm khách hàng lỗi", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } else { SplashScreenManager.ShowForm(this, typeof(WaitLoadFrm)); if (checkTaoTK.Checked) { Random random = new Random(); string mk = random.Next(999999).ToString(); TaiKhoanKH tk = new TaiKhoanKH(); tk.TaiKhoan = sdt; tk.MatKhau = mk; tk.Email = email; tk.TinhTrang = 0; tk.MaKhachHang = maKH; if (khachHang.ThemTKKhachHang(tk)) { GMail gMail = new GMail(); gMail.GuiEmailTaiKhoanKH(email, tenNV, sdt, mk); SplashScreenManager.CloseDefaultSplashScreen(); } else { MessageBox.Show("Lỗi tạo tài khoản cho khách hàng " + txtMaKH.Text, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information); } } MessageBox.Show("Thêm khách hàng " + txtMaKH.Text + " thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information); Click_BtnLuu(); } } else { if (!khachHang.suaKhachHang(nv)) { MessageBox.Show("Sửa khách hàng " + txtMaKH.Text + " lỗi!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } else { Click_BtnLuu(); MessageBox.Show("Sửa khách hàng " + txtMaKH.Text + " thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information); } } if (!string.IsNullOrEmpty(duongDanHinh) && !checkimg) { FileUtils.SaveFile(pathHinh, duongDanHinh, pEHinh); } LayDSKhachHang(); dgvDSKhachHang.FocusedRowHandle = rowselect; }
public void TestCut() { FileUtils.CreateDirectory(savePath); var image = ImageUtils.ReadFileToImage(filePath); //缩略图 image.ThumbnailImage(300, 150).Save(FileUtils.Combine(savePath, "缩略图.png")); ImageUtils.MakeThumbnail(filePath, 500, 450, FileUtils.Combine(savePath, "thumb.png")); //水印 //文字水印 ImageUtils.AddTextWatermark(filePath, "这是一个测试", "#ffffff", "微软雅黑", WatermarkPosition.MiddleCenter, 0.6f, FileUtils.Combine(savePath, "文本水印.png")); //图片水印 string watermarkPic = SystemUtils.GetMapPath("/TestSource/logo.png"); ImageUtils.AddImageWatermark(filePath, watermarkPic, WatermarkPosition.MiddleCenter, 0.6f, FileUtils.Combine(savePath, "图片水印.png")); }
/// <summary> /// Called when the GUI should be rendered. /// </summary> public void OnGUI() { GUILayout.BeginVertical(); GUILayout.Label(String.Format("Android Resolver (version {0}.{1}.{2})", AndroidResolverVersionNumber.Value.Major, AndroidResolverVersionNumber.Value.Minor, AndroidResolverVersionNumber.Value.Build)); scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition); GUI.skin.label.wordWrap = true; GUILayout.BeginVertical(); GUILayout.BeginHorizontal(); GUILayout.Label("Use Gradle Daemon", EditorStyles.boldLabel); settings.useGradleDaemon = EditorGUILayout.Toggle(settings.useGradleDaemon); GUILayout.EndHorizontal(); GUILayout.Label( settings.useGradleDaemon ? ("Gradle Daemon will be used to fetch dependencies. " + "This is faster but can be flakey in some environments.") : ("Gradle Daemon will not be used. This is slow but reliable.")); GUILayout.BeginHorizontal(); GUILayout.Label("Enable Auto-Resolution", EditorStyles.boldLabel); settings.enableAutoResolution = EditorGUILayout.Toggle(settings.enableAutoResolution); GUILayout.EndHorizontal(); GUILayout.Label( settings.enableAutoResolution ? ("Android libraries will be downloaded and processed in the editor.") : ("Android libraries will *not* be downloaded or processed in the editor.")); GUILayout.BeginHorizontal(); GUILayout.Label("Enable Resolution On Build", EditorStyles.boldLabel); settings.autoResolveOnBuild = EditorGUILayout.Toggle(settings.autoResolveOnBuild); GUILayout.EndHorizontal(); GUILayout.Label( settings.autoResolveOnBuild ? ("Android libraries will be downloaded and processed in a pre-build step.") : ("Android libraries will *not* be downloaded or processed in a pre-build step.")); GUILayout.BeginHorizontal(); GUILayout.Label("Install Android Packages", EditorStyles.boldLabel); settings.installAndroidPackages = EditorGUILayout.Toggle(settings.installAndroidPackages); GUILayout.EndHorizontal(); if (ConfigurablePackageDir) { GUILayout.BeginHorizontal(); string previousPackageDir = settings.packageDir; GUILayout.Label("Package Directory", EditorStyles.boldLabel); if (GUILayout.Button("Browse")) { string path = EditorUtility.OpenFolderPanel("Set Package Directory", PackageDir, ""); int startOfPath = path.IndexOf(AndroidPluginsDir); settings.packageDir = FileUtils.PosixPathSeparators( startOfPath < 0 ? "" : path.Substring(startOfPath, path.Length - startOfPath)); } if (!previousPackageDir.Equals(settings.packageDir)) { settings.packageDir = ValidatePackageDir(settings.packageDir); } GUILayout.EndHorizontal(); settings.packageDir = FileUtils.PosixPathSeparators( EditorGUILayout.TextField(settings.packageDir)); } GUILayout.BeginHorizontal(); GUILayout.Label("Explode AARs", EditorStyles.boldLabel); settings.explodeAars = EditorGUILayout.Toggle(settings.explodeAars); GUILayout.EndHorizontal(); if (settings.explodeAars) { GUILayout.Label("AARs will be exploded (unpacked) when ${applicationId} " + "variable replacement is required in an AAR's " + "AndroidManifest.xml or a single target ABI is selected " + "without a compatible build system."); } else { GUILayout.Label("AAR explosion will be disabled in exported Gradle builds " + "(Unity 5.5 and above). You will need to set " + "android.defaultConfig.applicationId to your bundle ID in your " + "build.gradle to generate a functional APK."); } // Disable the ability to toggle the auto-resolution disabled warning // when auto resolution is enabled. EditorGUI.BeginDisabledGroup(settings.enableAutoResolution || settings.autoResolveOnBuild); GUILayout.BeginHorizontal(); GUILayout.Label("Auto-Resolution Disabled Warning", EditorStyles.boldLabel); settings.autoResolutionDisabledWarning = EditorGUILayout.Toggle(settings.autoResolutionDisabledWarning); GUILayout.EndHorizontal(); EditorGUI.EndDisabledGroup(); // Disable the ability to toggle the auto-resolution disabled warning // when auto resolution is enabled. EditorGUI.BeginDisabledGroup(!settings.enableAutoResolution); GUILayout.BeginHorizontal(); GUILayout.Label("Prompt Before Auto-Resolution", EditorStyles.boldLabel); settings.promptBeforeAutoResolution = EditorGUILayout.Toggle(settings.promptBeforeAutoResolution); GUILayout.EndHorizontal(); EditorGUI.EndDisabledGroup(); GUILayout.BeginHorizontal(); GUILayout.Label("Patch AndroidManifest.xml", EditorStyles.boldLabel); settings.patchAndroidManifest = EditorGUILayout.Toggle(settings.patchAndroidManifest); GUILayout.EndHorizontal(); if (settings.patchAndroidManifest) { GUILayout.Label(String.Format( "Instances of \"applicationId\" variable references will be replaced in " + "{0} with the bundle ID. If the bundle ID " + "is changed the previous bundle ID will be replaced with the new " + "bundle ID by the plugin.\n\n" + "This works around a bug in Unity 2018.x where the " + "\"applicationId\" variable is not replaced correctly.", AndroidManifestPath)); } else { GUILayout.Label(String.Format( "{0} is not modified.\n\n" + "If you're using Unity 2018.x and have an AndroidManifest.xml " + "that uses the \"applicationId\" variable, your build may fail.", AndroidManifestPath)); } GUILayout.BeginHorizontal(); GUILayout.Label("Patch mainTemplate.gradle", EditorStyles.boldLabel); settings.patchMainTemplateGradle = EditorGUILayout.Toggle(settings.patchMainTemplateGradle); GUILayout.EndHorizontal(); if (settings.patchMainTemplateGradle) { GUILayout.Label( "If Gradle builds are enabled and a mainTemplate.gradle file is present, " + "the mainTemplate.gradle file will be patched with dependencies managed " + "by the Android Resolver."); } else { GUILayout.Label(String.Format( "If Gradle builds are enabled and a mainTemplate.gradle file is present, " + "the mainTemplate.gradle file will not be modified. Instead dependencies " + "managed by the Android Resolver will be added to the project under {0}", settings.packageDir)); } if (settings.patchMainTemplateGradle) { GUILayout.BeginHorizontal(); string previousDir = settings.localMavenRepoDir; GUILayout.Label("Local Maven Repo Directory", EditorStyles.boldLabel); if (GUILayout.Button("Browse")) { string path = EditorUtility.OpenFolderPanel("Set Local Maven Repo Directory", settings.localMavenRepoDir, ""); int startOfPath = path.IndexOf( FileUtils.ASSETS_FOLDER + Path.DirectorySeparatorChar); settings.localMavenRepoDir = FileUtils.PosixPathSeparators( startOfPath < 0 ? DefaultLocalMavenRepoDir : path.Substring(startOfPath, path.Length - startOfPath)); } if (!previousDir.Equals(settings.localMavenRepoDir)) { settings.localMavenRepoDir = ValidateLocalMavenRepoDir(settings.localMavenRepoDir); } GUILayout.EndHorizontal(); GUILayout.Label( "Please pick a folder under Assets folder. Currently it won't work at " + "any folder under \"Assets/Plugins/Android\""); settings.localMavenRepoDir = FileUtils.PosixPathSeparators( ValidateLocalMavenRepoDir(EditorGUILayout.TextField( settings.localMavenRepoDir))); } GUILayout.BeginHorizontal(); GUILayout.Label("Use Jetifier.", EditorStyles.boldLabel); settings.useJetifier = EditorGUILayout.Toggle(settings.useJetifier); GUILayout.EndHorizontal(); if (settings.useJetifier) { GUILayout.Label( "Legacy Android support libraries and references to them from other " + "libraries will be rewritten to use Jetpack using the Jetifier tool. " + "Enabling option allows an application to use Android Jetpack " + "when other libraries in the project use the Android support libraries."); } else { GUILayout.Label( "Class References to legacy Android support libraries (pre-Jetpack) will be " + "left unmodified in the project. This will possibly result in broken Android " + "builds when mixing legacy Android support libraries and Jetpack libraries."); } if (settings.useJetifier) { GUILayout.BeginHorizontal(); GUILayout.Label("Patch gradleTemplate.properties", EditorStyles.boldLabel); settings.patchPropertiesTemplateGradle = EditorGUILayout.Toggle(settings.patchPropertiesTemplateGradle); GUILayout.EndHorizontal(); GUILayout.Label( "For Unity 2019.3 and above, it is recommended to enable Jetifier " + "and AndroidX via gradleTemplate.properties. Please enable " + "Custom Gradle Properties Template' found under 'Player Settings > " + "Settings for Android > Publishing Settings' menu item. " + "This has no effect in older versions of Unity."); } settings.analyticsSettings.RenderGui(); GUILayout.BeginHorizontal(); GUILayout.Label("Verbose Logging", EditorStyles.boldLabel); settings.verboseLogging = EditorGUILayout.Toggle(settings.verboseLogging); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("Use project settings", EditorStyles.boldLabel); settings.useProjectSettings = EditorGUILayout.Toggle(settings.useProjectSettings); GUILayout.EndHorizontal(); GUILayout.Space(10); if (GUILayout.Button("Reset to Defaults")) { // Load default settings into the dialog but preserve the state in the user's // saved preferences. var backupSettings = new Settings(); RestoreDefaultSettings(); PlayServicesResolver.analytics.Report("settings/reset", "Settings Reset"); LoadSettings(); backupSettings.Save(); } GUILayout.BeginHorizontal(); bool closeWindow = GUILayout.Button("Cancel"); if (closeWindow) { PlayServicesResolver.analytics.Report("settings/cancel", "Settings Cancel"); } bool ok = GUILayout.Button("OK"); closeWindow |= ok; if (ok) { PlayServicesResolver.analytics.Report( "settings/save", new KeyValuePair<string, string>[] { new KeyValuePair<string, string>( "useGradleDaemon", SettingsDialog.UseGradleDaemon.ToString()), new KeyValuePair<string, string>( "enableAutoResolution", SettingsDialog.EnableAutoResolution.ToString()), new KeyValuePair<string, string>( "installAndroidPackages", SettingsDialog.InstallAndroidPackages.ToString()), new KeyValuePair<string, string>( "explodeAars", SettingsDialog.ExplodeAars.ToString()), new KeyValuePair<string, string>( "patchAndroidManifest", SettingsDialog.PatchAndroidManifest.ToString()), new KeyValuePair<string, string>( "localMavenRepoDir", SettingsDialog.LocalMavenRepoDir.ToString()), new KeyValuePair<string, string>( "useJetifier", SettingsDialog.UseJetifier.ToString()), new KeyValuePair<string, string>( "verboseLogging", SettingsDialog.VerboseLogging.ToString()), new KeyValuePair<string, string>( "autoResolutionDisabledWarning", SettingsDialog.AutoResolutionDisabledWarning.ToString()), new KeyValuePair<string, string>( "promptBeforeAutoResolution", SettingsDialog.PromptBeforeAutoResolution.ToString()), }, "Settings Save"); settings.Save(); PlayServicesResolver.OnSettingsChanged(); } if (closeWindow) Close(); GUILayout.EndHorizontal(); GUILayout.EndVertical(); EditorGUILayout.EndScrollView(); GUILayout.EndVertical(); }
private string ProcessUrls(string html, string baseUrl) { var matches = urlRegEx.Matches(html); string contentType = null; byte[] linkData = null; foreach (Match match in matches) { string matched = match.Value; if (string.IsNullOrEmpty(matched)) { continue; } var url = matched.Substring(5, matched.Length - 7); if (url.StartsWith("http")) { var http = new WebClient(); linkData = http.DownloadData(url); contentType = http.ResponseHeaders[System.Net.HttpResponseHeader.ContentType]; } else { if (url.StartsWith("file:///")) { url = url.Substring(8); } if (baseUrl.StartsWith("file:///")) { baseUrl = baseUrl.Substring(8); } var basePath = Path.GetDirectoryName(baseUrl); basePath += "\\"; if (!string.IsNullOrEmpty(basePath) && !basePath.EndsWith("/") && !basePath.EndsWith("\\")) { basePath += "\\"; } int atQ = url.IndexOf("?"); if (atQ > -1) { url = url.Substring(0, atQ); } try { url = FileUtils.NormalizePath(basePath + url); url = FileUtils.GetPhysicalPath(url); contentType = mmFileUtils.GetImageMediaTypeFromFilename(url); if (contentType == "application/image") { continue; } linkData = File.ReadAllBytes(url); } catch { continue; } } if (linkData == null) { continue; } string data = $"data:{contentType};base64,{Convert.ToBase64String(linkData)}"; var replace = "url('" + data + "')"; html = html.Replace(matched, replace); } return(html); }
public override void Rename(string id, string newFileName, bool newEnabled) { if (!Directories.Actual) { return; } if (id == null) { throw new ArgumentNullException(nameof(id)); } var wrapper = GetWrapperById(id); if (wrapper == null) { throw new ArgumentException(ToolsStrings.AcObject_IdIsWrong, nameof(id)); } var currentLocation = ((AcCommonObject)wrapper.Value).Location; var currentExtended = ((UserChampionshipObject)wrapper.Value).ExtendedFilename; var currentPreview = ((UserChampionshipObject)wrapper.Value).PreviewImage; var path = newEnabled ? Directories.EnabledDirectory : Directories.DisabledDirectory; if (path == null) { throw new ToggleException(ToolsStrings.AcObject_CannotBeMoved); } if (!File.Exists(currentExtended)) { currentExtended = null; } if (!File.Exists(currentPreview)) { currentPreview = null; } var newLocation = Path.Combine(path, newFileName); var newBasePart = Path.GetFileName(newLocation).ApartFromLast(UserChampionshipObject.FileExtension); var newExtended = currentExtended == null ? null : Path.Combine(path, newBasePart + UserChampionshipObject.FileDataExtension); var newPreview = currentPreview == null ? null : Path.Combine(path, newBasePart + UserChampionshipObject.FilePreviewExtension); if (FileUtils.Exists(newLocation) || currentExtended != null && File.Exists(newExtended) || currentPreview != null && File.Exists(newPreview)) { throw new ToggleException(ToolsStrings.AcObject_PlaceIsTaken); } try { using (IgnoreChanges()) { FileUtils.Move(currentLocation, newLocation); if (currentExtended != null) { FileUtils.Move(currentExtended, newExtended); } if (currentPreview != null) { FileUtils.Move(currentPreview, newPreview); } var obj = CreateAndLoadAcObject(newFileName, Directories.CheckIfEnabled(newLocation)); obj.PreviousId = id; ReplaceInList(id, new AcItemWrapper(this, obj)); UpdateList(); } } catch (Exception e) { throw new ToggleException(e.Message); } }
public static bool IsSsCmsExists(string directoryPath) { return(FileUtils.IsFileExists(PathUtils.Combine(directoryPath, Constants.ConfigFileName)) && FileUtils.IsFileExists(PathUtils.Combine(directoryPath, "appsettings.json")) && DirectoryUtils.IsDirectoryExists(Constants.WwwrootDirectory)); }
private void SelectLocalImageFile_Click(object sender, RoutedEventArgs e) { var fd = new OpenFileDialog { DefaultExt = ".png", Filter = "Image files (*.png;*.jpg;*.gif;)|*.png;*.jpg;*.jpeg;*.gif|All Files (*.*)|*.*", CheckFileExists = true, RestoreDirectory = true, Multiselect = false, Title = "Embed Image" }; if (!string.IsNullOrEmpty(MarkdownFile)) { fd.InitialDirectory = System.IO.Path.GetDirectoryName(MarkdownFile); } else { if (!string.IsNullOrEmpty(mmApp.Configuration.LastImageFolder)) { fd.InitialDirectory = mmApp.Configuration.LastImageFolder; } else { fd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); } } var res = fd.ShowDialog(); if (res == null || !res.Value) { return; } Image = fd.FileName; if (PasteAsBase64Content) { Base64EncodeImage(fd.FileName); ImagePreview.Source = new BitmapImage(new Uri(fd.FileName)); return; } // Normalize the path relative to the Markdown file if (!string.IsNullOrEmpty(MarkdownFile) && MarkdownFile != "untitled") { var imgUrl = AddinManager.Current.RaiseOnSaveImage(fd.FileName); if (!string.IsNullOrEmpty(imgUrl)) { Image = imgUrl; TextImageText.Focus(); return; } string mdPath = Path.GetDirectoryName(MarkdownFile); string relPath = fd.FileName; try { relPath = FileUtils.GetRelativePath(fd.FileName, mdPath); } catch (Exception ex) { mmApp.Log($"Failed to get relative path.\r\nFile: {fd.FileName}, Path: {mdPath}", ex); } if (!relPath.StartsWith("..\\")) { Image = relPath; } else { // not relative var mbres = MessageBox.Show( "The image you are linking, is not in a relative path.\r\n" + "Do you want to copy it to a local path?", "Non-relative Image", MessageBoxButton.YesNo, MessageBoxImage.Question); if (mbres.Equals(MessageBoxResult.Yes)) { string newImageFileName = System.IO.Path.Combine(mdPath, System.IO.Path.GetFileName(fd.FileName)); var sd = new SaveFileDialog { Filter = "Image files (*.png;*.jpg;*.gif;)|*.png;*.jpg;*.jpeg;*.gif|All Files (*.*)|*.*", FilterIndex = 1, FileName = newImageFileName, InitialDirectory = mdPath, CheckFileExists = false, OverwritePrompt = true, CheckPathExists = true, RestoreDirectory = true }; var result = sd.ShowDialog(); if (result != null && result.Value) { try { File.Copy(fd.FileName, sd.FileName, true); } catch (Exception ex) { MessageBox.Show("Couldn't copy file to new location: \r\n" + ex.Message, mmApp.ApplicationName); return; } try { relPath = FileUtils.GetRelativePath(sd.FileName, mdPath); } catch (Exception ex) { mmApp.Log($"Failed to get relative path.\r\nFile: {sd.FileName}, Path: {mdPath}", ex); } Image = relPath; } } else { Image = relPath; } } } if (Image.Contains(":\\")) { Image = "file:///" + Image; } else { Image = Image.Replace("\\", "/"); } SetImagePreview("file:///" + fd.FileName); IsMemoryImage = false; mmApp.Configuration.LastImageFolder = Path.GetDirectoryName(fd.FileName); TextImageText.Focus(); }
private void SelectLocalLinkFile_Click(object sender, RoutedEventArgs e) { var fd = new OpenFileDialog { DefaultExt = ".html", Filter = "Linkable Files (*.html,*.htm,*.md,*.pdf;*.zip)|*.html;*.htm;*.md;*.pdf;*.zip|All Files (*.*)|*.*", CheckFileExists = true, RestoreDirectory = true, Multiselect = false, Title = "Embed a local relative link" }; if (!string.IsNullOrEmpty(MarkdownFile)) { fd.InitialDirectory = System.IO.Path.GetDirectoryName(MarkdownFile); } else { fd.InitialDirectory = mmApp.Configuration.LastFolder; } var res = fd.ShowDialog(); if (res == null || !res.Value) { return; } Link = fd.FileName; // Normalize the path relative to the Markdown file if (!string.IsNullOrEmpty(MarkdownFile)) { string mdPath = System.IO.Path.GetDirectoryName(MarkdownFile); string relPath = fd.FileName; try { relPath = FileUtils.GetRelativePath(fd.FileName, mdPath); } catch (Exception ex) { mmApp.Log($"Failed to get relative path.\r\nFile: {fd.FileName}, Path: {mdPath}", ex); } // not relative if (!relPath.StartsWith("..\\")) { Link = relPath.Replace("\\", "/"); } // is it a physical path? if (Link.Contains(":\\")) { Link = "file:///" + Link; } } Link = StringUtils.UrlEncode(Link); mmApp.Configuration.LastFolder = System.IO.Path.GetDirectoryName(fd.FileName); TextLink.Focus(); }
/// <summary> /// Saves an image loaded from clipboard to disk OR if base64 is checked /// creates the base64 content. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Button_SaveImage(object sender, RoutedEventArgs e) { string imagePath = null; var bitmapSource = ImagePreview.Source as BitmapSource; if (bitmapSource == null) { MessageBox.Show("Unable to convert bitmap source.", "Bitmap conversion error", MessageBoxButton.OK, MessageBoxImage.Warning); return; } using (var bitMap = WindowUtilities.BitmapSourceToBitmap(bitmapSource)) { imagePath = AddinManager.Current.RaiseOnSaveImage(bitMap); if (PasteAsBase64Content) { Base64EncodeImage(bitMap); IsMemoryImage = false; return; } } if (!string.IsNullOrEmpty(imagePath)) { TextImage.Text = imagePath; IsMemoryImage = false; return; } string initialFolder = null; if (!string.IsNullOrEmpty(Document.Filename) && Document.Filename != "untitled") { initialFolder = Path.GetDirectoryName(Document.Filename); } var sd = new SaveFileDialog { Filter = "Image files (*.png;*.jpg;*.gif;)|*.png;*.jpg;*.jpeg;*.gif|All Files (*.*)|*.*", FilterIndex = 1, Title = "Save Image from Clipboard as", InitialDirectory = initialFolder, CheckFileExists = false, OverwritePrompt = true, CheckPathExists = true, RestoreDirectory = true }; var result = sd.ShowDialog(); if (result != null && result.Value) { imagePath = sd.FileName; try { var ext = Path.GetExtension(imagePath)?.ToLower(); using (var fileStream = new FileStream(imagePath, FileMode.Create)) { BitmapEncoder encoder = null; if (ext == ".png") { encoder = new PngBitmapEncoder(); } else if (ext == ".jpg") { encoder = new JpegBitmapEncoder(); } else if (ext == ".gif") { encoder = new GifBitmapEncoder(); } encoder.Frames.Add(BitmapFrame.Create(ImagePreview.Source as BitmapSource)); encoder.Save(fileStream); if (ext == ".png") { mmFileUtils.OptimizePngImage(sd.FileName, 5); // async } } } catch (Exception ex) { MessageBox.Show("Couldn't copy file to new location: \r\n" + ex.Message, mmApp.ApplicationName); return; } string relPath = Path.GetDirectoryName(sd.FileName); if (initialFolder != null) { try { relPath = FileUtils.GetRelativePath(sd.FileName, initialFolder); } catch (Exception ex) { mmApp.Log($"Failed to get relative path.\r\nFile: {sd.FileName}, Path: {imagePath}", ex); } imagePath = relPath; } if (imagePath.Contains(":\\")) { imagePath = "file:///" + imagePath; } imagePath = imagePath.Replace("\\", "/"); this.Image = imagePath; IsMemoryImage = false; } }
public override List <StockBasicInfo> fetchFromLocalCsvOrWindAndSaveAndCache(int localCsvExpiration = 5, bool appendMode = false, String tag = null, string code = null, DateTime startDate = new DateTime(), DateTime endDate = new DateTime()) { if (tag == null) { tag = typeof(StockBasicInfo).Name; } List <StockBasicInfo> data = null; List <StockBasicInfo> preList = null; List <string> existCode = null; DateTime today = DateUtils.PreviousOrCurrentTradeDay(DateTime.Today); var filePathPattern = _buildCacheDataFilePath(tag, code, "*"); var todayFilePath = _buildCacheDataFilePath(tag, code, DateTime.Now.ToString("yyyyMMdd")); var dirPath = Path.GetDirectoryName(filePathPattern); if (Directory.Exists(dirPath) == false) { Directory.CreateDirectory(dirPath); } var fileNamePattern = Path.GetFileName(filePathPattern); var allFilePaths = Directory.EnumerateFiles(dirPath, fileNamePattern) .OrderByDescending(fn => fn).ToList(); var lastestFilePath = (allFilePaths == null || allFilePaths.Count == 0) ? null : allFilePaths[0]; if (lastestFilePath != null) { try { preList = readFromLocalCsv(lastestFilePath); existCode = preList.Where(x => x.delistDate > today).Select(x => x.code).ToList(); } catch (Exception e) { log.Error(e, "股票基本信息历史数据读取错误!"); } } var daysdiff = FileUtils.GetCacheDataFileDaysPastTillToday(lastestFilePath); if (daysdiff > localCsvExpiration && Caches.WindConnection == true) { //CacheData太旧,需要远程更新,然后保存到本地CacheData目录 var txt = (daysdiff == int.MaxValue) ? "不存在" : "已过期" + daysdiff + "天"; log.Info("本地csv文件{0},尝试Wind读取新数据...", txt); try { data = readFromWind(date: today, tag: tag, existCode: existCode, preList: preList); } catch (Exception e) { log.Error(e, "从Wind读取数据失败!"); } log.Info("正在保存新数据到本地..."); try { if (lastestFilePath == null) { //新增 saveToLocalCsvFile(data, todayFilePath, appendMode, tag); log.Debug("文件{0}已保存.", todayFilePath); } else { //修改 saveToLocalCsvFile(data, lastestFilePath, appendMode, tag); //重命名为最新日期 File.Move(lastestFilePath, todayFilePath); log.Debug("文件重命名为{0}", todayFilePath); } } catch (Exception e) { log.Error(e); } } else { //CacheData不是太旧,直接读取 log.Info("正在从本地csv文件{0}读取数据... ", lastestFilePath); try { data = readFromLocalCsv(lastestFilePath); } catch (Exception e) { log.Error(e, "从本地csv文件读取数据失败!"); } } if (data != null) { //加载到内存缓存 if (tag != "TradeDays") { tag = tag + '_' + code; } Caches.put(tag, data); log.Info("已将{0}加载到内存缓存.", tag); log.Info("获取{0}数据列表成功.共{1}行.", tag, data.Count); } else { log.Warn("没有任何内容可以缓存!"); } return(data); }
public static async Task Execute(IJobContext context) { if (!CliUtils.ParseArgs(Options, context.Args)) { return; } if (_isHelp) { PrintUsage(); return; } try { if (string.IsNullOrEmpty(_userName)) { await CliUtils.PrintErrorAsync("未设置参数管理员用户名:{userName} !"); return; } if (string.IsNullOrEmpty(_password)) { await CliUtils.PrintErrorAsync("未设置参数管理员密码:{password} !"); return; } if (_password.Length < 6) { await CliUtils.PrintErrorAsync("管理员密码必须大于6位 !"); return; } if (!EUserPasswordRestrictionUtils.IsValid(_password, EUserPasswordRestrictionUtils.GetValue(EUserPasswordRestriction.LetterAndDigit))) { await CliUtils.PrintErrorAsync($"管理员密码不符合规则,请包含{EUserPasswordRestrictionUtils.GetText(EUserPasswordRestriction.LetterAndDigit)}"); return; } var webConfigPath = PathUtils.Combine(CliUtils.PhysicalApplicationPath, "web.config"); if (!FileUtils.IsFileExists(webConfigPath)) { await CliUtils.PrintErrorAsync($"系统配置文件不存在:{webConfigPath}!"); return; } if (string.IsNullOrEmpty(WebConfigUtils.ConnectionString)) { await CliUtils.PrintErrorAsync("web.config 中数据库连接字符串 connectionString 未设置"); return; } WebConfigUtils.Load(CliUtils.PhysicalApplicationPath, "web.config"); await Console.Out.WriteLineAsync($"数据库类型: {WebConfigUtils.DatabaseType.Value}"); await Console.Out.WriteLineAsync($"连接字符串: {WebConfigUtils.ConnectionString}"); await Console.Out.WriteLineAsync($"系统文件夹: {CliUtils.PhysicalApplicationPath}"); if (!DataProvider.DatabaseDao.IsConnectionStringWork(WebConfigUtils.DatabaseType, WebConfigUtils.ConnectionString)) { await CliUtils.PrintErrorAsync("系统无法连接到 web.config 中设置的数据库"); return; } if (!SystemManager.IsNeedInstall()) { await CliUtils.PrintErrorAsync("系统已安装在 web.config 指定的数据库中,命令执行失败"); return; } WebConfigUtils.UpdateWebConfig(WebConfigUtils.IsProtectData, WebConfigUtils.DatabaseType, WebConfigUtils.ConnectionString, WebConfigUtils.ApiPrefix, WebConfigUtils.AdminDirectory, WebConfigUtils.HomeDirectory, StringUtils.GetShortGuid(), false); DataProvider.Reset(); SystemManager.InstallDatabase(_userName, _password); } catch (Exception e) { await CliUtils.PrintErrorAsync(e.Message); return; } await Console.Out.WriteLineAsync("恭喜,系统安装成功!"); }
public override IEnumerable <string> Process() { var paramFile = options.OutputFile + ".param"; options.SaveToFile(options.OutputFile + ".param"); var bedfile = new BedItemFile <BedItem>(6); Progress.SetMessage("building chromosome name map ..."); var mitoName = "M"; Dictionary <string, string> chrNameMap = new Dictionary <string, string>(); var ff = new FastaFormat(int.MaxValue); var faiFile = options.FastaFile + ".fai"; if (File.Exists(faiFile)) { using (StreamReader sr = new StreamReader(faiFile)) { string line; while ((line = sr.ReadLine()) != null) { var name = line.Split('\t')[0]; chrNameMap[name] = name; if (name.StartsWith("chr")) { chrNameMap[name.StringAfter("chr")] = name; } if (!name.StartsWith("chr")) { chrNameMap["chr" + name] = name; } if (name.Equals("chrMT") || name.Equals("MT")) { mitoName = "MT"; } if (name.Equals("chrM") || name.Equals("M")) { mitoName = "M"; } } } } else { using (StreamReader sr = new StreamReader(options.FastaFile)) { Sequence seq; while ((seq = ff.ReadSequence(sr)) != null) { var name = seq.Name; chrNameMap[name] = name; if (name.StartsWith("chr")) { chrNameMap[name.StringAfter("chr")] = name; } if (!name.StartsWith("chr")) { chrNameMap["chr" + name] = name; } if (name.Equals("chrMT") || name.Equals("MT")) { mitoName = "MT"; } if (name.Equals("chrM") || name.Equals("M")) { mitoName = "M"; } } } } var longMitoName = chrNameMap[mitoName]; Progress.SetMessage("mitochondral chromosome name = {0}", longMitoName); var mirnas = new List <BedItem>(); if (File.Exists(options.MiRBaseFile)) { Progress.SetMessage("Processing {0} ...", options.MiRBaseFile); if (options.MiRBaseFile.EndsWith(".bed")) { mirnas = bedfile.ReadFromFile(options.MiRBaseFile); mirnas.ForEach(m => { m.Seqname = m.Seqname.StringAfter("chr"); m.Name = options.MiRBaseKey + ":" + m.Name; }); } else { using (var gf = new GtfItemFile(options.MiRBaseFile)) { GtfItem item; while ((item = gf.Next(options.MiRBaseKey)) != null) { BedItem loc = new BedItem(); loc.Seqname = item.Seqname.StringAfter("chr"); loc.Start = item.Start - 1; loc.End = item.End; loc.Name = options.MiRBaseKey + ":" + item.Attributes.StringAfter("Name=").StringBefore(";"); loc.Score = 1000; loc.Strand = item.Strand; mirnas.Add(loc); } } } Progress.SetMessage("{0} miRNA readed.", mirnas.Count); } List <BedItem> trnas = new List <BedItem>(); if (File.Exists(options.UcscTrnaFile)) { //reading tRNA from ucsc table without mitocondrom tRNA Progress.SetMessage("Processing {0} ...", options.UcscTrnaFile); trnas = bedfile.ReadFromFile(options.UcscTrnaFile); trnas.ForEach(m => m.Seqname = m.Seqname.StringAfter("chr")); var removed = trnas.Where(m => (m.Seqname.Length > 1) && !m.Seqname.All(n => char.IsDigit(n))).ToList(); if (removed.Count != trnas.Count) { //remove the tRNA not from 1-22, X and Y trnas.RemoveAll(m => (m.Seqname.Length > 1) && !m.Seqname.All(n => char.IsDigit(n))); //mitocondrom tRNA will be extracted from ensembl gtf file trnas.RemoveAll(m => m.Seqname.Equals("M") || m.Seqname.Equals("MT")); } trnas.ForEach(m => m.Name = GetTRNAName(m.Name)); Progress.SetMessage("{0} tRNA from ucsc readed.", trnas.Count); if (File.Exists(options.UcscMatureTrnaFastaFile)) { var seqs = SequenceUtils.Read(options.UcscMatureTrnaFastaFile); foreach (var seq in seqs) { var tRNAName = GetTRNAName(seq.Name); trnas.Add(new BedItem() { Seqname = seq.Name, Start = 0, End = seq.SeqString.Length, Strand = '+', Name = tRNAName, Sequence = seq.SeqString }); } } } var others = new List <BedItem>(); if (File.Exists(options.EnsemblGtfFile)) { //reading smallRNA/tRNA from ensembl gtf file Progress.SetMessage("Processing {0} ...", options.EnsemblGtfFile); using (var gf = new GtfItemFile(options.EnsemblGtfFile)) { var biotypes = new HashSet <string>(SmallRNAConsts.Biotypes); biotypes.Remove(SmallRNAConsts.miRNA); GtfItem item; int count = 0; while ((item = gf.Next("gene")) != null) { string biotype; if (item.Attributes.Contains("gene_biotype")) { biotype = item.Attributes.StringAfter("gene_biotype \"").StringBefore("\""); } else if (item.Attributes.Contains("gene_type")) { biotype = item.Attributes.StringAfter("gene_type \"").StringBefore("\""); } else { continue; } if (File.Exists(options.UcscTrnaFile) && biotype.Equals(SmallRNAConsts.tRNA)) { continue; } if (biotype.Equals("Mt_tRNA")) { count++; var gene_name = item.Attributes.Contains("gene_name") ? item.Attributes.StringAfter("gene_name \"").StringBefore("\"") : item.GeneId; BedItem loc = new BedItem(); loc.Seqname = mitoName; loc.Start = item.Start - 1; loc.End = item.End; loc.Name = string.Format(SmallRNAConsts.mt_tRNA + ":" + longMitoName + ".tRNA{0}-{1}", count, gene_name.StringAfter("-")); loc.Score = 1000; loc.Strand = item.Strand; trnas.Add(loc); } else if (biotypes.Contains(biotype)) { string seqName; if (item.Seqname.ToLower().StartsWith("chr")) { seqName = item.Seqname.Substring(3); } else { seqName = item.Seqname; } if (seqName.Equals("M") || seqName.Equals("MT")) { seqName = mitoName; } //ignore all smallRNA coordinates on scaffold or contig. //if (seqName.Length > 5) //{ // continue; //} var gene_name = item.Attributes.StringAfter("gene_name \"").StringBefore("\""); var lowGeneName = gene_name.ToLower(); if (lowGeneName.StartsWith("rny") || lowGeneName.Equals("y_rna")) { biotype = "yRNA"; } BedItem loc = new BedItem(); loc.Seqname = seqName; loc.Start = item.Start - 1; loc.End = item.End; //if (lowGeneName.EndsWith("_rrna") && loc.Length < 200) //{ // biotype = "rRNA"; //} loc.Name = biotype + ":" + gene_name + ":" + item.GeneId; loc.Score = 1000; loc.Strand = item.Strand; others.Add(loc); } } } } var all = new List <BedItem>(); all.AddRange(mirnas); all.AddRange(trnas); all.AddRange(others); foreach (var bi in all) { if (chrNameMap.ContainsKey(bi.Seqname)) { bi.Seqname = chrNameMap[bi.Seqname]; } } if (File.Exists(options.RRNAFile)) { var seqs = SequenceUtils.Read(options.RRNAFile); foreach (var seq in seqs) { all.Add(new BedItem() { Seqname = seq.Name, Start = 0, End = seq.SeqString.Length, Strand = '+', Name = "rRNA:" + SmallRNAConsts.rRNADB_KEY + seq.Name }); } } Progress.SetMessage("Saving smallRNA coordinates to " + options.OutputFile + "..."); using (var sw = new StreamWriter(options.OutputFile)) { foreach (var pir in SmallRNAConsts.Biotypes) { var locs = all.Where(m => m.Name.StartsWith(pir)).ToList(); Progress.SetMessage("{0} : {1}", pir, locs.Count); GenomeUtils.SortChromosome(locs, m => m.Seqname, m => (int)m.Start); foreach (var loc in locs) { sw.WriteLine(bedfile.GetValue(loc)); } } } var miRNA_bed = FileUtils.ChangeExtension(options.OutputFile, ".miRNA.bed"); Progress.SetMessage("Saving miRNA coordinates to " + miRNA_bed + "..."); using (var sw = new StreamWriter(miRNA_bed)) { var pir = SmallRNAConsts.miRNA; var locs = all.Where(m => m.Name.StartsWith(pir)).ToList(); Progress.SetMessage("{0} : {1}", pir, locs.Count); GenomeUtils.SortChromosome(locs, m => m.Seqname, m => (int)m.Start); foreach (var loc in locs) { sw.WriteLine(bedfile.GetValue(loc)); } } Progress.SetMessage("Saving smallRNA miss1 coordinates to " + options.OutputFile + ".miss1 ..."); using (var sw = new StreamWriter(options.OutputFile + ".miss1")) { foreach (var pir in SmallRNAConsts.Biotypes) { if (pir == SmallRNABiotype.lincRNA.ToString() || pir == SmallRNABiotype.lncRNA.ToString()) { continue; } var locs = all.Where(m => m.Name.StartsWith(pir)).ToList(); locs.RemoveAll(l => l.Name.Contains(SmallRNAConsts.rRNADB_KEY)); Progress.SetMessage("{0} : {1}", pir, locs.Count); GenomeUtils.SortChromosome(locs, m => m.Seqname, m => (int)m.Start); foreach (var loc in locs) { sw.WriteLine(bedfile.GetValue(loc)); } } } Progress.SetMessage("Saving smallRNA miss1 coordinates to " + options.OutputFile + ".miss0 ..."); using (var sw = new StreamWriter(options.OutputFile + ".miss0")) { foreach (var pir in SmallRNAConsts.Biotypes) { if (pir != SmallRNABiotype.lincRNA.ToString() && pir != SmallRNABiotype.lncRNA.ToString() && pir != SmallRNABiotype.rRNA.ToString()) { continue; } var locs = all.Where(m => m.Name.StartsWith(pir)).ToList(); if (pir == SmallRNABiotype.rRNA.ToString()) { locs.RemoveAll(l => !l.Name.Contains(SmallRNAConsts.rRNADB_KEY)); } Progress.SetMessage("{0} : {1}", pir, locs.Count); GenomeUtils.SortChromosome(locs, m => m.Seqname, m => (int)m.Start); foreach (var loc in locs) { sw.WriteLine(bedfile.GetValue(loc)); } } } var summaryFile = options.OutputFile + ".info"; Progress.SetMessage("Writing summary to " + summaryFile + "..."); using (var sw = new StreamWriter(summaryFile)) { sw.WriteLine("Biotype\tCount"); all.ConvertAll(m => m.Name).Distinct().GroupBy(m => m.StringBefore(":")).OrderByDescending(m => m.Count()).ToList().ForEach(m => sw.WriteLine("{0}\t{1}", m.Key, m.Count())); } var result = new List <string>(new[] { options.OutputFile }); var fasta = Path.ChangeExtension(options.OutputFile, ".fasta"); if ((File.Exists(options.UcscTrnaFile) && File.Exists(options.UcscMatureTrnaFastaFile)) || File.Exists(options.RRNAFile)) { result.Add(fasta); using (var sw = new StreamWriter(fasta)) { string line; using (var sr = new StreamReader(options.FastaFile)) { while ((line = sr.ReadLine()) != null) { sw.WriteLine(line); } } if (File.Exists(options.UcscTrnaFile) && File.Exists(options.UcscMatureTrnaFastaFile)) { using (var sr = new StreamReader(options.UcscMatureTrnaFastaFile)) { while ((line = sr.ReadLine()) != null) { sw.WriteLine(line); } } } if (File.Exists(options.RRNAFile)) { using (var sr = new StreamReader(options.RRNAFile)) { while ((line = sr.ReadLine()) != null) { sw.WriteLine(line); } } } } } var faFile = options.OutputFile + ".fa"; Progress.SetMessage("Extracting sequence from " + options.FastaFile + "..."); var b2foptions = new Bed2FastaProcessorOptions() { GenomeFastaFile = options.FastaFile, InputFile = options.OutputFile, OutputFile = faFile, KeepChrInName = false, }; if (!File.Exists(options.UcscMatureTrnaFastaFile)) { b2foptions.AcceptName = m => m.StartsWith(SmallRNAConsts.miRNA) || m.StartsWith(SmallRNAConsts.mt_tRNA) || m.StartsWith(SmallRNAConsts.tRNA); } else { b2foptions.AcceptName = m => m.StartsWith(SmallRNAConsts.miRNA) || m.StartsWith(SmallRNAConsts.mt_tRNA); } new Bed2FastaProcessor(b2foptions) { Progress = this.Progress }.Process(); if (File.Exists(options.UcscMatureTrnaFastaFile)) { Progress.SetMessage("Extracting sequence from " + options.UcscMatureTrnaFastaFile + " ..."); using (var sw = new StreamWriter(faFile, true)) { foreach (var tRNA in trnas) { if (!string.IsNullOrEmpty(tRNA.Sequence)) { sw.WriteLine(">{0}", tRNA.Name); sw.WriteLine("{0}", tRNA.Sequence); } } } } return(result); }
private static async Task <object> ParseImplAsync(IParseManager parseManager, NameValueCollection attributes, bool isGetPicUrlFromAttribute, string channelIndex, string channelName, int upLevel, int topLevel, string type, int no, bool isOriginal, bool isClearTags, string src, string altSrc) { var databaseManager = parseManager.DatabaseManager; var pageInfo = parseManager.PageInfo; var contextInfo = parseManager.ContextInfo; object parsedContent = null; var contentId = 0; //判断是否图片地址由标签属性获得 if (!isGetPicUrlFromAttribute) { contentId = contextInfo.ContentId; } var contextType = contextInfo.ContextType; var picUrl = string.Empty; if (!string.IsNullOrEmpty(src)) { picUrl = src; } else { if (contextType == ParseType.Undefined) { contextType = contentId != 0 ? ParseType.Content : ParseType.Channel; } if (contextType == ParseType.Content)//获取内容图片 { var contentInfo = await parseManager.GetContentAsync(); if (isOriginal) { if (contentInfo != null && contentInfo.ReferenceId > 0 && contentInfo.SourceId > 0) { var targetChannelId = contentInfo.SourceId; //var targetSiteId = databaseManager.ChannelRepository.GetSiteId(targetChannelId); var targetSiteId = await databaseManager.ChannelRepository.GetSiteIdAsync(targetChannelId); var targetSite = await databaseManager.SiteRepository.GetAsync(targetSiteId); var targetNodeInfo = await databaseManager.ChannelRepository.GetAsync(targetChannelId); //var targetContentInfo = databaseManager.ContentRepository.GetContentInfo(tableStyle, tableName, contentInfo.ReferenceId); var targetContentInfo = await databaseManager.ContentRepository.GetAsync(targetSite, targetNodeInfo, contentInfo.ReferenceId); if (targetContentInfo != null && targetContentInfo.ChannelId > 0) { contentInfo = targetContentInfo; } } } if (contentInfo == null) { contentInfo = await databaseManager.ContentRepository.GetAsync(pageInfo.Site, contextInfo.ChannelId, contentId); } if (contentInfo != null) { if (no <= 1) { picUrl = contentInfo.Get <string>(type); } else { var extendName = ColumnsManager.GetExtendName(type, no - 1); picUrl = contentInfo.Get <string>(extendName); } } } else if (contextType == ParseType.Channel)//获取栏目图片 { var dataManager = new StlDataManager(parseManager.DatabaseManager); var channelId = await dataManager.GetChannelIdByLevelAsync(pageInfo.SiteId, contextInfo.ChannelId, upLevel, topLevel); channelId = await dataManager.GetChannelIdByChannelIdOrChannelIndexOrChannelNameAsync(pageInfo.SiteId, channelId, channelIndex, channelName); var channel = await databaseManager.ChannelRepository.GetAsync(channelId); if (type == nameof(Content.ImageUrl)) { picUrl = channel.ImageUrl; } else { if (no <= 1) { picUrl = channel.Get <string>(type); } else { var extendName = ColumnsManager.GetExtendName(type, no - 1); picUrl = channel.Get <string>(extendName); } } } else if (contextType == ParseType.Each) { picUrl = contextInfo.ItemContainer.EachItem.Value as string; } } if (string.IsNullOrEmpty(picUrl)) { picUrl = altSrc; } if (!string.IsNullOrEmpty(picUrl)) { var extension = PathUtils.GetExtension(picUrl); if (FileUtils.IsFlash(extension)) { parsedContent = await StlPdf.ParseAsync(parseManager); } else if (FileUtils.IsPlayer(extension)) { parsedContent = await StlPlayer.ParseAsync(parseManager); } else { parsedContent = await parseManager.PathManager.ParseSiteUrlAsync(pageInfo.Site, picUrl, pageInfo.IsLocal); if (!isClearTags) { attributes["src"] = (string)parsedContent; parsedContent = $@"<img {TranslateUtils.ToAttributesString(attributes)}>"; } } } return(parsedContent); }
protected override void ImportTypeLibrary() { TlbImpTask tlbImp = new TlbImpTask(); // parent is solution task tlbImp.Parent = SolutionTask; // inherit project from solution task tlbImp.Project = SolutionTask.Project; // inherit namespace manager from solution task tlbImp.NamespaceManager = SolutionTask.NamespaceManager; // inherit verbose setting from solution task tlbImp.Verbose = SolutionTask.Verbose; // make sure framework specific information is set tlbImp.InitializeTaskConfiguration(); tlbImp.TypeLib = new FileInfo(GetTypeLibrary()); tlbImp.OutputFile = new FileInfo(WrapperAssembly); tlbImp.Namespace = TypeLibraryName; // according to "COM Programming with Microsoft .NET" (page 59) // the /sysarray option should always be set in order to // generate wrappers that match those generated by VS.NET tlbImp.SysArray = true; // use other imported type libraries to resolve references // // there's one serious limitation in the current implementation: // // if type library A references type library B, then we should // first import type library B and use a reference to that // imported type library when we import type library A. // // however, we have no way to find out in which order the type // libraries should be imported. So only if type library B is // first listed in the project file, it will work fine. // // we should find a way to analyse a type library to determine // dependencies on other type libraries // // according to JR ([email protected]) a possible // solution could be to "use TypeLibConverter.ConvertTypeLibToAssembly. // This has a callback of type ITypeLibImporterNotifySink, which I // speculate allows one to recognize when one type library // depends on another. I believe what you have to do is start // with an arbitrary type library, and if that type library calls // back on the ResolveRef() method, and if that type library is // one you were planning to add later, you compile it // immediately and pass the assembly back out of ResolveRef. I // haven't tested this yet, but it's my best understanding of // how it all works. foreach (ReferenceBase reference in Parent.References) { // we're only interested in imported type libraries WrapperReferenceBase wrapper = reference as WrapperReferenceBase; // avoid stack overflow causes by mutual dependencies if (wrapper == null || !wrapper.IsCreated || wrapper.WrapperTool != "tlbimp") { continue; } tlbImp.References.Includes.Add(wrapper.WrapperAssembly); } if (ProjectSettings.AssemblyOriginatorKeyFile != null) { tlbImp.KeyFile = new FileInfo(FileUtils.CombinePaths(Parent.ProjectDirectory.FullName, ProjectSettings.AssemblyOriginatorKeyFile)); } if (ProjectSettings.AssemblyKeyContainerName != null) { tlbImp.KeyContainer = ProjectSettings.AssemblyKeyContainerName; } // increment indentation level tlbImp.Project.Indent(); try { // execute task tlbImp.Execute(); } finally { // restore indentation level tlbImp.Project.Unindent(); } }
public async Task <ActionResult <List <SubmitResult> > > Submit([FromBody] SubmitRequest request) { var result = new List <SubmitResult>(); if (request.SiteId > 0) { var site = await _siteRepository.GetAsync(request.SiteId); if (site == null) { return(this.Error("无法确定内容对应的站点")); } foreach (var filePath in request.FilePaths) { if (string.IsNullOrEmpty(filePath)) { continue; } var fileName = PathUtils.GetFileName(filePath); var fileExtName = StringUtils.ToLower(PathUtils.GetExtension(filePath)); var localDirectoryPath = await _pathManager.GetUploadDirectoryPathAsync(site, fileExtName); var virtualUrl = await _pathManager.GetVirtualUrlByPhysicalPathAsync(site, filePath); var imageUrl = await _pathManager.ParseSiteUrlAsync(site, virtualUrl, true); if (request.IsMaterial) { var materialFileName = PathUtils.GetMaterialFileName(fileName); var virtualDirectoryPath = PathUtils.GetMaterialVirtualDirectoryPath(UploadType.Image); var directoryPath = _pathManager.ParsePath(virtualDirectoryPath); var materialFilePath = PathUtils.Combine(directoryPath, materialFileName); DirectoryUtils.CreateDirectoryIfNotExists(materialFilePath); FileUtils.CopyFile(filePath, materialFilePath, true); var image = new MaterialImage { GroupId = -request.SiteId, Title = fileName, Url = PageUtils.Combine(virtualDirectoryPath, materialFileName) }; await _materialImageRepository.InsertAsync(image); } if (request.IsThumb) { var localSmallFileName = Constants.SmallImageAppendix + fileName; var localSmallFilePath = PathUtils.Combine(localDirectoryPath, localSmallFileName); var thumbnailVirtualUrl = await _pathManager.GetVirtualUrlByPhysicalPathAsync(site, localSmallFilePath); var thumbnailUrl = await _pathManager.ParseSiteUrlAsync(site, thumbnailVirtualUrl, true); _pathManager.ResizeImageByMax(filePath, localSmallFilePath, request.ThumbWidth, request.ThumbHeight); if (request.IsLinkToOriginal) { result.Add(new SubmitResult { ImageUrl = thumbnailUrl, ImageVirtualUrl = thumbnailVirtualUrl, PreviewUrl = imageUrl, PreviewVirtualUrl = virtualUrl }); } else { FileUtils.DeleteFileIfExists(filePath); result.Add(new SubmitResult { ImageUrl = thumbnailUrl, ImageVirtualUrl = thumbnailVirtualUrl }); } } else { result.Add(new SubmitResult { ImageUrl = imageUrl, ImageVirtualUrl = virtualUrl }); } } var options = TranslateUtils.JsonDeserialize(site.Get <string>(nameof(LayerImageUploadController)), new Options { IsEditor = true, IsMaterial = true, IsThumb = false, ThumbWidth = 1024, ThumbHeight = 1024, IsLinkToOriginal = true, }); options.IsEditor = request.IsEditor; options.IsMaterial = request.IsMaterial; options.IsThumb = request.IsThumb; options.ThumbWidth = request.ThumbWidth; options.ThumbHeight = request.ThumbHeight; options.IsLinkToOriginal = request.IsLinkToOriginal; site.Set(nameof(LayerImageUploadController), TranslateUtils.JsonSerialize(options)); await _siteRepository.UpdateAsync(site); } else if (request.UserId > 0) { foreach (var filePath in request.FilePaths) { if (string.IsNullOrEmpty(filePath)) { continue; } var fileName = PathUtils.GetFileName(filePath); var userFilePath = _pathManager.GetUserUploadPath(request.UserId, fileName); FileUtils.CopyFile(filePath, userFilePath, true); var imageUrl = _pathManager.GetUserUploadUrl(request.UserId, fileName); result.Add(new SubmitResult { ImageUrl = imageUrl, ImageVirtualUrl = imageUrl }); } } return(result); }
public Hashtable GetCoverageList(string foldername) { Hashtable ht = new Hashtable(); FileUtils fileutil = new FileUtils(); fileutil.SetHowDeepToScan(2); fileutil.ProcessDir(foldername, 1, true, "_", ".xml", null); List<String> fileNames = fileutil.GetFileNames(); for (int i = 0; i < fileNames.Count; i++) { ReportAnalyzor ra = new ReportAnalyzor(); string[] method_ratio = ra.ExtractCoverageInfo(fileNames[i]); ht.Add(method_ratio[0], (float)System.Convert.ToSingle(method_ratio[1])); Console.WriteLine(i + "/" + fileNames.Count + " MethodName: " + method_ratio[0] + " BlockCoverage: " + (float)System.Convert.ToSingle(method_ratio[1])); } fileutil.CleanFileNames(); return ht; }
private void ExecuteExternalFormCapture() { // Result file holds filename in temp folder string resultFilePath = Path.Combine(Path.GetTempPath(), "ScreenCapture.result"); string imageFolder = null; imageFolder = Path.GetDirectoryName(Model.ActiveDocument.Filename); var helper = new WindowInteropHelper((Window)Model.Window); var handle = helper.Handle; if (File.Exists(resultFilePath)) { File.Delete(resultFilePath); } string args = $@"""{imageFolder}"" {handle} {Model.Window.Left} {Model.Window.Top}"; try { var process = Process.Start(new ProcessStartInfo() { FileName = Path.Combine(Environment.CurrentDirectory, "Addins", "ScreenCapture.exe"), Arguments = args }); process.WaitForExit(); } catch (Exception ex) { MessageBox.Show("Unable to capture screen shot.\r\n" + ex.Message, mmApp.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Warning); return; } if (!File.Exists(resultFilePath)) { return; } // read the location for the captured image so we can embed a link to it string capturedFile = File.ReadAllText(resultFilePath); if (string.IsNullOrEmpty(capturedFile) || capturedFile.StartsWith("Cancelled") || !File.Exists(capturedFile)) { return; } capturedFile = FileUtils.GetRelativePath(capturedFile, imageFolder); string relPath = capturedFile.Replace("\\", "/"); if (relPath.StartsWith("..")) { relPath = capturedFile; } if (relPath.Contains(":\\")) // full path { relPath = "file:///" + relPath.Replace("\\", "/"); } string replaceText = "![](" + relPath + ")"; // Push the new text into the Editor's Selection SetSelection(replaceText); }
private void iq_Closed(object sender, EventArgs e) { IncreaseQuota iq = sender as IncreaseQuota; if (iq == null || iq.DialogResult.GetValueOrDefault(false)) { Calculations.RegisterModel(typeof(Rawr.Bear.CalculationsBear)); Calculations.RegisterModel(typeof(Rawr.Cat.CalculationsCat)); Calculations.RegisterModel(typeof(Rawr.DPSDK.CalculationsDPSDK)); Calculations.RegisterModel(typeof(Rawr.DPSWarr.CalculationsDPSWarr)); Calculations.RegisterModel(typeof(Rawr.Elemental.CalculationsElemental)); Calculations.RegisterModel(typeof(Rawr.Enhance.CalculationsEnhance)); Calculations.RegisterModel(typeof(Rawr.Healadin.CalculationsHealadin)); Calculations.RegisterModel(typeof(Rawr.HealPriest.CalculationsHealPriest)); Calculations.RegisterModel(typeof(Rawr.Hunter.CalculationsHunter)); Calculations.RegisterModel(typeof(Rawr.Mage.CalculationsMage)); Calculations.RegisterModel(typeof(Rawr.Moonkin.CalculationsMoonkin)); Calculations.RegisterModel(typeof(Rawr.ProtPaladin.CalculationsProtPaladin)); Calculations.RegisterModel(typeof(Rawr.ProtWarr.CalculationsProtWarr)); Calculations.RegisterModel(typeof(Rawr.RestoSham.CalculationsRestoSham)); Calculations.RegisterModel(typeof(Rawr.Retribution.CalculationsRetribution)); Calculations.RegisterModel(typeof(Rawr.Rogue.CalculationsRogue)); Calculations.RegisterModel(typeof(Rawr.ShadowPriest.CalculationsShadowPriest)); Calculations.RegisterModel(typeof(Rawr.TankDK.CalculationsTankDK)); Calculations.RegisterModel(typeof(Rawr.Tree.CalculationsTree)); Calculations.RegisterModel(typeof(Rawr.Warlock.CalculationsWarlock)); string[] files = new List<string>(Classes.Keys).ToArray(); Buff.LoadDefaultBuffs(null, 85); Enchant.LoadDefaultEnchants(); Tinkering.LoadDefaultTinkerings(); FileUtils f = new FileUtils(files, progressUpdated); f.DownloadIfNotExists(new EventHandler(filesLoaded)); } else { new Base.ErrorBox("Not Enough Storage Space", "Rawr will not work if you do not allow it to increase its available " + "storage size. Please refresh this page and accept to continue.").Show(); } }
public override void SetQuotaLimitOnFolder(string folderPath, string shareNameDrive, QuotaType quotaType, string quotaLimit, int mode, string wmiUserName, string wmiPassword) { Log.WriteStart("SetQuotaLimitOnFolder"); Log.WriteInfo("FolderPath : {0}", folderPath); Log.WriteInfo("QuotaLimit : {0}", quotaLimit); string path = folderPath; if (shareNameDrive != null) { path = Path.Combine(shareNameDrive + @":\", folderPath); } Runspace runSpace = null; try { runSpace = OpenRunspace(); if (path.IndexOfAny(Path.GetInvalidPathChars()) == -1) { if (!FileUtils.DirectoryExists(path)) { FileUtils.CreateDirectory(path); } if (quotaLimit.Contains("-")) { RemoveOldQuotaOnFolder(runSpace, path); } else { var quota = CalculateQuota(quotaLimit); switch (mode) { //deleting old quota and creating new one case 0: { RemoveOldQuotaOnFolder(runSpace, path); ChangeQuotaOnFolder(runSpace, "New-FsrmQuota", path, quotaType, quota); break; } //modifying folder quota case 1: { ChangeQuotaOnFolder(runSpace, "Set-FsrmQuota", path, quotaType, quota); break; } } } } } catch (Exception ex) { Log.WriteError("SetQuotaLimitOnFolder", ex); throw; } finally { CloseRunspace(runSpace); } Log.WriteEnd("SetQuotaLimitOnFolder"); }
public static RegisterInfo getRegisterInfo() { if (registerInfo.VersionType == null) { registerInfo.VersionType = "UN_SUPPORT"; try { if (File.Exists(SystemUtils.getCurrentPath() + "\\license.info")) { //0:company_name,1:end_date,2:version_type String[] info = FileUtils.read("license.info").Split('#'); registerInfo.CompanyName = info[0]; registerInfo.EndDate = info[1]; String keyData = FileUtils.read("license.key"); if (keyData != null) { HardDiskInfo hardDiskInfo = HardInfoUtils.getDiskInfo(0); if (RegisterService.verify(keyData, RegisterService.getRegisterString(registerInfo.CompanyName, "1900-01-01", registerInfo.EndDate, HardInfoUtils.getCpuSerialNumber(), hardDiskInfo.SerialNumber, Convert.ToString(hardDiskInfo.Capacity), info[2]))) { String newDate = DateUtils.getRealSysDate(); if (newDate.Length < 10) { MessageBox.Show("没有取得时间,请在保证网络能连接情况下重启该程序"); registerInfo.VersionType = "CLOSE"; } //判断日期 DateTime nowDT = Convert.ToDateTime(newDate.Substring(0, 10)); DateTime end = Convert.ToDateTime(registerInfo.EndDate); if (nowDT.Subtract(end).TotalDays <= 0) { registerInfo.VersionType = info[2]; } else { MessageBox.Show("您的授权日期:" + end + "已过期,~请与销售联系购买新的许可"); registerInfo.VersionType = "CLOSE"; } } else { MessageBox.Show("序列号不一致~请与销售联系"); registerInfo.VersionType = "CLOSE"; } } else { MessageBox.Show("当前目录下无法找到注册文件license.key,请联系销售购买获得序列号!"); registerInfo.VersionType = "CLOSE"; } } } catch { MessageBox.Show("检查软件许可时出现异常,请重新启动软件"); } } return(registerInfo); }
protected override void ProcessItem(Model.WorkQueue item) { Platform.CheckForNullReference(item, "item"); Platform.CheckForNullReference(item.StudyStorageKey, "item.StudyStorageKey"); bool successful = true; string failureDescription = null; // The processor stores its state in the Data column ReadQueueData(item); if (_queueData.State == null || !_queueData.State.ExecuteAtLeastOnce) { // Added for ticket #9673: // If the study folder does not exist and the study has been archived, trigger a restore and we're done if (!Directory.Exists(StorageLocation.GetStudyPath())) { if (StorageLocation.ArchiveLocations.Count > 0) { Platform.Log(LogLevel.Info, "Reprocessing archived study {0} for Patient {1} (PatientId:{2} A#:{3}) on Partition {4} without study data on the filesystem. Inserting Restore Request.", Study.StudyInstanceUid, Study.PatientsName, Study.PatientId, Study.AccessionNumber, ServerPartition.Description); PostProcessing(item, WorkQueueProcessorStatus.Complete, WorkQueueProcessorDatabaseUpdate.ResetQueueState); // Post process had to be done first so the study is unlocked so the RestoreRequest can be inserted. ServerHelper.InsertRestoreRequest(StorageLocation); RaiseAlert(WorkQueueItem, AlertLevel.Warning, string.Format( "Found study {0} for Patient {1} (A#:{2})on Partition {3} without storage folder, restoring study.", Study.StudyInstanceUid, Study.PatientsName, Study.AccessionNumber, ServerPartition.Description)); return; } } if (Study == null) { Platform.Log(LogLevel.Info, "Reprocessing study {0} on Partition {1}", StorageLocation.StudyInstanceUid, ServerPartition.Description); } else { Platform.Log(LogLevel.Info, "Reprocessing study {0} for Patient {1} (PatientId:{2} A#:{3}) on Partition {4}", Study.StudyInstanceUid, Study.PatientsName, Study.PatientId, Study.AccessionNumber, ServerPartition.Description); } CleanupDatabase(); } else { if (_queueData.State.Completed) { #region SAFE-GUARD CODE: PREVENT INFINITE LOOP // The processor indicated it had completed reprocessing in previous run. The entry should have been removed and this block of code should never be called. // However, we have seen ReprocessStudy entries that mysterously contain rows in the WorkQueueUid table. // The rows prevent the entry from being removed from the database and the ReprocessStudy keeps repeating itself. // update the state first, increment the CompleteAttemptCount _queueData.State.ExecuteAtLeastOnce = true; _queueData.State.Completed = true; _queueData.State.CompleteAttemptCount++; SaveState(item, _queueData); if (_queueData.State.CompleteAttemptCount < 10) { // maybe there was db error in previous attempt to remove the entry. Let's try again. Platform.Log(LogLevel.Info, "Resuming Reprocessing study {0} but it was already completed!!!", StorageLocation.StudyInstanceUid); PostProcessing(item, WorkQueueProcessorStatus.Complete, WorkQueueProcessorDatabaseUpdate.ResetQueueState); } else { // we are definitely stuck. Platform.Log(LogLevel.Error, "ReprocessStudy {0} for study {1} appears stuck. Aborting it.", item.Key, StorageLocation.StudyInstanceUid); item.FailureDescription = "This entry had completed but could not be removed."; PostProcessingFailure(item, WorkQueueProcessorFailureType.Fatal); } return; #endregion } if (Study == null) { Platform.Log(LogLevel.Info, "Resuming Reprocessing study {0} on Partition {1}", StorageLocation.StudyInstanceUid, ServerPartition.Description); } else { Platform.Log(LogLevel.Info, "Resuming Reprocessing study {0} for Patient {1} (PatientId:{2} A#:{3}) on Partition {4}", Study.StudyInstanceUid, Study.PatientsName, Study.PatientId, Study.AccessionNumber, ServerPartition.Description); } } // As per #12583, Creation of the SopInstanceProcessor should occur after the CleanupDatabase() call. var context = new StudyProcessorContext(StorageLocation, WorkQueueItem); // TODO: Should we enforce the patient's name rule? // If we do, the Study record will have the new patient's name // but how should we handle the name in the Patient record? const bool enforceNameRules = false; var processor = new SopInstanceProcessor(context) { EnforceNameRules = enforceNameRules }; var seriesMap = new Dictionary <string, List <string> >(); StudyXml studyXml = LoadStudyXml(); var reprocessedCounter = 0; var skippedCount = 0; var removedFiles = new List <FileInfo>(); try { // Traverse the directories, process 500 files at a time var isCancelled = FileProcessor.Process(StorageLocation.GetStudyPath(), "*.*", delegate(string path, out bool cancel) { #region Reprocess File var file = new FileInfo(path); // ignore all files except those ending ".dcm" // ignore "bad(0).dcm" files too if (Regex.IsMatch(file.Name.ToUpper(), "[0-9]+\\.DCM$")) { try { var dicomFile = new DicomFile(path); dicomFile.Load(DicomReadOptions.StorePixelDataReferences | DicomReadOptions.Default); string seriesUid = dicomFile.DataSet[DicomTags.SeriesInstanceUid].GetString(0, string.Empty); string instanceUid = dicomFile.DataSet[DicomTags.SopInstanceUid].GetString(0, string.Empty); if (studyXml.Contains(seriesUid, instanceUid)) { if (!seriesMap.ContainsKey(seriesUid)) { seriesMap.Add(seriesUid, new List <string>()); } if (!seriesMap[seriesUid].Contains(instanceUid)) { seriesMap[seriesUid].Add(instanceUid); } else { Platform.Log(LogLevel.Warn, "SOP Instance UID in {0} appears more than once in the study.", path); } skippedCount++; } else { Platform.Log(ServerPlatform.InstanceLogLevel, "Reprocessing SOP {0} for study {1}", instanceUid, StorageLocation.StudyInstanceUid); string groupId = ServerHelper.GetUidGroup(dicomFile, StorageLocation.ServerPartition, WorkQueueItem.InsertTime); ProcessingResult result = processor.ProcessFile(groupId, dicomFile, studyXml, true, false, null, null, SopInstanceProcessorSopType.ReprocessedSop); switch (result.Status) { case ProcessingStatus.Success: reprocessedCounter++; if (!seriesMap.ContainsKey(seriesUid)) { seriesMap.Add(seriesUid, new List <string>()); } if (!seriesMap[seriesUid].Contains(instanceUid)) { seriesMap[seriesUid].Add(instanceUid); } else { Platform.Log(LogLevel.Warn, "SOP Instance UID in {0} appears more than once in the study.", path); } break; case ProcessingStatus.Reconciled: Platform.Log(LogLevel.Warn, "SOP was unexpectedly reconciled on reprocess SOP {0} for study {1}. It will be removed from the folder.", instanceUid, StorageLocation.StudyInstanceUid); failureDescription = String.Format("SOP Was reconciled: {0}", instanceUid); // Added for #10620 (Previously we didn't do anything here) // Because we are reprocessing files in the study folder, when file needs to be reconciled it is copied to the reconcile folder // Therefore, we need to delete the one in the study folder. Otherwise, there will be problem when the SIQ entry is reconciled. // InstanceAlreadyExistsException will also be thrown by the SOpInstanceProcessor if this ReprocessStudy WQI // resumes and reprocesses the same file again. // Note: we are sure that the file has been copied to the Reconcile folder and there's no way back. // We must get rid of this file in the study folder. FileUtils.Delete(path); // Special handling: if the file is one which we're supposed to reprocess at the end (see ProcessAdditionalFiles), we must remove the file from the list if (_additionalFilesToProcess != null && _additionalFilesToProcess.Contains(path)) { _additionalFilesToProcess.Remove(path); } break; } } } catch (DicomException ex) { // TODO : should we fail the reprocess instead? Deleting an dicom file can lead to incomplete study. removedFiles.Add(file); Platform.Log(LogLevel.Warn, "Skip reprocessing and delete {0}: Not readable.", path); FileUtils.Delete(path); failureDescription = ex.Message; } } else if (!file.Extension.Equals(".xml") && !file.Extension.Equals(".gz")) { // not a ".dcm" or header file, delete it removedFiles.Add(file); FileUtils.Delete(path); } #endregion if (reprocessedCounter > 0 && reprocessedCounter % 200 == 0) { Platform.Log(LogLevel.Info, "Reprocessed {0} files for study {1}", reprocessedCounter + skippedCount, StorageLocation.StudyInstanceUid); } cancel = reprocessedCounter >= 5000; }, true); if (studyXml != null) { EnsureConsistentObjectCount(studyXml, seriesMap); SaveStudyXml(studyXml); } // Completed if either all files have been reprocessed // or no more dicom files left that can be reprocessed. _completed = reprocessedCounter == 0 || !isCancelled; } catch (Exception e) { successful = false; failureDescription = e.Message; Platform.Log(LogLevel.Error, e, "Unexpected exception when reprocessing study: {0}", StorageLocation.StudyInstanceUid); Platform.Log(LogLevel.Error, "Study may be in invalid unprocessed state. Study location: {0}", StorageLocation.GetStudyPath()); throw; } finally { LogRemovedFiles(removedFiles); // Update the state _queueData.State.ExecuteAtLeastOnce = true; _queueData.State.Completed = _completed; _queueData.State.CompleteAttemptCount++; SaveState(item, _queueData); if (!successful) { FailQueueItem(item, failureDescription); } else { if (!_completed) { // Put it back to Pending PostProcessing(item, WorkQueueProcessorStatus.Pending, WorkQueueProcessorDatabaseUpdate.None); } else { // Reload the record from the database because referenced entities have been modified since the beginning. // Need to reload because we are passing the location to the rule engine. StorageLocation = CollectionUtils.FirstElement <StudyStorageLocation>(StudyStorageLocation.FindStorageLocations(item.ServerPartitionKey, StorageLocation.StudyInstanceUid), null); LogHistory(); // Run Study / Series Rules Engine. var engine = new StudyRulesEngine(StorageLocation, ServerPartition); engine.Apply(ServerRuleApplyTimeEnum.StudyProcessed); // Log the FilesystemQueue related entries StorageLocation.LogFilesystemQueue(); PostProcessing(item, WorkQueueProcessorStatus.Complete, WorkQueueProcessorDatabaseUpdate.ResetQueueState); Platform.Log(LogLevel.Info, "Completed reprocessing of study {0} on partition {1}", StorageLocation.StudyInstanceUid, ServerPartition.Description); } } } }
/// <summary> /// returns true if the moved item was a imported item otherwise false /// </summary> /// <param name="newLocation"></param> /// <param name="progress"></param> /// <returns></returns> public bool move_URLock(String newLocation, CancellableOperationProgressBase progress) { bool isImported = false; if (ItemState == MediaItemState.DELETED) { return (isImported); } FileUtils fileUtils = new FileUtils(); fileUtils.moveFile(Location, newLocation, progress); // A delete event will be fired by the mediafilewatcher for the current item with it's old location. // If location is changed to it's new location it will not be be found in the current mediastate. // So only update the location when mediafilewatcher is not active. EnterWriteLock(); try { Location = newLocation; } finally { ExitWriteLock(false); } return (isImported = Metadata.IsImported); }
public Hashtable GetCoverageList_NodeEdge(string foldername) { Hashtable ht = new Hashtable(); FileUtils fileutil = new FileUtils(); fileutil.SetHowDeepToScan(1); fileutil.ProcessDir(foldername, 1, false, "", ".txt", null); List<String> fileNames = fileutil.GetFileNames(); for (int i = 0; i < fileNames.Count; i++) { string[] info = ExtractCoverageInfo_NodeEdge(fileNames[i]); ht.Add(fileNames[i].Substring(fileNames[i].LastIndexOf("\\") + 1, fileNames[i].IndexOf(".txt") - fileNames[i].LastIndexOf("\\") - 1), info); } fileutil.CleanFileNames(); return ht; }