public GameSetupSvc(AppConfigMgnr conf) { int id = -1; FileHelper fReader = new FileHelper(); var persistentLevels = fReader.ReadFromXml<Level>(conf.GetSetting<string>("LevelFile")); AllLevels = new List<NonPersistentLevel>(); int k = 0; foreach (Level level in persistentLevels) { NonPersistentLevel npl = new NonPersistentLevel(); npl.Lvl = level; npl.Coins = new List<Coin>(); int rasterHalb = level.Raster / 2; for (int i = 0; i < level.Height / level.Raster; i++) // vertical { for (int j = 0; j < level.Width / level.Raster; j++) // horizontal { Coin c = new Coin(); c.Pos = new Point() { X = j * level.Raster + rasterHalb, Y = i * level.Raster + rasterHalb }; c.Id = ++id; npl.Coins.Add(c); } } AllLevels.Add(npl); ++k; } }
static FileHelper() { if (Environment.OSVersion.Platform.ToString ().StartsWith ("Win")) Instance = new FileHelper (); else Instance = new LinuxFileHelper (); }
static void benchmarkingRunFinished(IBenchmarkable sender, BenchmarkResult result) { ConsoleBuilder.AddResult(++FinishedRunCount, sender as RunBenchmark, result); if (CsvFilePath != String.Empty) CsvBuilder.AddResult(FinishedRunCount, sender as RunBenchmark, result); Console.WriteLine("Finished " + FinishedRunCount + "/" + TotalRunCount + " ..."); if (FinishedRunCount >= TotalRunCount) { if (CsvFilePath != String.Empty) { var csvContent = CsvBuilder.Build(); var exporter = new FileHelper(); try { exporter.Save(csvContent, CsvFilePath); } catch (Exception) { Console.WriteLine("Saving CSV failed. Do you have the required access privileges?"); } } Console.Write(ConsoleBuilder.Build()); Console.WriteLine(); Console.WriteLine(); Console.WriteLine("Press any key to exit."); } }
public Form1() { InitializeComponent(); this.label1.Visible = false; this.tableLayoutPanel1.Visible = false; this.pictureBox1.MouseHover += this.Control_MouseHover; this.pictureBox1.MouseWheel += this.pictureBox1_MouseWheel; this.treeView1.MouseHover += this.Control_MouseHover; this.treeView1.DragEnter += this.treeView1_DragEnter; this.treeView1.DragDrop += this.treeView1_DragDrop; this.treeView1.AfterSelect += this.treeView1_AfterSelect; this.dataGridView1.MouseHover += this.Control_MouseHover; this.dataGridView1.Columns.Add("tagName", "Tag name"); this.dataGridView1.Columns.Add("tagValue", "Tag value"); this.dataGridView1.Columns["tagName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; this.dataGridView1.Columns["tagValue"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; this.dataGridView1.RowHeadersWidth = 14; this.workerCompleted = (s, e) => { this.tableLayoutPanel1.Visible = false; this.progressBar1.Value = 0; }; this.progressChanged = (s, e) => { this.progressBar1.Value = e.ProgressPercentage; }; this.fileHelper = new FileHelper(this.treeView1); this.fileHelper.zipCompleted = this.workerCompleted; this.fileHelper.zipProgressChanged = this.progressChanged; this.reader = new Reader(); }
static Connector() { FileHelper = new FileHelper(); PatternParser = new PatternParser(); PatternNormalizer = new PatternNormalizer(); PatternValidator = new PatternValidator(); PatternDispatcher = new PatternDispatcher(); }
public void TestInit() { _fileHelper = new FileHelper(); _rootPath = Path.GetDirectoryName(Uri.UnescapeDataString(new UriBuilder(Assembly.GetExecutingAssembly().CodeBase).Path)); if (Directory.Exists(_rootPath + @"\TestDir")) Directory.Delete(_rootPath + @"\TestDir", true); if (Directory.Exists(_rootPath + @"\TestFile")) Directory.Delete(_rootPath + @"\TestFile", true); }
public DataService() { if (!Windows.ApplicationModel.DesignMode.DesignModeEnabled) { _fileHelper = new FileHelper(); _newsService = new NewsService.NewsService(); } }
static int Main(string[] args) { if (!ValidArgs(args)) { return -1; } currentPass = args[0].Split('=')[1]; destinationDir = args[1].Split('=')[1]; newPass = args[2].Split('=')[1]; instanceType = args[3].Split('=')[1]; defaultInstanceName = args[4].Split('=')[1]; mssqlBasePath = (string)Registry.LocalMachine.OpenSubKey(string.Format(@"SOFTWARE\Microsoft\Microsoft SQL Server\{0}.{1}\Setup", instanceType, defaultInstanceName)).GetValue("SQLPath"); mssqlRegPath = string.Format(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\{0}.{1}", instanceType, defaultInstanceName); workingDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); backupDirectory = Path.Combine(workingDirectory, "sql_instance_backup"); foreach (Process p in Process.GetProcessesByName("sqlservr")) { if (p.MainModule.FileName.ToLower() == Path.Combine(mssqlBasePath, "Binn", "sqlservr.exe").ToLower()) { Output.WriteInfo(string.Format("Stopping SQL Server with pid {0}", p.Id)); p.Kill(); } } BackupSystem(); Process defaultInstance = StartMSSQLInstance(defaultInstanceName, mssqlBasePath); CheckMSSQLInstance("", currentPass); ChangeDatabaseLocations(); ChangeAdminPassword(); Output.WriteInfo("Stopping SQL Server"); defaultInstance.Kill(); Output.WriteInfo("Copying files to new location"); FileHelper fileHelper = new FileHelper(); fileHelper.Copy1(mssqlBasePath, destinationDir); Output.WriteSuccess("Done"); Output.WriteInfo("Restoring databases to default instance"); fileHelper = new FileHelper(); fileHelper.Copy1(Path.Combine(backupDirectory, "MSSQLServer"), Path.Combine(mssqlBasePath, "DATA")); Output.WriteSuccess("Done"); Output.WriteInfo("Cleaning up backup"); Directory.Delete(backupDirectory, true); return 0; }
public FtpHelper(string ip, int port, string username, string password) { this.ip = ip; this.port = port; this.username = username; this.password = password; fileHelper = new FileHelper(); rootUrl = "ftp://" + ip + ":" + port + "/"; }
static FileHelper() { if (Environment.OSVersion.Platform.ToString ().StartsWith ("Win")) Instance = new FileHelper (); else { var path = ((FilePath) typeof (FileHelper).Assembly.Location).GetParent (); var assembly = Assembly.LoadFile (Path.Combine (path, "Sharpen.Unix.dll")); if (assembly == null) throw new Exception ("Sharpen.Unix.dll is required when running on a Unix based system"); Instance = (FileHelper) Activator.CreateInstance (assembly.GetType ("Sharpen.Unix.UnixFileHelper")); } }
internal HttpConnectingClient(SecureTcpListener server, SecurityOptions options, AppFunc next, bool useHandshake, bool usePriorities, bool useFlowControl, List<string> listOfRootFiles) { _listOfRootFiles = listOfRootFiles; _usePriorities = usePriorities; _useHandshake = useHandshake; _useFlowControl = useFlowControl; _server = server; _next = next; _options = options; _fileHelper = new FileHelper(ConnectionEnd.Server); }
public static int constructor(IntPtr l) { try { FileHelper o; o=new FileHelper(); pushValue(l,true); pushValue(l,o); return 2; } catch(Exception e) { return error(l,e); } }
/// <summary> /// </summary> /// <param name="bytefile"></param> /// <param name="fileKey"> </param> /// <param name="param"> </param> /// <returns></returns> public string SaveFile(byte[] bytefile, string fileKey, params object[] param) { FileSaveInfo fileInfo = _currentKey.GetFileSavePath(fileKey, param); Server server = fileInfo.FileServer; var filehelper = new FileHelper { hostIp = server.hostip, password = server.password, username = server.username, startdirname = server.startdirname }; filehelper.WriteFile(fileInfo.Dirname, fileInfo.Savefilename, bytefile); return fileKey; }
private static List<string> LoadJsFiles(HtmlHelper helper, string pathName) { string path = helper.ViewContext.HttpContext.Server.MapPath("~") + "\\Scripts\\" + pathName; string tmpPath = helper.ViewContext.HttpContext.Server.MapPath("~") + "\\Scripts\\"; FileHelper file = new FileHelper(); file.GetFilesByDirectory(path, "*.js"); List<string> arr = file.FileList; List<string> tmpArr = new List<string>(); if (arr!=null && arr.Count>0 ) { for (int i = arr.Count-1; i>=0 ; i--) { int index = arr[i].IndexOf(pathName); string tmp = arr[i].Substring(index, arr[i].Length - index).Replace("\\","/"); tmpArr.Add(tmp); } } return tmpArr; }
public object OnDownload(ISession session, Download e) { try { CurrentFolder folder = GetFolder(session); string filename = folder.Path + e.File; if (!System.IO.File.Exists(filename)) { return new Error { Message = e.File + " not found!" }; } session["DOWNLOAD_TAG"] = new FileHelper(filename); System.IO.FileInfo fi = new System.IO.FileInfo(filename); return new FileInfo { Name=fi.Name, Size= fi.Length }; } catch (Exception e_) { return new Error { Message = e_.Message }; } }
public static FileHelper GetInstance(TestFileType fileType) { lock (syncRoot) { IFilePathProvider provider = GetProvider(fileType); if (_instance == null) { _instance = new FileHelper(provider); } else { if (!_instance._filePathProvider.GetType().Equals(provider.GetType())) { _instance = null; _instance = new FileHelper(provider); } } } return _instance; }
protected void ProcessAllBundles(IList<Bundle> bundles) { Trace.Source.TraceInformation("Processing bundles..."); if (!settings.IsDebuggingEnabled) { foreach (var bundle in bundles) { bundle.Process(settings); } } else { var hasher = new AssignHash(); var diskBacker = new FileHelper(); var bundlesToSort = new List<Bundle>(); var directory = new FileSystemDirectory(DiskBackedBundleCache.CacheDirectory); for (var i = 0; i < bundles.Count; i++) { bundles[i] = ProcessSingleBundle(diskBacker, directory, bundlesToSort, CassetteSettings.uncachedToCachedFiles, bundles[i], hasher); if (typeof(StylesheetBundle).IsAssignableFrom(bundles[i].GetType())) { ((StylesheetBundle)bundles[i]).Renderer = new DebugStylesheetHtmlRenderer(settings.UrlGenerator); } else if (typeof(ScriptBundle).IsAssignableFrom(bundles[i].GetType())) { ((ScriptBundle)bundles[i]).Renderer = new DebugScriptBundleHtmlRenderer(settings.UrlGenerator); } else if (typeof(HtmlTemplateBundle).IsAssignableFrom(bundles[i].GetType())) { ((HtmlTemplateBundle)bundles[i]).Renderer = new DebugHtmlTemplateBundleRenderer(settings.UrlGenerator); bundles[i].ContentType = "text/javascript"; } } CassetteSettings.bundles.FixReferences(CassetteSettings.uncachedToCachedFiles, bundles); bundlesToSort.ForEach(b => b.SortAssetsByDependency()); } Trace.Source.TraceInformation("Bundle processing completed."); }
private List<string> GenerateReport() { if (!Files.Any()) return null; var fileHelper = new FileHelper(); var days = Files.Select(fileHelper.GetEntries).ToList(); var lines = new List<string>(); var runningTotal = new TimeSpan(0, 0, 0, 0); foreach (var d in days) { lines.AddRange(d.Select(entry => entry.ToString())); var hours = d.Sum(te => te.Hours); var minutes = d.Sum(te => te.Minutes); var seconds = d.Sum(te => te.Seconds); var ts = new TimeSpan(0, hours, minutes, seconds); runningTotal = runningTotal.Add(ts); lines.Add(string.Format("---- Total Time For Day ---- {0}:{1:D2}:{2:D2} ---------------", ts.Hours, ts.Minutes, ts.Seconds)); } lines.Add(string.Format("---- Total Time For All Days Selected ---- {0}:{1:D2}:{2:D2} ---------------", (runningTotal.Days * 24 + runningTotal.Hours), runningTotal.Minutes, runningTotal.Seconds)); return lines; }
protected void Application_Start(object sender, EventArgs e) { string path = Server.MapPath("~/"); SysInfo.IsReg = false; SysInfo.DRegStr = "jssl160721"; SysInfo.RegStr = SysInfo.DRegStr; if (SysInfo.IsReg) { myLogger.Info("判断注册!"); SysInfo.SetFilePath(path); SysInfo.IsRegSuccess = false; string regStr = ""; if (FileHelper.IsExists(SysInfo.fileName)) { regStr = FileHelper.ReadFile(SysInfo.fileName); } else { regStr = "00000000000000000000000000000000"; FileHelper.writeFile(SysInfo.fileName, regStr); } if (regStr != SysInfo.GetRegStr2()) { myLogger.Info("注册码不对!序列号为:" + SysInfo.GetRegStr1()); } else { myLogger.Info("注册码正确"); SysInfo.IsRegSuccess = true; } } isClose = false; myLogger.Info("网站启动"); DbHelperSQL.SetConnectionString(ConfigurationManager.AppSettings["ConnectionString"]); GlobalAppModule.IsInitMainLib = true; BaseModule.LoadBaseInfo(); MenuModule.MenuInit(); RoleModule.UpdateRoleInfo(); SysUserModule.UpdateUserInfo(); //SysUserConfigModule.LoadSysUserConfig(); DeviceTypeCodeModule.LoadDeviceTypeCodeInfos(); PriceModule.LoadPriceTypes(); PriceModule.LoadPriceInfos(); CropModule.LoadUnitQuotaInfos(); DistrictModule.UpdateLevelInfo(); DistrictModule.UpdateDistrictInfo(); WaterUserModule.LoadWaterUsers(); DeviceModule.LoadDevices(); //Device_GroundWaterModule.LoadDevices(); CardUserModule.LoadCardUsers(); GlobalAppModule.IsInitMainLib = false; Thread thread = new Thread(new ThreadStart(testConnect)); thread.Start(); Thread threadDeleteXLS = new Thread(new ThreadStart(DeleteXLS)); threadDeleteXLS.Start(); Thread threadRefresh = new Thread(new ThreadStart(Refresh)); threadRefresh.Start(); myLogger.Info("网站启动完成!"); }
public IResult Delete(CarImage carImage) { FileHelper.Delete(carImage.ImagePath); _carImageDal.Delete(carImage); return(new SuccessResult()); }
private void txtPath_KeyPress(object sender, KeyPressEventArgs e) { e.Handled = ((e.KeyChar == '\\' || FileHelper.CheckPathForIllegalChars(e.KeyChar.ToString())) && !char.IsControl(e.KeyChar)); }
private void CreateFile(string fileName, bool landscape = false) { var code = FileHelper.GetTextResource("code1.txt"); if (File.Exists(fileName)) { File.Delete(fileName); } var styleset = new DefaultStyleSet(); if (landscape) { LoadLandScapeSettings(styleset); } var pdf = new PdfCreator(styleset); pdf.SetDocInfo("Test", "Susbject", "Author"); pdf.SetHeader("Kopfzeile", "Header1", @"\\192.168.10.121\softwarestore$\Logos\Intern\logo_bre.png"); pdf.SetFooter("Footer \t<<page>> / <<pages>>"); pdf.CreateTocSection("Inhaltsverzeichnis"); pdf.CreateContentSection(); pdf.AddParagraph("Überschrift 1", "Heading1"); pdf.AddParagraph(TestHelper.Masstext1, "Normal"); pdf.AddParagraph(code, "Code"); pdf.AddParagraph(TestHelper.Masstext1, "Normal"); pdf.AddDefinitionList(TestHelper.GetDefinitionList(), "Normal", "Normal"); pdf.AddParagraph(TestHelper.Masstext1, "Normal"); pdf.AddTable(TestHelper.GetDataTable(), "Tabellenüberschrift", "NoHeading1", "some additional info", "Details", pdf.Width); pdf.AddTableFrame(TestHelper.GetDataTable(), "Tabellenüberschrift Frame", "NoHeading1", "some additional info", "Details", pdf.Width / 2); pdf.AddTableFrame(TestHelper.GetDataTable(), "Tabellenüberschrift Frame", "NoHeading1", null, "Details", pdf.Width / 2); pdf.AddParagraph("Überschrift 2", "Heading1"); pdf.AddParagraph(TestHelper.Masstext1, "Normal"); pdf.AddParagraph("Überschrift 2-1", "Heading2"); pdf.AddParagraph(TestHelper.Masstext1, "Normal"); pdf.AddImage(@"\\192.168.10.121\softwarestore$\Logos\Intern\logo_bre.png", 150, 50); pdf.AddParagraph("Überschrift 2-2", "Heading2"); pdf.AddParagraph(TestHelper.Masstext1, "Normal"); pdf.AddParagraph("Aufzählung 1", "Bullet1"); pdf.AddParagraph("Aufzählung 2", "Bullet1"); pdf.AddParagraph("Aufzählung 3", "Bullet1"); pdf.AddParagraph("Aufzählung 4", "Bullet1"); pdf.AddParagraph(TestHelper.Masstext1, "Normal"); pdf.AddParagraph(code, "Code"); pdf.AddParagraph(TestHelper.Masstext1, "Normal"); pdf.RenderToPdf(fileName, false); Assert.IsTrue(File.Exists(fileName)); TestHelper.OpenFile(fileName); }
/// <summary> /// 日志写入处理 /// </summary> /// <param name="sender">调用者</param> /// <param name="args"><see cref="LogEventArgs"/> 数组</param> protected override void WriteLogInternal(object sender, LogEventArgs[] args) { FileHelper.WriteLog(this.GetFileName(this.LogPath + this.LogFile), this.LogFormat(sender, args, false)); }
private bool DownloadFileWebClient(string remoteFileLocation, string localFilePath) { try { PercentDownloaded = 0; DownloadStatusCode = DownloadStatusCode.Ok; if (WebHelper.UrlExists(remoteFileLocation)) { string outputFolder = Path.GetDirectoryName(localFilePath); if (outputFolder != null && !Directory.Exists(outputFolder)) { Directory.CreateDirectory(outputFolder); } MyWebClient webClient = new MyWebClient { Proxy = null }; using (Stream webStream = webClient.OpenRead(remoteFileLocation)) using (FileStream fileStream = new FileStream(localFilePath, FileMode.Create)) { var buffer = new byte[32768]; int bytesRead; Int64 bytesReadComplete = 0; // Use Int64 for files larger than 2 gb // Get the size of the file to download Int64 bytesTotal = Convert.ToInt64(webClient.ResponseHeaders["Content-Length"]); // Start a new StartWatch for measuring download time Stopwatch sw = Stopwatch.StartNew(); // Download file in chunks while (webStream != null && (bytesRead = webStream.Read(buffer, 0, buffer.Length)) > 0) { bytesReadComplete += bytesRead; fileStream.Write(buffer, 0, bytesRead); // Output current progress to the "Output" editor //StringBuilder sb = new StringBuilder(); // ReSharper disable once PossibleLossOfFraction PercentDownloaded = bytesReadComplete * 100 / bytesTotal; FileSizeRecieved = bytesReadComplete; //sb.AppendLine($"Time Elapsed: {sw.ElapsedMilliseconds:0,.00}s"); //sb.AppendLine( // $"Average Speed: {(sw.ElapsedMilliseconds > 0 ? bytesReadComplete/sw.ElapsedMilliseconds/1.024 : 0):0,0} KB/s"); } sw.Stop(); TotalFileSize += FileSizeRecieved; DownloadStatusCode = DownloadStatusCode.Done; return(true); } } DownloadStatusCode = DownloadStatusCode.UnableDownload; return(false); } catch { DownloadStatusCode = DownloadStatusCode.UnableDownload; if (FileHelper.FileExists(localFilePath)) { FileInfo file = new FileInfo(localFilePath); if (!FileHelper.IsFileLocked(file)) { file.Delete(); } } return(false); } }
protected virtual IWebDriver CreateChromeWebDriver(long loginWaitTime) { DriverOptions driverOptions; IWebDriver driver; driverOptions = BrowserOptionsFactory.Create(); if (string.Equals(ConfigurationReader.GetConfigurationValue(Configuration.EnableDetailedLogging).ToLower(), Infrastructure.Constants.Generic.TrueValue)) { var service = ChromeDriverService.CreateDefaultService(ConfigurationReader.GetConfigurationValue(Configuration.DriverServerLocationKey)); service.LogPath = "chromedriver.log"; service.EnableVerboseLogging = true; driver = new ChromeDriver(service, (ChromeOptions)driverOptions, TimeSpan.FromMinutes(loginWaitTime)); } else { var driverServerLocation = string.IsNullOrWhiteSpace(ConfigurationReader.GetConfigurationValue(Configuration.DriverServerLocationKey)) ? FileHelper.GetCurrentExecutingDirectory() : ConfigurationReader.GetConfigurationValue(Constants.Configuration.DriverServerLocationKey); driver = new ChromeDriver(driverServerLocation, (ChromeOptions)driverOptions, TimeSpan.FromMinutes(loginWaitTime)); } driver.Manage().Cookies.DeleteAllCookies(); return(driver); }
public static List <LogInfo> SystemCmd(EngineState s, CodeCommand cmd) { List <LogInfo> logs = new List <LogInfo>(1); CodeInfo_System info = cmd.Info.Cast <CodeInfo_System>(); SystemType type = info.Type; switch (type) { case SystemType.Cursor: { SystemInfo_Cursor subInfo = info.SubInfo.Cast <SystemInfo_Cursor>(); string iconStr = StringEscaper.Preprocess(s, subInfo.State); if (iconStr.Equals("WAIT", StringComparison.OrdinalIgnoreCase)) { Application.Current?.Dispatcher.Invoke(() => { System.Windows.Input.Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait; }); s.CursorWait = true; logs.Add(new LogInfo(LogState.Success, "Mouse cursor icon set to [Wait]")); } else if (iconStr.Equals("NORMAL", StringComparison.OrdinalIgnoreCase)) { Application.Current?.Dispatcher.Invoke(() => { System.Windows.Input.Mouse.OverrideCursor = null; }); s.CursorWait = false; logs.Add(new LogInfo(LogState.Success, "Mouse cursor icon set to [Normal]")); } else { logs.Add(new LogInfo(LogState.Error, $"Wrong mouse cursor icon [{iconStr}]")); } } break; case SystemType.ErrorOff: { SystemInfo_ErrorOff subInfo = info.SubInfo.Cast <SystemInfo_ErrorOff>(); string linesStr = StringEscaper.Preprocess(s, subInfo.Lines); if (!NumberHelper.ParseInt32(linesStr, out int lines)) { return(LogInfo.LogErrorMessage(logs, $"[{linesStr}] is not a positive integer")); } if (lines <= 0) { return(LogInfo.LogErrorMessage(logs, $"[{linesStr}] is not a positive integer")); } if (s.ErrorOff == null) { // Enable s.ErrorOff // Write to s.ErrorOffWaitingRegister instead of s.ErrorOff, to prevent muting error of [System,ErrorOff] itself. ErrorOffState newState = new ErrorOffState { Section = cmd.Section, SectionDepth = s.CurDepth, StartLineIdx = cmd.LineIdx, LineCount = lines, }; if (s.ErrorOffDepthMinusOne) { newState.SectionDepth -= 1; } s.ErrorOffWaitingRegister = newState; s.ErrorOffDepthMinusOne = false; logs.Add(new LogInfo(LogState.Success, $"Error and warning logs will be muted for [{lines}] lines")); } else { // If s.ErrorOff is already enabled, do nothing. Ex) Nested ErrorOff logs.Add(new LogInfo(LogState.Ignore, "ErrorOff is already enabled")); } } break; case SystemType.GetEnv: { SystemInfo_GetEnv subInfo = info.SubInfo.Cast <SystemInfo_GetEnv>(); string envVarName = StringEscaper.Preprocess(s, subInfo.EnvVar); string envVarValue = Environment.GetEnvironmentVariable(envVarName); if (envVarValue == null) // Failure { logs.Add(new LogInfo(LogState.Ignore, $"Cannot get environment variable [%{envVarName}%]'s value")); envVarValue = string.Empty; } logs.Add(new LogInfo(LogState.Success, $"Environment variable [{envVarName}]'s value is [{envVarValue}]")); List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.DestVar, envVarValue); logs.AddRange(varLogs); } break; case SystemType.GetFreeDrive: { SystemInfo_GetFreeDrive subInfo = info.SubInfo.Cast <SystemInfo_GetFreeDrive>(); DriveInfo[] drives = DriveInfo.GetDrives(); const string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; char lastFreeLetter = letters.Except(drives.Select(d => d.Name[0])).LastOrDefault(); if (lastFreeLetter != '\0') // Success { logs.Add(new LogInfo(LogState.Success, $"Last free drive letter is [{lastFreeLetter}]")); List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.DestVar, lastFreeLetter.ToString()); logs.AddRange(varLogs); } else // No Free Drives { // TODO: Is it correct WB082 behavior? logs.Add(new LogInfo(LogState.Ignore, "No free drive letter")); List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.DestVar, string.Empty); logs.AddRange(varLogs); } } break; case SystemType.GetFreeSpace: { SystemInfo_GetFreeSpace subInfo = info.SubInfo.Cast <SystemInfo_GetFreeSpace>(); string path = StringEscaper.Preprocess(s, subInfo.Path); FileInfo f = new FileInfo(path); if (f.Directory == null) { return(LogInfo.LogErrorMessage(logs, $"Unable to get drive information of [{path}]")); } DriveInfo drive = new DriveInfo(f.Directory.Root.FullName); long freeSpaceMB = drive.TotalFreeSpace / (1024 * 1024); // B to MB List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.DestVar, freeSpaceMB.ToString()); logs.AddRange(varLogs); } break; case SystemType.IsAdmin: { SystemInfo_IsAdmin subInfo = info.SubInfo.Cast <SystemInfo_IsAdmin>(); bool isAdmin; using (WindowsIdentity identity = WindowsIdentity.GetCurrent()) { WindowsPrincipal principal = new WindowsPrincipal(identity); isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator); } if (isAdmin) { logs.Add(new LogInfo(LogState.Success, "PEBakery is running as Administrator")); } else { logs.Add(new LogInfo(LogState.Success, "PEBakery is not running as Administrator")); } List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.DestVar, isAdmin.ToString()); logs.AddRange(varLogs); } break; case SystemType.OnBuildExit: { SystemInfo_OnBuildExit subInfo = info.SubInfo.Cast <SystemInfo_OnBuildExit>(); s.OnBuildExit = subInfo.Cmd; logs.Add(new LogInfo(LogState.Success, "OnBuildExit callback registered")); } break; case SystemType.OnScriptExit: { SystemInfo_OnScriptExit subInfo = info.SubInfo.Cast <SystemInfo_OnScriptExit>(); s.OnScriptExit = subInfo.Cmd; logs.Add(new LogInfo(LogState.Success, "OnScriptExit callback registered")); } break; case SystemType.RefreshInterface: { Debug.Assert(info.SubInfo.GetType() == typeof(SystemInfo), "Invalid CodeInfo"); s.MainViewModel.StartRefreshScript().Wait(); logs.Add(new LogInfo(LogState.Success, $"Re-rendered script [{cmd.Section.Script.Title}]")); } break; case SystemType.RescanScripts: case SystemType.RefreshAllScripts: { Debug.Assert(info.SubInfo.GetType() == typeof(SystemInfo), "Invalid CodeInfo"); // Refresh Project s.MainViewModel.StartLoadingProjects(true, true).Wait(); logs.Add(new LogInfo(LogState.Success, $"Reload project [{cmd.Section.Script.Project.ProjectName}]")); } break; case SystemType.LoadNewScript: { SystemInfo_LoadNewScript subInfo = info.SubInfo.Cast <SystemInfo_LoadNewScript>(); string srcFilePath = StringEscaper.Preprocess(s, subInfo.SrcFilePath); string destTreeDir = StringEscaper.Preprocess(s, subInfo.DestTreeDir); SearchOption searchOption = SearchOption.AllDirectories; if (subInfo.NoRecFlag) { searchOption = SearchOption.TopDirectoryOnly; } Debug.Assert(srcFilePath != null, "Internal Logic Error at CommandSystem.LoadNewScript"); // Check wildcard string wildcard = Path.GetFileName(srcFilePath); bool containsWildcard = wildcard.IndexOfAny(new[] { '*', '?' }) != -1; string[] files; if (containsWildcard) { // With wildcard files = FileHelper.GetFilesEx(FileHelper.GetDirNameEx(srcFilePath), wildcard, searchOption); if (files.Length == 0) { return(LogInfo.LogErrorMessage(logs, $"Script [{srcFilePath}] does not exist")); } } else { // No wildcard if (!File.Exists(srcFilePath)) { return(LogInfo.LogErrorMessage(logs, $"Script [{srcFilePath}] does not exist")); } files = new string[] { srcFilePath }; } List <Script> newScripts = new List <Script>(files.Length); string srcDirPath = Path.GetDirectoryName(srcFilePath); Debug.Assert(srcDirPath != null, $"{nameof(srcDirPath)} is null (CommandSystem.LoadNewScript)"); (string realPath, string treePath)[] fileTuples = files
public async Task<ActionResult> RegMentoringTotalReport(MentoringTotalReportViewModel dataRequestViewModel, IEnumerable<HttpPostedFileBase> files) { ViewBag.LeftMenu = Global.MentoringReport; var mentorId = Session[Global.LoginID].ToString(); if (ModelState.IsValid) { var scMentoringTotalReport = Mapper.Map<ScMentoringTotalReport>(dataRequestViewModel); scMentoringTotalReport.MentorId = mentorId; scMentoringTotalReport.RegId = mentorId; scMentoringTotalReport.RegDt = DateTime.Now; scMentoringTotalReport.Status = "N"; //신규파일정보저장 및 파일업로드 if (files != null) { foreach (var file in files) { if (file != null) { var fileHelper = new FileHelper(); var savedFileName = fileHelper.GetUploadFileName(file); var subDirectoryPath = Path.Combine(FileType.Mentoring_Total.ToString(), DateTime.Now.Year.ToString(), DateTime.Now.Month.ToString()); var savedFilePath = Path.Combine(subDirectoryPath, savedFileName); var scFileInfo = new ScFileInfo { FileNm = Path.GetFileName(file.FileName), FilePath = savedFilePath, Status = "N", RegId = Session[Global.LoginID].ToString(), RegDt = DateTime.Now }; var scMentoringTrFileInfo = new ScMentoringTrFileInfo { ScFileInfo = scFileInfo }; scMentoringTrFileInfo.Classify = "A"; scMentoringTotalReport.ScMentoringTrFileInfoes.Add(scMentoringTrFileInfo); await fileHelper.UploadFile(file, subDirectoryPath, savedFileName); } } } //저장 int result = await _scMentoringTotalReportService.AddScMentoringTotalReportAsync(scMentoringTotalReport); if (result != -1) return RedirectToAction("MentoringTotalReportList", "MentoringReport"); else { ModelState.AddModelError("", "자료요청 등록 실패."); return View(dataRequestViewModel); } } ModelState.AddModelError("", "입력값 검증 실패."); return View(dataRequestViewModel); }
/// <summary> /// checkin文件 /// </summary> /// <param name="tgv"></param> /// <param name="fileType"></param> private void CheckInFile(TreeGridView tgv, DataType.FileType fileType) { int rowIndex = tgv.CurrentCell.RowIndex; if (rowIndex <= 0) { MessageBox.Show("请选择文件", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } DataGridViewRow row = tgv.Rows[rowIndex]; String Id = row.Cells["DFL_ID"].Value.ToString(); DOC_FILE_LIST docFileEntity = _docFileListService.GetDocFileEntityByDCID(Id); // HYPDM.Entities.PDM_PHYSICAL_FILE physicalfile = _physicalService.GetPhysicalFile(Id, ""); HYDocumentMS.IFileHelper file = new FileHelper(); Boolean bl = file.isHasAuth(DataType.AuthParmsType.CheckIn, LoginInfo.LoginID, row.Cells["DFL_ID"].Value.ToString()); if (bl == false) { MessageBox.Show("你没有权限检入此文件!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (docFileEntity == null) return; if (docFileEntity.CHECKOUTFLG == "N") { MessageBox.Show("文件名【" + docFileEntity.DFL_FILE_NAME + "】" + "\n" + "不为检出状态,不能进行检入操作!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } else { CheckInForm form = new CheckInForm(); form.DocFileEntity = docFileEntity; if (form.ShowDialog() == DialogResult.OK) { docFileEntity.CHECKINFLG = "Y"; docFileEntity.CHECKINDATE = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); docFileEntity.CHECKOUTFLG = "N"; docFileEntity.DFL_VER_LATEST = "V" + DateTime.Now.ToString("yyyyMMddHHmmss"); docFileEntity.LASTUPDATEDATE = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); docFileEntity.LASTUPDATEUSER = LoginInfo.LoginID; docFileEntity.Save(); VersionSave("1", docFileEntity); } } }
/// <summary> /// 删除文件 /// </summary> private void delFile(TreeGridView tgv,DataType.FileType fileType) { int rowIndex = tgv.CurrentCell.RowIndex; if (rowIndex <= 0) { MessageBox.Show("请选择文件", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } HYDocumentMS.IFileHelper file = new FileHelper(); Boolean bl = file.isHasAuth(DataType.AuthParmsType.Delete, LoginInfo.LoginID, tgv.CurrentRow.Cells["DFL_ID"].Value.ToString()); if (bl == false) { MessageBox.Show("你没有权限删除此文件!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (MessageBox.Show("所选择的文件将被删除,是否确定?", "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { DataGridViewRow row = tgv.Rows[rowIndex]; string dflID = row.Cells["DFL_ID"].Value.ToString(); //var file = _physicalService.GetPhysicalFile(Id, ""); // IDocFileListService serv = new DocFileListService(); if (_docFileListService.delDocFileByDFLID(dflID)) { MessageBox.Show("删除成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1); } else { MessageBox.Show("删除失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1); } this.BindTreeData(); //serv. //file.Delete(); // MessageBox.Show("所选择的文件已被删除!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
public override void ReadFromStream(AwesomeReader ar, ISerializable data) { var dir = data as MiloObjectDir; int version = ReadMagic(ar, data); string dirType = null, dirName = null; dir.Extras.Clear(); // Clears for good measure if (version >= 24) { // Parses directory type/name dirType = ar.ReadString(); dirName = FileHelper.SanitizePath(ar.ReadString()); //ar.BaseStream.Position += 8; // Skips string count + total length dir.Extras.Add("Num1", ar.ReadInt32()); dir.Extras.Add("Num2", ar.ReadInt32()); } int entryCount = ar.ReadInt32(); var entries = Enumerable.Range(0, entryCount).Select(x => new { Type = ar.ReadString(), Name = FileHelper.SanitizePath(ar.ReadString()) }).ToArray(); if (version == 10) { // Parses external resource paths? entryCount = ar.ReadInt32(); // Note: Entry can be empty var external = Enumerable.Range(0, entryCount) .Select(x => ar.ReadString()) .ToList(); dir.Extras.Add("ExternalResources", external); } else if (version == 25 && dirType == "ObjectDir") { // Hack for project 9 var dirEntry = new MiloObjectDirEntry() { Name = dirName }; dirEntry.Version = ar.ReadInt32(); dirEntry.SubVersion = ar.ReadInt32(); dirEntry.ProjectName = ar.ReadString(); // Skip matrices + constants var matCount = ar.ReadInt32(); // Usually 7 ar.BaseStream.Position += (matCount * 48) + 9; // Read imported milos var importedMiloCount = ar.ReadInt32(); dirEntry.ImportedMiloPaths = Enumerable.Range(0, importedMiloCount) .Select(x => ar.ReadString()) .ToArray(); // Boolean, true when sub directory? ar.ReadBoolean(); // Sub directory names seem to be in reverse order of serialization... var subDirCount = ar.ReadInt32(); var subDirNames = Enumerable.Range(0, subDirCount) .Select(x => ar.ReadString()) .ToArray(); // Read subdirectories foreach (var _ in subDirNames.Reverse()) { var subDir = new MiloObjectDir(); ReadFromStream(ar, subDir); dirEntry.SubDirectories.Add(subDir); } dir.Extras.Add("DirectoryEntry", dirEntry); ar.BaseStream.Position += 17; // 0'd data + ADDE } else if (version == 25 && (dirType == "WorldDir")) { // Read past unknown stuff, big hack int unk1 = ar.ReadInt32(); int unk2 = ar.ReadInt32(); float unk3 = ar.ReadSingle(); string unk4 = ar.ReadString(); int unk5 = ar.ReadInt32(); int unk6 = ar.ReadInt32(); // Hack for project 9 var dirEntry = new MiloObjectDirEntry() { Name = dirName }; dirEntry.Version = ar.ReadInt32(); dirEntry.SubVersion = ar.ReadInt32(); dirEntry.ProjectName = ar.ReadString(); // Skip matrices + constants var matCount = ar.ReadInt32(); // Usually 7 ar.BaseStream.Position += (matCount * 48) + 9; // Read imported milos var importedMiloCount = ar.ReadInt32(); dirEntry.ImportedMiloPaths = Enumerable.Range(0, importedMiloCount) .Select(x => ar.ReadString()) .ToArray(); // Boolean, true when sub directory? ar.ReadBoolean(); // Sub directory names seem to be in reverse order of serialization... var subDirCount = ar.ReadInt32(); var subDirNames = Enumerable.Range(0, subDirCount) .Select(x => ar.ReadString()) .ToArray(); // Read subdirectories foreach (var _ in subDirNames.Reverse()) { var subDir = new MiloObjectDir(); ReadFromStream(ar, subDir); dirEntry.SubDirectories.Add(subDir); } dir.Extras.Add("DirectoryEntry", dirEntry); ar.BaseStream.Position += 17; // 0'd data + ADDE } else if (version == 25 && (dirType == "RndDir" || dirType == "SynthDir")) { // Read past unknown stuff, big hack int unk1 = ar.ReadInt32(); // Hack for project 9 var dirEntry = new MiloObjectDirEntry() { Name = dirName }; dirEntry.Version = ar.ReadInt32(); dirEntry.SubVersion = ar.ReadInt32(); dirEntry.ProjectName = ar.ReadString(); // Skip matrices + constants var matCount = ar.ReadInt32(); // Usually 7 ar.BaseStream.Position += (matCount * 48) + 9; // Read imported milos var importedMiloCount = ar.ReadInt32(); dirEntry.ImportedMiloPaths = Enumerable.Range(0, importedMiloCount) .Select(x => ar.ReadString()) .ToArray(); // Boolean, true when sub directory? ar.ReadBoolean(); // Sub directory names seem to be in reverse order of serialization... var subDirCount = ar.ReadInt32(); var subDirNames = Enumerable.Range(0, subDirCount) .Select(x => ar.ReadString()) .ToArray(); // Read subdirectories foreach (var _ in subDirNames.Reverse()) { var subDir = new MiloObjectDir(); ReadFromStream(ar, subDir); dirEntry.SubDirectories.Add(subDir); } dir.Extras.Add("DirectoryEntry", dirEntry); ar.BaseStream.Position += 17; // 0'd data + ADDE } else if (version == 25 && (dirType == "PanelDir" || dirType == "VocalTrackDir" || dirType == "UILabelDir" || dirType == "UILabelDir" || dirType == "UIListDir" || dirType == "PitchArrowDir" || dirType == "Character")) { // Read past unknown stuff, big hack int unk1 = ar.ReadInt32(); int unk2 = ar.ReadInt32(); // Hack for project 9 var dirEntry = new MiloObjectDirEntry() { Name = dirName }; dirEntry.Version = ar.ReadInt32(); dirEntry.SubVersion = ar.ReadInt32(); dirEntry.ProjectName = ar.ReadString(); // Skip matrices + constants var matCount = ar.ReadInt32(); // Usually 7 ar.BaseStream.Position += (matCount * 48) + 9; // Read imported milos var importedMiloCount = ar.ReadInt32(); dirEntry.ImportedMiloPaths = Enumerable.Range(0, importedMiloCount) .Select(x => ar.ReadString()) .ToArray(); // Boolean, true when sub directory? ar.ReadBoolean(); // Sub directory names seem to be in reverse order of serialization... var subDirCount = ar.ReadInt32(); var subDirNames = Enumerable.Range(0, subDirCount) .Select(x => ar.ReadString()) .ToArray(); // Read subdirectories foreach (var _ in subDirNames.Reverse()) { var subDir = new MiloObjectDir(); ReadFromStream(ar, subDir); dirEntry.SubDirectories.Add(subDir); } dir.Extras.Add("DirectoryEntry", dirEntry); ar.BaseStream.Position += 17; // 0'd data + ADDE } else if (version == 25 && (dirType == "BackgroundDir" || dirType == "WorldInstance")) { // Read past unknown stuff, big hack int unk1 = ar.ReadInt32(); int unk2 = ar.ReadInt32(); int unk3 = ar.ReadInt32(); // Hack for project 9 var dirEntry = new MiloObjectDirEntry() { Name = dirName }; dirEntry.Version = ar.ReadInt32(); dirEntry.SubVersion = ar.ReadInt32(); dirEntry.ProjectName = ar.ReadString(); // Skip matrices + constants var matCount = ar.ReadInt32(); // Usually 7 ar.BaseStream.Position += (matCount * 48) + 9; // Read imported milos var importedMiloCount = ar.ReadInt32(); dirEntry.ImportedMiloPaths = Enumerable.Range(0, importedMiloCount) .Select(x => ar.ReadString()) .ToArray(); // Boolean, true when sub directory? ar.ReadBoolean(); // Sub directory names seem to be in reverse order of serialization... var subDirCount = ar.ReadInt32(); var subDirNames = Enumerable.Range(0, subDirCount) .Select(x => ar.ReadString()) .ToArray(); // Read subdirectories foreach (var _ in subDirNames.Reverse()) { var subDir = new MiloObjectDir(); ReadFromStream(ar, subDir); dirEntry.SubDirectories.Add(subDir); } dir.Extras.Add("DirectoryEntry", dirEntry); ar.BaseStream.Position += 17; // 0'd data + ADDE } else if (version == 25 && (dirType == "TrackPanelDir" || dirType == "H2HTrackPanelDir")) { // Read past unknown stuff, big hack int unk1 = ar.ReadInt32(); int unk2 = ar.ReadInt32(); int unk3 = ar.ReadInt32(); int unk4 = ar.ReadInt32(); // Hack for project 9 var dirEntry = new MiloObjectDirEntry() { Name = dirName }; dirEntry.Version = ar.ReadInt32(); dirEntry.SubVersion = ar.ReadInt32(); dirEntry.ProjectName = ar.ReadString(); // Skip matrices + constants var matCount = ar.ReadInt32(); // Usually 7 ar.BaseStream.Position += (matCount * 48) + 9; // Read imported milos var importedMiloCount = ar.ReadInt32(); dirEntry.ImportedMiloPaths = Enumerable.Range(0, importedMiloCount) .Select(x => ar.ReadString()) .ToArray(); // Boolean, true when sub directory? ar.ReadBoolean(); // Sub directory names seem to be in reverse order of serialization... var subDirCount = ar.ReadInt32(); var subDirNames = Enumerable.Range(0, subDirCount) .Select(x => ar.ReadString()) .ToArray(); // Read subdirectories foreach (var _ in subDirNames.Reverse()) { var subDir = new MiloObjectDir(); ReadFromStream(ar, subDir); dirEntry.SubDirectories.Add(subDir); } dir.Extras.Add("DirectoryEntry", dirEntry); ar.BaseStream.Position += 17; // 0'd data + ADDE } else if (version >= 24) { // GH2 and above // Reads data as a byte array var entrySize = GuessEntrySize(ar); var entryBytes = new MiloObjectBytes(dirType) { Name = dirName }; entryBytes.Data = ar.ReadBytes((int)entrySize); dir.Extras.Add("DirectoryEntry", entryBytes); ar.BaseStream.Position += 4; } foreach (var entry in entries) { var entryOffset = ar.BaseStream.Position; // TODO: De-serialize entries //try //{ // var miloEntry = ReadFromStream(ar.BaseStream, entry.Type); // miloEntry.Name = entry.Name; // dir.Entries.Add(miloEntry); // ar.BaseStream.Position += 4; // Skips padding // continue; //} //catch (Exception ex) //{ // // Catch exception and log? // ar.Basestream.Position = entryOffset; // Return to start //} // Reads data as a byte array var entrySize = GuessEntrySize(ar); var entryBytes = new MiloObjectBytes(entry.Type) { Name = entry.Name }; entryBytes.Data = ar.ReadBytes((int)entrySize); dir.Entries.Add(entryBytes); ar.BaseStream.Position += 4; } }
public CResult <bool> ImportMaintainItemFromExcel(HttpPostedFileBase file, string projectID, string operatorUserID) { LogHelper.Info(MethodBase.GetCurrentMethod().ToString()); if (string.IsNullOrEmpty(projectID) || string.IsNullOrEmpty(operatorUserID)) { return(new CResult <bool>(false, ErrorCode.ParameterError)); } var fileName = string.Format("{0}{1}", Guid.NewGuid().ToString(), Path.GetExtension(file.FileName)); var filePath = FileHelper.SaveFile(file, SystemInfo.TempFileFolder, fileName); if (string.IsNullOrEmpty(filePath)) { return(new CResult <bool>(false, ErrorCode.SystemError)); } var dataTable = ExcelHelper.ExcelToDataTable(filePath, 0); if (dataTable.Rows.Count == 0) { return(new CResult <bool>(false, ErrorCode.FileContainNoData)); } var WebMaintainItemList = new List <WebMaintainItem>(); foreach (DataRow row in dataTable.Rows) { int i = 0; var WebMaintainItem = new WebMaintainItem(); WebMaintainItem.Name = row[i++].ToString(); WebMaintainItem.Note = row[i++].ToString(); WebMaintainItemList.Add(WebMaintainItem); } var nameList = WebMaintainItemList.Select(t => t.Name).Distinct().ToList(); if (nameList.Count < WebMaintainItemList.Count) { return(new CResult <bool>(false, ErrorCode.MaintainItemExist)); } using (var context = new DeviceMgmtEntities()) { if (context.Project.Any(t => t.IsValid && t.ID == projectID) == false) { return(new CResult <bool>(false, ErrorCode.ProjectNotExist)); } if (context.User.Any(t => t.IsValid && t.UserID == operatorUserID) == false) { return(new CResult <bool>(false, ErrorCode.UserNotExist)); } if (context.MaintainItem.Any(t => t.ProjectID == projectID && t.IsValid && nameList.Contains(t.Name))) { return(new CResult <bool>(false, ErrorCode.MaintainItemExist)); } var currentTime = DateTime.Now; foreach (var WebMaintainItem in WebMaintainItemList) { var item = new MaintainItem() { CreateDate = currentTime, CreateUserID = operatorUserID, ID = Guid.NewGuid().ToString(), IsValid = true, Name = WebMaintainItem.Name, Note = WebMaintainItem.Note, ProjectID = projectID, }; context.MaintainItem.Add(item); } LogHelper.Info("importList", WebMaintainItemList); return(context.Save()); } }
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; //context.Response.Write("Hello World"); string method = context.Request.Params["method"]; if ("list".Equals(method)) { string ajax = context.Request.Params["ajax"]; BrandProjectDAO dao = new BrandProjectDAO(); BrandProject bp = new BrandProject(); bp.bpType = context.Request.Params["bpType"]; DataSet ds = dao.select(bp); string result = ""; if (String.IsNullOrEmpty(ajax)) { result = "_list = " + JsonCommon.ds2json(ds); } else { result = JsonCommon.ds2json(ds); } context.Response.Write(result); } else if ("detail".Equals(method)) { BrandProjectDAO dao = new BrandProjectDAO(); BrandProject bp = new BrandProject(); bp.bpId = context.Request.Params["bpId"]; DataSet ds = dao.select(bp); string json = JsonCommon.ds2json(ds); PictureDAO picDao = new PictureDAO(); Picture pic = new Picture(); pic.picTableName = "BrandProject"; pic.picTableId = bp.bpId; DataSet picDs = picDao.select(pic); string picJson = JsonCommon.ds2json(picDs); json = String.Format("[{0},{1}]", json, picJson); context.Response.Write(json); } else if ("save".Equals(method)) { string bpContent = HttpUtility.UrlDecode((context.Request.Params["bpContent"]).Replace("@", "%")); string bpType = context.Request.Params["bpType"]; string bpId = context.Request.Params["bpId"]; BrandProjectDAO dao = new BrandProjectDAO(); BrandProject bp = new BrandProject(); bp.bpContent = bpContent; bp.bpType = bpType; if (!String.IsNullOrEmpty(bpId)) { bp.bpId = bpId; dao.update(bp); } else { bp.bpId = Guid.NewGuid().ToString(); bpId = bp.bpId; dao.insert(bp); } string pics = context.Request.Params["pics"]; string disc = context.Request.Params["disc"]; PictureDAO picDao = new PictureDAO(); //删除要删除的图片 string delPics = context.Request.Params["delPic"]; if (!String.IsNullOrEmpty(delPics)) { string[] arrDelPics = delPics.Split(','); for (int i = 0; i < arrDelPics.Length; i++) { Picture p = new Picture(); p.picId = arrDelPics[i]; picDao.delete(p); } } if (!String.IsNullOrEmpty(pics)) { string[] arrPics = pics.Split(','); string[] arrDisc = disc.Split(','); for (int i = 0; i < arrPics.Length; i++) { string fileName = arrPics[i].Substring(arrPics[i].LastIndexOf("/") + 1); string fromPath = context.Server.MapPath(arrPics[i]); string toPath = context.Server.MapPath(FileHelper.Default_Pic_Forder + fileName); FileHelper.MoveTo(fromPath, toPath); Picture pic = new Picture(); pic.picTableId = bpId; pic.picTableName = "BrandProject"; pic.picDescrip = arrDisc[i]; pic.picExtension = fileName.Substring(fileName.LastIndexOf(".") + 1); pic.picName = fileName; pic.picPath = FileHelper.Default_Pic_Forder + fileName; picDao.insert(pic); } } } else if ("delete".Equals(method)) { string bpId = context.Request.Params["bpId"]; BrandProjectDAO dao = new BrandProjectDAO(); BrandProject bp = new BrandProject(); bp.bpId = bpId; dao.delete(bp); } }
public static void Write ( Color[] pixels, int width, int height, int bitDepth, bool alpha, bool greyscale, string filePath ) { var info = new ImageInfo( width, height, bitDepth, alpha, greyscale, false//not implemented here yet//bitDepth==4 ); // open image for writing: PngWriter writer = FileHelper.CreatePngWriter(filePath, info, true); // add some optional metadata (chunks) var meta = writer.GetMetadata(); int numRows = info.Rows; int numCols = info.Cols; ImageLine imageline = new ImageLine(info); for (int row = 0; row < numRows; row++) { //fill line: if (greyscale == false) { if (alpha) { for (int col = 0; col < numCols; col++) { RGBA rgba = ToRGBA(pixels[IndexPngToTexture(row, col, numRows, numCols)], bitDepth); ImageLineHelper.SetPixel(imageline, col, rgba.r, rgba.g, rgba.b, rgba.a); } } else { for (int col = 0; col < numCols; col++) { RGB rgb = ToRGB(pixels[IndexPngToTexture(row, col, numRows, numCols)], bitDepth); ImageLineHelper.SetPixel(imageline, col, rgb.r, rgb.g, rgb.b); } } } else { if (alpha == false) { for (int col = 0; col < numCols; col++) { int r = ToInt(pixels[IndexPngToTexture(row, col, numRows, numCols)].r, bitDepth); ImageLineHelper.SetPixel(imageline, col, r); } } else { for (int col = 0; col < numCols; col++) { int a = ToInt(pixels[IndexPngToTexture(row, col, numRows, numCols)].a, bitDepth); ImageLineHelper.SetPixel(imageline, col, a); } } } //write line: writer.WriteRow(imageline, row); } writer.End(); }
/// <summary> /// Saves the maze with a specified path as PNG /// </summary> /// <param name="fileName">The filename of the file</param> /// <param name="pathPosjes">The path (can be generated by calling PathFinderDepthFirst.GoFind)</param> /// <param name="lineSavingProgress">An action that will be called to obtain the status of the saving.</param> public void SaveMazeAsImageDeluxe(String fileName, List <MazePointPos> pathPosjes, Action <int, int> lineSavingProgress) { //pathPosjes = pathPosjes.OrderBy(t => t.Y).ThenBy(t => t.X).ToArray(); pathPosjes.Sort((first, second) => { if (first.Y == second.Y) { return(first.X - second.X); } return(first.Y - second.Y); }); ImageInfo imi = new ImageInfo(this.Width - 1, this.Height - 1, 8, false); // 8 bits per channel, no alpha // open image for writing PngWriter png = FileHelper.CreatePngWriter(fileName, imi, true); // add some optional metadata (chunks) png.GetMetadata().SetDpi(100.0); png.GetMetadata().SetTimeNow(0); // 0 seconds fron now = now png.CompLevel = 4; //png.GetMetadata().SetText(PngChunkTextVar.KEY_Title, "Just a text image"); //PngChunk chunk = png.GetMetadata().SetText("my key", "my text .. bla bla"); //chunk.Priority = true; // this chunk will be written as soon as possible int curpos = 0; for (int y = 0; y < this.Height - 1; y++) { ImageLine iline = new ImageLine(imi); for (int x = 0; x < this.Width - 1; x++) { int r = 0; int g = 0; int b = 0; MazePointPos curPathPos; if (curpos < pathPosjes.Count) { curPathPos = pathPosjes[curpos]; if (curPathPos.X == x && curPathPos.Y == y) { r = curPathPos.RelativePos; g = 255 - curPathPos.RelativePos; b = 0; curpos++; } else if (this.innerMap[x, y]) { r = 255; g = 255; b = 255; } } else if (this.innerMap[x, y]) { r = 255; g = 255; b = 255; } ImageLineHelper.SetPixel(iline, x, r, g, b); } png.WriteRow(iline, y); lineSavingProgress(y, this.Height - 2); } png.End(); }
public async Task ResetCache() { await FileHelper.DeleteFileAsync(CACHEFILE); }
private void tsbExport_Click(object sender, EventArgs e) { string filename = "数据"; if (!String.IsNullOrEmpty(this.Text)) { filename = this.Text; } try { FileHelper.InitSaveExcelDialog(sfdExport, filename); if (sfdExport.ShowDialog() == DialogResult.OK) { string file = sfdExport.FileName; sfdExport.Dispose(); //FileHelper.ExportToExcel(dgvList, file); ExcelHelper excel = new ExcelHelper(); excel.NewExcelFile(); excel.SaveFileName = file; excel.SetWorksheetName(1, OnExportExcel()); int i = 0; int j = 0; int k = 0; for (i = 0; i < dgvList.Columns.Count; i++) { if (!dgvList.Columns[i].Visible) { continue; } k++; excel.SetCellValue(1, k, dgvList.Columns[i].HeaderText); } for (i = 0; i < dgvList.Rows.Count; i++) { k = 0; for (j = 0; j < dgvList.Columns.Count; j++) { if (!dgvList.Columns[j].Visible) { continue; } k++; excel.SetCellValue(i + 2, k, dgvList.Rows[i].Cells[j].Value != null ? dgvList.Rows[i].Cells[j].Value.ToString() : ""); } } excel.SaveExcel(); excel.CloseExcelApplication(); MessageBox.Show("导出成功!", PublicConsts.PC_Tip); } } catch (Exception ex) { MessageBox.Show("导出错误:" + ex.Message, PublicConsts.PC_Tip); return; } }
public void Invoke(Http2Context http2Context) { var path = http2Context.Request.Path; if (path == "/") { path = "/index.html"; } switch (http2Context.Request.Method) { case "GET": var filePath = PathExtentions.MapPath(path); if (FileHelper.Exists(filePath)) { var responseHeaders1 = new HeaderField[] { new HeaderField { Name = ":status", Value = "200" }, new HeaderField { Name = "date", Value = DateTime.Now.ToGMTString() }, new HeaderField { Name = "server", Value = "SAEA.Http2Server" }, new HeaderField { Name = "content-type", Value = "text/html" }, }; http2Context.Response.SetHeaders(responseHeaders1); http2Context.Response.Write(FileHelper.Read(filePath)); } else { var responseHeaders2 = new HeaderField[] { new HeaderField { Name = ":status", Value = "404" }, new HeaderField { Name = "date", Value = DateTime.Now.ToGMTString() }, new HeaderField { Name = "server", Value = "SAEA.Http2Server" }, new HeaderField { Name = "content-type", Value = "text/html" }, }; http2Context.Response.SetHeaders(responseHeaders2); http2Context.Response.Write("找不到内容!"); } break; case "POST": var responseHeaders3 = new HeaderField[] { new HeaderField { Name = ":status", Value = "204" }, new HeaderField { Name = "date", Value = DateTime.Now.ToGMTString() }, new HeaderField { Name = "server", Value = "SAEA.Http2Server" }, new HeaderField { Name = "content-type", Value = "text/html" }, }; http2Context.Response.SetHeaders(responseHeaders3); http2Context.Response.Write(http2Context.Request.Body); break; default: break; } http2Context.Response.End(); }
/// <summary> /// Actual implementation of loading a dictionary /// </summary> /// <param name="lexiconFilePath"></param> /// <param name="dictionaryLoadedCallback"></param> /// <param name="callbackParam"></param> /// <returns> /// A tuple of cultureinfo detected from <paramref name="lexiconFilePath"/> and /// a temp file path which holds a copy of <paramref name="lexiconFilePath"/> /// /// If no culture is specified in the first line of <paramref name="lexiconFilePath"/> /// in the format #LID nnnn (where nnnn = decimal LCID of the culture), then invariant /// culture is returned. /// </returns> /// <remarks> /// At the end of this method, we guarantee that <paramref name="lexiconFilePath"/> /// can be reclaimed (i.e., potentially deleted) by the caller. /// </remarks> private Tuple <string, string> LoadDictionaryImpl(string lexiconFilePath) { if (_isDisposed) { return(new Tuple <string, string>(null, null)); } if (!File.Exists(lexiconFilePath)) { throw new ArgumentException(SR.Get(SRID.CustomDictionaryFailedToLoadDictionaryUri, lexiconFilePath)); } bool fileCopied = false; string lexiconPrivateCopyPath = null; try { CultureInfo culture = null; // Read the first line of the file and detect culture, if specified using (FileStream stream = new FileStream(lexiconFilePath, FileMode.Open, FileAccess.Read)) { string line = null; using (StreamReader reader = new StreamReader(stream)) { line = reader.ReadLine(); culture = WinRTSpellerInterop.TryParseLexiconCulture(line); } } string ietfLanguageTag = culture.IetfLanguageTag; // Make a temp file and copy the original file over. // Ensure that the copy has Unicode (UTF16-LE) encoding using (FileStream lexiconPrivateCopyStream = FileHelper.CreateAndOpenTemporaryFile(out lexiconPrivateCopyPath, extension: "dic")) { WinRTSpellerInterop.CopyToUnicodeFile(lexiconFilePath, lexiconPrivateCopyStream); fileCopied = true; } // Add the temp file (with .dic extension) just created to a cache, // then pass it along to IUserDictionariesRegistrar if (!_customDictionaryFiles.ContainsKey(ietfLanguageTag)) { _customDictionaryFiles[ietfLanguageTag] = new List <string>(); } _customDictionaryFiles[ietfLanguageTag].Add(lexiconPrivateCopyPath); using (new SpellerCOMActionTraceLogger(this, SpellerCOMActionTraceLogger.Actions.RegisterUserDictionary)) { SpellCheckerFactory.RegisterUserDictionary(lexiconPrivateCopyPath, ietfLanguageTag); } return(new Tuple <string, string>(ietfLanguageTag, lexiconPrivateCopyPath)); } catch (Exception e) when((e is ArgumentException) || !fileCopied) { // IUserDictionariesRegistrar.RegisterUserDictionary can // throw ArgumentException on failure. Cleanup the temp file if // we successfully created one. if (lexiconPrivateCopyPath != null) { FileHelper.DeleteTemporaryFile(lexiconPrivateCopyPath); } throw new ArgumentException(SR.Get(SRID.CustomDictionaryFailedToLoadDictionaryUri, lexiconFilePath), e); } }
private static async Task DeleteNpmrcFileAsync(string directoryName) { FileHelper.DeleteIfExists(Path.Combine(directoryName, ".npmrc")); await Task.CompletedTask; }
public FaceRecognitionTrainingStatus AddImageToTrainingSet(Bitmap faceImage, SimplePerson personOnImage) { using (var originalImage = new Image<Bgr, byte>(faceImage)) { try { var faces = _faceDetectionAlgorithm.FindFaces(faceImage); if (faces.Count == 1) { var face = faces.First(); var tag = new PictureTag { X = face.Bounds.X, Y = face.Bounds.Y, Height = face.Bounds.Height, Width = face.Bounds.Width, }; var existingPerson = _unitOfWork.Repository<Person>().Query(q => q.FirstName == personOnImage.FirstName && q.LastName == personOnImage.LastName).Select().FirstOrDefault(); if (existingPerson != null) { tag.PersonOnImageTag = existingPerson; } else { tag.PersonOnImageTag = new Person { FirstName = personOnImage.FirstName, LastName = personOnImage.LastName }; } if (!Directory.Exists(_basePicturesPath)) { Directory.CreateDirectory(_basePicturesPath); } var thumbnailGrayscaleIplImage = CropAndNormalizeFace(originalImage, face); string originalImageGuid = Guid.NewGuid().ToString(); string thumbnailGrayscaleGuid = Guid.NewGuid().ToString(); string imageExtension = FileHelper.ImageExtensionFromImageFormat(originalImage.Bitmap.RawFormat); string localOrignalImagePath = _basePicturesPath +"\\Files\\Faces\\"+ originalImageGuid + imageExtension; string localThumbnailGrayscaleImagePath = _basePicturesPath + "\\Files\\Faces\\" + thumbnailGrayscaleGuid + imageExtension; originalImage.Save(localOrignalImagePath); thumbnailGrayscaleIplImage.Save(localThumbnailGrayscaleImagePath); //FileHelper.Save(originalImage, orignalImagePath, 90); //FileHelper.Save(thumbnailGrayscaleIplImage, thumbnailGrayscaleImagePath, 90); var image = new FaceDetection.Library.Models.Image { Pictures = new List<Picture>() { new Picture { PicturePath = "/Files/Faces/"+originalImageGuid+imageExtension, NumberOfChannels = originalImage.NumberOfChannels, Height = faceImage.Height, Width = faceImage.Width, Type = PictureType.Original, Tags = new List<PictureTag> { tag } }, new Picture { PicturePath = "/Files/Faces/"+thumbnailGrayscaleGuid+imageExtension, NumberOfChannels = thumbnailGrayscaleIplImage.NumberOfChannels, Height = _faceSize.Height, Width = _faceSize.Width, Type = PictureType.GrayscaleThumbnail, Tags = new List<PictureTag> { tag } } } }; _unitOfWork.BeginTransaction(); try { _unitOfWork.Repository<FaceDetection.Library.Models.Image>().Insert(image); _unitOfWork.Commit(); return FaceRecognitionTrainingStatus.TrainingSuccessful; } catch (Exception e) { _unitOfWork.Rollback(); throw e; } } else if (faces.Count == 0) { return FaceRecognitionTrainingStatus.NoFacesFound; } else { return FaceRecognitionTrainingStatus.FoundMoreThenOneFace; } } catch (Exception e) { throw e; } } return FaceRecognitionTrainingStatus.TrainingFailure; }
public async Task<ActionResult> ModifyReceive(DataRequstViewModels dataRequestViewModel, string expertType, IEnumerable<HttpPostedFileBase> files) { ViewBag.LeftMenu = Global.ExpertService; var scReqDoc = await _scReqDocService.GetReqDoc(dataRequestViewModel.ReqDocSn); scReqDoc.ResContents = dataRequestViewModel.ResContents; scReqDoc.ChkYn = "Y"; scReqDoc.ResDt = DateTime.Now; //신규파일정보저장 및 파일업로드 foreach (var file in files) { if (file != null) { var fileHelper = new FileHelper(); var savedFileName = fileHelper.GetUploadFileName(file); var subDirectoryPath = Path.Combine(FileType.Document.ToString(), DateTime.Now.Year.ToString(), DateTime.Now.Month.ToString()); var savedFilePath = Path.Combine(subDirectoryPath, savedFileName); var scFileInfo = new ScFileInfo { FileNm = Path.GetFileName(file.FileName), FilePath = savedFilePath, Status = "N", RegId = Session[Global.LoginID].ToString(), RegDt = DateTime.Now }; var scReqDocFile = new ScReqDocFile { ScFileInfo = scFileInfo }; scReqDocFile.RegType = "R"; scReqDocFile.ReqDocSn = dataRequestViewModel.ReqDocSn; scReqDoc.ScReqDocFiles.Add(scReqDocFile); await fileHelper.UploadFile(file, subDirectoryPath, savedFileName); } } int result = await _scReqDocService.SaveDbContextAsync(); if (result != -1) return RedirectToAction("ReceiveDetail", "ExpertService", new { reqDocSn = dataRequestViewModel.ReqDocSn, expertType = expertType }); else { ModelState.AddModelError("", "답변 등록 실패."); return View(dataRequestViewModel); } }
public ActionResult New() { if (Request.Files.Count > 0) { try { var file = Request.Files[0]; if (file == null || file.ContentLength < 500) { return(Content(string.Empty)); } String fileName = file.FileName; string mimeType = Path.GetExtension(fileName); string fileId = FileHelper.generateID(); var newFileName = string.Format("img_{0}{1}", fileId, mimeType); string dirRoot = "~/img/"; System.IO.Directory.CreateDirectory(Server.MapPath(dirRoot)); var dirs = fileName.Split(new char[1] { '/' }); string path = ""; //try //{ // await UploadImageToS3(dirs.FirstOrDefault(), newFileName, file.InputStream); //} //catch (Exception ex) //{ // _log.ErrorFormat("Upload to S3 error: {0}", ex); // _log.ErrorFormat("Folder: {0} , FileName: {2}", dirs.FirstOrDefault(), newFileName); //} foreach (var dir in dirs) { if (dir.Contains(mimeType) == false) { dirRoot = string.Join("/", dirRoot, dir, ""); System.IO.Directory.CreateDirectory(Server.MapPath(dirRoot)); } else { path = Path.Combine(Server.MapPath(dirRoot), newFileName); } } if (mimeType == ".png" || mimeType == ".jpg" || mimeType == ".bmp") { System.Drawing.Image image = System.Drawing.Image.FromStream(file.InputStream); if (image.Width > 1920 || image.Height > 1200) { //_log.Info(image.Width); //_log.Info(image.Height); var newImg = ImageHelper.Resize(image, 1920, 1200, true); newImg.Save(path); } else { file.SaveAs(path); } } else { file.SaveAs(path); } //try //{ // var pathname = Path.Combine(dirRoot.Replace("~/", ""), newFileName); // _log.Info(pathname); // UploadToGooleCloud(pathname, mimeType, file.InputStream); //} //catch (Exception ex) //{ // _log.ErrorFormat("Upload to google cloud error: {0}", ex); //} string fullfn = Path.Combine(dirRoot.Replace("~/img/", ""), newFileName); //"/" + code + "/" + newFileName; return(Content(fullfn)); } catch (Exception ex) { _log.Error(ex); return(Content(string.Empty)); } } return(Content(string.Empty)); }
/// <summary> /// 给.NET Core使用的HttpPost请求公共设置方法 /// </summary> /// <param name="url"></param> /// <param name="hc"></param> /// <param name="cookieContainer"></param> /// <param name="postStream"></param> /// <param name="fileDictionary"></param> /// <param name="refererUrl"></param> /// <param name="encoding"></param> /// <param name="cer"></param> /// <param name="useAjax"></param> /// <param name="timeOut"></param> /// <param name="checkValidationResult"></param> /// <returns></returns> public static HttpClient HttpPost_Common_NetCore(string url, out HttpContent hc, CookieContainer cookieContainer = null, Stream postStream = null, Dictionary <string, string> fileDictionary = null, string refererUrl = null, Encoding encoding = null, X509Certificate2 cer = null, bool useAjax = false, int timeOut = Config.TIME_OUT, bool checkValidationResult = false) { var handler = new HttpClientHandler() { UseProxy = _webproxy != null, Proxy = _webproxy, UseCookies = true, CookieContainer = cookieContainer, }; if (checkValidationResult) { handler.ServerCertificateCustomValidationCallback = new Func <HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool>(CheckValidationResult); } if (cer != null) { handler.ClientCertificates.Add(cer); } HttpClient client = new HttpClient(handler); HttpClientHeader(client, refererUrl, useAjax, timeOut); #region 处理Form表单文件上传 var formUploadFile = fileDictionary != null && fileDictionary.Count > 0;//是否用Form上传文件 if (formUploadFile) { //通过表单上传文件 string boundary = "----" + DateTime.Now.Ticks.ToString("x"); var multipartFormDataContent = new MultipartFormDataContent(boundary); hc = multipartFormDataContent; foreach (var file in fileDictionary) { try { var fileName = file.Value; //准备文件流 using (var fileStream = FileHelper.GetFileStream(fileName)) { if (fileStream != null) { //存在文件 //multipartFormDataContent.Add(new StreamContent(fileStream), file.Key, Path.GetFileName(fileName)); //报流已关闭的异常 multipartFormDataContent.Add(CreateFileContent(File.Open(fileName, FileMode.Open), Path.GetFileName(fileName)), file.Key, Path.GetFileName(fileName)); fileStream.Dispose(); } else { //不存在文件或只是注释 multipartFormDataContent.Add(new StringContent(string.Empty), file.Key, file.Value); } } } catch (Exception ex) { throw ex; } } hc.Headers.ContentType = MediaTypeHeaderValue.Parse(string.Format("multipart/form-data; boundary={0}", boundary)); } else { hc = new StreamContent(postStream); hc.Headers.ContentType = new MediaTypeHeaderValue("text/xml"); //使用Url格式Form表单Post提交的时候才使用application/x-www-form-urlencoded //去掉注释以测试Request.Body为空的情况 //hc.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); } //HttpContentHeader(hc, timeOut); #endregion if (!string.IsNullOrEmpty(refererUrl)) { client.DefaultRequestHeaders.Referrer = new Uri(refererUrl); } return(client); }
public void Perform() #endif { var request = WebRequest.Create(this.From); if (!string.IsNullOrEmpty(this.Proxy)) { var proxyInformation = new CustomProxyInformation(this.Proxy !); if (proxyInformation.Credentials != null) { request.Proxy = new WebProxy(proxyInformation.ServerAddress, false, null, proxyInformation.Credentials); } else { request.Proxy = new WebProxy(proxyInformation.ServerAddress); } } switch (this.Auth) { case AuthType.None: // Do nothing break; case AuthType.Sspi: request.UseDefaultCredentials = true; request.PreAuthenticate = true; request.Credentials = CredentialCache.DefaultCredentials; break; case AuthType.Basic: this.SetBasicAuthHeader(request, this.Username !, this.Password !); break; default: throw new WebException("Code defect. Unsupported authentication type: " + this.Auth); } bool supportsIfModifiedSince = false; if (request is HttpWebRequest httpRequest && File.Exists(this.To)) { supportsIfModifiedSince = true; httpRequest.IfModifiedSince = File.GetLastWriteTime(this.To); } DateTime lastModified = default; string tmpFilePath = this.To + ".tmp"; try { #if VNEXT using (var response = await request.GetResponseAsync()) #else using (var response = request.GetResponse()) #endif using (var responseStream = response.GetResponseStream()) using (var tmpStream = new FileStream(tmpFilePath, FileMode.Create)) { if (supportsIfModifiedSince) { lastModified = ((HttpWebResponse)response).LastModified; } #if VNEXT await responseStream.CopyToAsync(tmpStream); #elif NET20 CopyStream(responseStream, tmpStream); #else responseStream.CopyTo(tmpStream); #endif } FileHelper.MoveOrReplaceFile(this.To + ".tmp", this.To); if (supportsIfModifiedSince) { File.SetLastWriteTime(this.To, lastModified); } } catch (WebException e) { if (supportsIfModifiedSince && ((HttpWebResponse?)e.Response)?.StatusCode == HttpStatusCode.NotModified) { Logger.Info($"Skipped downloading unmodified resource '{this.From}'"); } else { throw; } } }
private void BindProcessFileTreeData(TreeGridView tgv, DataType.FileType fileType) { //this.tvFileList.Nodes.Clear(); tgv.Nodes.Clear(); IDocFileListService service = ServiceContainer.GetService<IDocFileListService>(); dtDocFile = service.GetDocFileDataTableByDCID(Document.DOCID, fileType.ToString()); // Font boldFont = new Font(tvFileList.DefaultCellStyle.Font, FontStyle.Bold); Font boldFont = new Font(tgv.DefaultCellStyle.Font, FontStyle.Bold); // DataView dv = new DataView(dt); node = new TreeGridNode(); // dv.RowFilter = "[PARENT]=" + parentId; //foreach (DataRowView dr in dv) //{ // if (parentId == "0") // { // node = tvFileList.Nodes.Add(Document.DOCNO, "", "", "", "", "", "", ""); node = tgv.Nodes.Add(Document.DOCNO, "", "", "", "", "", "", ""); node.DefaultCellStyle.Font = boldFont; // BindChildNode(node, (string)dr["PHYSICALID"]); HYDocumentMS.IFileHelper file = new FileHelper(); foreach (DataRow dr in dtDocFile.Rows) { node.Nodes.Add(dr["DFL_FILE_NAME"].ToString(), file.getDocumentAllPathByPathID(dr["DFL_FILE_CHILD_PATH"].ToString()), dr["DFL_VER_LATEST"].ToString(), dr["CHECKINFLG"].ToString(), dr["CHECKINDATE"].ToString(), dr["CHECKOUTFLG"].ToString(), dr["CHECKOUTDATE"].ToString(), dr["DFL_ID"].ToString()); node.Expand(); } }
/// <summary> /// 给.NET Framework使用的HttpPost请求公共设置方法 /// </summary> /// <param name="url"></param> /// <param name="cookieContainer"></param> /// <param name="postStream"></param> /// <param name="fileDictionary"></param> /// <param name="refererUrl"></param> /// <param name="encoding"></param> /// <param name="cer"></param> /// <param name="useAjax"></param> /// <param name="timeOut"></param> /// <param name="checkValidationResult"></param> /// <returns></returns> public static HttpWebRequest HttpPost_Common_Net45(string url, CookieContainer cookieContainer = null, Stream postStream = null, Dictionary <string, string> fileDictionary = null, string refererUrl = null, Encoding encoding = null, X509Certificate2 cer = null, bool useAjax = false, int timeOut = Config.TIME_OUT, bool checkValidationResult = false) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.Timeout = timeOut; request.Proxy = _webproxy; if (cer != null) { request.ClientCertificates.Add(cer); } if (checkValidationResult) { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); } #region 处理Form表单文件上传 var formUploadFile = fileDictionary != null && fileDictionary.Count > 0;//是否用Form上传文件 if (formUploadFile) { //通过表单上传文件 string boundary = "----" + DateTime.Now.Ticks.ToString("x"); postStream = postStream ?? new MemoryStream(); //byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n"); string fileFormdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n"; string dataFormdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}"; foreach (var file in fileDictionary) { try { var fileName = file.Value; //准备文件流 using (var fileStream = FileHelper.GetFileStream(fileName)) { string formdata = null; if (fileStream != null) { //存在文件 formdata = string.Format(fileFormdataTemplate, file.Key, /*fileName*/ Path.GetFileName(fileName)); } else { //不存在文件或只是注释 formdata = string.Format(dataFormdataTemplate, file.Key, file.Value); } //统一处理 var formdataBytes = Encoding.UTF8.GetBytes(postStream.Length == 0 ? formdata.Substring(2, formdata.Length - 2) : formdata);//第一行不需要换行 postStream.Write(formdataBytes, 0, formdataBytes.Length); //写入文件 if (fileStream != null) { byte[] buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { postStream.Write(buffer, 0, bytesRead); } } } } catch (Exception ex) { throw ex; } } //结尾 var footer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); postStream.Write(footer, 0, footer.Length); request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary); } else { request.ContentType = "application/x-www-form-urlencoded"; } #endregion request.ContentLength = postStream != null ? postStream.Length : 0; HttpClientHeader(request, refererUrl, useAjax, timeOut); if (cookieContainer != null) { request.CookieContainer = cookieContainer; } return(request); }
/// <summary> /// 检出文件 /// </summary> /// <param name="tgv"></param> /// <param name="fileType"></param> private void CheckOut(TreeGridView tgv, DataType.FileType fileType) { int rowIndex = tgv.CurrentCell.RowIndex; if (rowIndex <= 0) { MessageBox.Show("请选择文件", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } DataGridViewRow row = tgv.Rows[rowIndex]; HYDocumentMS.IFileHelper file = new FileHelper(); Boolean bl = file.isHasAuth(DataType.AuthParmsType.CheckOut, LoginInfo.LoginID, row.Cells["DFL_ID"].Value.ToString()); if (bl == false) { MessageBox.Show("你没有权限检出此文件!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } String Id = row.Cells["DFL_ID"].Value.ToString(); DOC_FILE_LIST docFileEntity = _docFileListService.GetDocFileEntityByDCID(Id); // HYPDM.Entities.PDM_PHYSICAL_FILE physicalfile = _physicalService.GetPhysicalFile(Id, ""); if (docFileEntity == null) return; if (docFileEntity.CHECKOUTFLG == "Y") { MessageBox.Show("当前文档已被检出,不能再次检出,请等待检出人检入!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } DetectionForm form = new DetectionForm(); form.DocFileEntity = docFileEntity; if (form.ShowDialog() == DialogResult.OK) { docFileEntity.CHECKOUTFLG = "Y"; docFileEntity.CHECKINFLG = "N"; docFileEntity.CHECKOUTDATE = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); docFileEntity.LASTUPDATEDATE = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); docFileEntity.LASTUPDATEUSER = LoginInfo.LoginID; docFileEntity.Save(); try { VersionSave("0", docFileEntity); } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } finally { MessageBox.Show("文件检出成功!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information); } } }
public static (FileInfo[] files, DirectoryInfo[] directories, DirectoryInfo rootDirectory) GetSourceInfo(this SyncTarget st) { var files = new List <FileInfo>(); DirectoryInfo[] directories = null; DirectoryInfo rootDirectory = null; if (st.source.IsFile()) { var file = st.source.ToFileInfo(); files.Add(file); rootDirectory = file.Directory; directories = new DirectoryInfo[1] { rootDirectory }; } else if (st.source.IsDirectory()) { rootDirectory = st.source.ToDirectoryInfo(); directories = rootDirectory.GetDirectories(recursive: st.recursive).Merge(rootDirectory); files = FileHelper.GetFiles(st.source, recursive: st.recursive).ToList(); if (!st.filesIgnore.IsNullOrEmpty() && !files.IsNullOrEmpty()) //remove files that should be ignored { foreach (var ignore in st.filesIgnore) { if (ignore.IsNullOrEmpty()) { continue; } if (files.IsNullOrEmpty()) { break; } var remove = FileHelper.GetFiles(st.source, recursive: st.recursive, pattern: ignore); foreach (var r in remove) { var toRemove = files.FirstOrDefault(x => x.FullName == r.FullName); if (toRemove != null) { files.Remove(toRemove); } if (files.IsNullOrEmpty()) { break; } } } } } else { var message = $"Could not process, source not found: '{st.source}'"; if (st.throwIfSourceNotFound) { throw new Exception(message); } else { Console.WriteLine(message); } } return(files?.ToArray(), directories, rootDirectory); }
/// <summary> /// 文件下载 /// </summary> private void downLoadFile(TreeGridView tgv, DataType.FileType fileType) { TreeGridNode node = null;//当前选择的节点 String serverpath = ""; node = new TreeGridNode(); //node = this.tvFileList.CurrentNode; node = tgv.CurrentNode; int index = node.RowIndex; if (index <= 0) { MessageBox.Show("请选择需要下载的文件" + "(" + index + ")", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (tgv.CurrentRow == null) { MessageBox.Show("请选择需要下载的文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { HYDocumentMS.IFileHelper file = new FileHelper(); Boolean bl = file.isHasAuth(DataType.AuthParmsType.DownLoad, LoginInfo.LoginID, tgv.CurrentRow.Cells["DFL_ID"].Value.ToString()); if (bl == false) { MessageBox.Show("你没有权限下载此文件!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } SaveFileDialog saveDialog = new SaveFileDialog(); saveDialog.FileName = node.Cells[0].Value.ToString(); //saveDialog.Filter = @"Text Files (*.txt)|*.txt|All Files (*.*)|*.*"; string suffix = node.Cells[0].Value.ToString().Substring(node.Cells[0].Value.ToString().LastIndexOf(@".") + 1); saveDialog.Filter = @"文件 (*." + suffix + ")|*." + suffix; DialogResult res = saveDialog.ShowDialog(); //SaveFileDialog saveDialog = new SaveFileDialog(); //saveDialog.FileName = node.Cells[0].Value.ToString(); //saveDialog.Filter = @"Text Files (*.txt)|*.txt|All Files (*.*)|*.*"; //DialogResult res = saveDialog.ShowDialog(); if (DialogResult.OK == res) { string clientSaveFileAndPath = saveDialog.FileName.ToString(); //MessageBox.Show(clientSavepath); // MessageBox.Show(index.ToString()); if (index > 0) //取消第一行 { serverpath = node.Cells[1].Value.ToString() + node.Cells[0].Value.ToString(); // MessageBox.Show(serverpath); //FileSockClient.DownLoadFileSocketClient downSocket = new FileSockClient.DownLoadFileSocketClient(serverpath, @"C:\\" + node.Cells[0].Value.ToString()); FileSockClient.DownLoadFileSocketClient downSocket = new FileSockClient.DownLoadFileSocketClient(serverpath, clientSaveFileAndPath); if (!downSocket.AckStatus) { return; } } else { MessageBox.Show("请选择需要下载的文件" + "(" + index + ")", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } // this.tvFileList.CurrentRow }
public AdsIndexDeleter(IIndexSystemMapper indexSystem, IAppConfig configuration, FileHelper fileHelper) { _indexSystem = indexSystem; _configuration = configuration; _fileHelper = fileHelper; }
public async Task<ActionResult> ModifyMentoringReport(MentoringReportViewModel dataRequestViewModel, string deleteFileSns, IEnumerable<HttpPostedFileBase> files) { ViewBag.LeftMenu = Global.MentoringReport; var mentorId = Session[Global.LoginID].ToString(); if (ModelState.IsValid) { var scMentoringReport = await _scMentoringReportService.GetMentoringReportById(dataRequestViewModel.ReportSn); scMentoringReport.Attendee = dataRequestViewModel.Attendee; scMentoringReport.BizWorkSn = dataRequestViewModel.BizWorkSn; scMentoringReport.CompSn = dataRequestViewModel.CompSn; scMentoringReport.MentorAreaCd = dataRequestViewModel.MentorAreaCd; scMentoringReport.MentoringContents = dataRequestViewModel.MentoringContents; scMentoringReport.MentoringDt = dataRequestViewModel.MentoringDt; scMentoringReport.MentoringEdHr = dataRequestViewModel.MentoringEdHr; scMentoringReport.MentoringPlace = dataRequestViewModel.MentoringPlace; scMentoringReport.MentoringStHr = dataRequestViewModel.MentoringStHr; scMentoringReport.MentoringSubject = dataRequestViewModel.MentoringSubject; scMentoringReport.SubmitDt = dataRequestViewModel.SubmitDt; scMentoringReport.UpdId = mentorId; scMentoringReport.UpdDt = DateTime.Now; //삭제파일 상태 업데이트 if (!string.IsNullOrEmpty(deleteFileSns.Trim())) { foreach (var deleteFileSn in deleteFileSns.Split(',').AsEnumerable()) { scMentoringReport.ScMentoringFileInfoes.Select(mtfi => mtfi.ScFileInfo).Where(fi => fi.FileSn == int.Parse(deleteFileSn)).FirstOrDefault().Status = "D"; } } //첨부파일 if (files != null) { var fileHelper = new FileHelper(); foreach (var file in files) { if (file != null) { var savedFileName = fileHelper.GetUploadFileName(file); var subDirectoryPath = Path.Combine(FileType.Mentoring_Report.ToString(), DateTime.Now.Year.ToString(), DateTime.Now.Month.ToString()); var savedFilePath = Path.Combine(subDirectoryPath, savedFileName); var scFileInfo = new ScFileInfo { FileNm = Path.GetFileName(file.FileName), FilePath = savedFilePath, Status = "N", RegId = Session[Global.LoginID].ToString(), RegDt = DateTime.Now }; var scMentoringFileInfo = new ScMentoringFileInfo { ScFileInfo = scFileInfo }; //파일타입에 따라 재정의해서 넣어야 함(첨부파일, 사진) scMentoringFileInfo.Classify = fileHelper.HasImageFile(file) ? "P" : "A"; scMentoringReport.ScMentoringFileInfoes.Add(scMentoringFileInfo); await fileHelper.UploadFile(file, subDirectoryPath, savedFileName); } } } //수정 await _scMentoringReportService.ModifyScMentoringReportAsync(scMentoringReport); return RedirectToAction("MentoringReportList", "MentoringReport"); } ModelState.AddModelError("", "입력값 검증 실패."); return View(dataRequestViewModel); }
public override string GetLocalFileName(HttpContentHeaders headers) { return(FileHelper.GenerateFileName() + "_" + headers.ContentDisposition.FileName.Replace("\"", string.Empty)); }
public async Task<ActionResult> MentoringReportDetail(int reportSn, SelectedMentorReportParmModel selectParam, string searchType) { ViewBag.LeftMenu = Global.Report; var scMentoringReport = await _scMentoringReportService.GetMentoringReportById(reportSn); //멘토링 사진 var listscMentoringImageInfo = scMentoringReport.ScMentoringFileInfoes.Where(mtfi => mtfi.Classify == "P").Select(mtfi => mtfi.ScFileInfo).Where(fi => fi.Status == "N"); //사진추가 var listMentoringPhotoView = Mapper.Map<List<FileContent>>(listscMentoringImageInfo); FileHelper fileHelper = new FileHelper(); foreach (var mentoringPhoto in listMentoringPhotoView) { mentoringPhoto.FileBase64String = await fileHelper.GetPhotoString(mentoringPhoto.FilePath); } //첨부파일 var listscFileInfo = scMentoringReport.ScMentoringFileInfoes.Where(mtfi => mtfi.Classify == "A").Select(mtfi => mtfi.ScFileInfo).Where(fi => fi.Status == "N"); var listFileContentView = Mapper.Map<List<FileContent>>(listscFileInfo); //멘토링 상세 매핑 var reportViewModel = Mapper.Map<MentoringReportViewModel>(scMentoringReport); //멘토링상세뷰에 파일정보 추가 reportViewModel.FileContents = listFileContentView; reportViewModel.MentoringPhoto = listMentoringPhotoView; //검색조건 유지를 위해 ViewBag.SelectParam = selectParam; //호출한 탭으로 돌아가기 위해 ViewBag.SearchType = searchType; return View(reportViewModel); }
public ActionResult UploadResource() { if (Request.Files.Count != 1) { return(Content("Error")); } HttpPostedFileBase hpf = Request.Files[0]; var md5 = FileHelper.ConvertToMD5(hpf.InputStream); var file = Files.ConditionQuery(f.Md5 == md5, null).FirstOrDefault(); if (file == null) { var ext = Path.GetExtension(hpf.FileName); var anotherName = md5 + ext; // upload file to CDN Server var uploadFile = new UploadFile { Stream = hpf.InputStream, FileName = $"2019/files/{DateTime.Today.ToString("yyyyMMdd")}/{anotherName}" }; var result = FileUploader.SliceUpload(uploadFile); if (null == result || null == result.FileUrl) { return(Content("上传失败")); } if (ext.ToLowerInvariant() == ".doc" || ext.ToLowerInvariant() == ".docx") { Stream docStream = null; try { docStream = Util.ThirdParty.Aspose.WordConverter.ConvertoPdf(hpf.InputStream); var docFile = new UploadFile { Stream = docStream, FileName = $"2019/files/{DateTime.Today.ToString("yyyyMMdd")}/{anotherName}{FileHelper.PdfExtName}" }; var docResult = FileUploader.SliceUpload(docFile); if (null == docResult || null == docResult.FileUrl || !docResult.IsSuccess) { return(Content("word 转pdf失败")); } } catch { } finally { if (docStream != null) { docStream.Close(); docStream.Dispose(); } } } file = new Files { Md5 = md5, FileName = hpf.FileName, FilePath = result.FileUrl, ExtName = ext, FileSize = hpf.ContentLength }; db.FilesDal.Insert(file); } if (Request.IsAjaxRequest()) { return(Json(new { fileId = file.FileId, name = file.FileName, path = file.FilePath, size = file.FileSize, ext = file.ExtName })); } else { return(Content("upload ok")); } }
public Http2SessionHandler(IDictionary<string, object> environment) { if (environment["useFlowControl"] is bool) { _useFlowControl = (bool) environment["useFlowControl"]; } else { _useFlowControl = true; } if (environment["usePriorities"] is bool) { _usePriorities = (bool) environment["usePriorities"]; } else { _usePriorities = true; } if (environment["useHandshake"] is bool) { _useHandshake = (bool) environment["useHandshake"]; } else { _useHandshake = true; } _fileHelper = new FileHelper(ConnectionEnd.Client); }
static void TestSplitTrainTestTransform(string option, int numThreads = 1) { using (var host = EnvHelper.NewTestEnvironment(conc: numThreads == 1 ? 1 : 0)) { var inputsl = new List <InputOutput>(); for (int i = 0; i < 100; ++i) { inputsl.Add(new InputOutput { X = new float[] { 0, 1 }, Y = i }); } var inputs = inputsl.ToArray(); var data = host.CreateStreamingDataView(inputs); var args = new SplitTrainTestTransform.Arguments { newColumn = "Part", numThreads = numThreads }; if (option == "2") { var methodName = System.Reflection.MethodBase.GetCurrentMethod().Name; var cacheFile = FileHelper.GetOutputFile("cacheFile.idv", methodName); args.cacheFile = cacheFile; } var transformedData = new SplitTrainTestTransform(host, args, data); var counter1 = new Dictionary <int, List <int> >(); using (var cursor = transformedData.GetRowCursor(i => true)) { int index = SchemaHelper.GetColumnIndex(cursor.Schema, "Y"); var sortColumnGetter = cursor.GetGetter <int>(index); index = SchemaHelper.GetColumnIndex(cursor.Schema, args.newColumn); var partGetter = cursor.GetGetter <int>(index); var schema = SchemaHelper.ToString(cursor.Schema); if (string.IsNullOrEmpty(schema)) { throw new Exception("null"); } if (!schema.Contains("Part:I4")) { throw new Exception(schema); } var schema2 = SchemaHelper.ToString(transformedData.OutputSchema); SchemaHelper.CheckSchema(host, transformedData.OutputSchema, cursor.Schema); int got = 0; int part = 0; while (cursor.MoveNext()) { sortColumnGetter(ref got); partGetter(ref part); if (!counter1.ContainsKey(part)) { counter1[part] = new List <int>(); } if (counter1[part].Any() && got.Equals(counter1[part][counter1[part].Count - 1])) { throw new Exception("Unexpected value, they should be all different."); } counter1[part].Add(got); } } // Check than there is no overlap. if (counter1.Count != 2) { throw new Exception(string.Format("Too many or not enough parts: {0}", counter1.Count)); } var nb = counter1.Select(c => c.Value.Count).Sum(); if (inputs.Length != nb) { throw new Exception(string.Format("Length mismath: {0} != {1}", inputs.Length, nb)); } foreach (var part in counter1) { var hash = part.Value.ToDictionary(c => c, d => d); if (hash.Count != part.Value.Count) { throw new Exception(string.Format("Not identical id for part {0}", part)); } } var part0 = new HashSet <int>(counter1[0]); var part1 = new HashSet <int>(counter1[1]); if (part0.Intersect(part1).Any()) { throw new Exception("Intersection is not null."); } // Check sizes. if (part0.Count > part1.Count * 2 + 15) { throw new Exception("Size are different from ratios."); } if (part0.Count < part1.Count + 5) { throw new Exception("Size are different from ratios."); } // We check a second run brings the same results (CacheView). var counter2 = new Dictionary <int, List <int> >(); using (var cursor = transformedData.GetRowCursor(i => true)) { var schema = SchemaHelper.ToString(cursor.Schema); if (string.IsNullOrEmpty(schema)) { throw new Exception("null"); } if (!schema.Contains("Part:I4")) { throw new Exception(schema); } var schema2 = SchemaHelper.ToString(transformedData.OutputSchema); SchemaHelper.CheckSchema(host, transformedData.OutputSchema, cursor.Schema); int index = SchemaHelper.GetColumnIndex(cursor.Schema, "Y"); var sortColumnGetter = cursor.GetGetter <int>(index); index = SchemaHelper.GetColumnIndex(cursor.Schema, args.newColumn); var partGetter = cursor.GetGetter <int>(index); int got = 0; int part = 0; while (cursor.MoveNext()) { sortColumnGetter(ref got); partGetter(ref part); if (!counter2.ContainsKey(part)) { counter2[part] = new List <int>(); } counter2[part].Add(got); } } if (counter1.Count != counter2.Count) { throw new Exception("Not the same number of parts."); } foreach (var pair in counter1) { var list1 = pair.Value; var list2 = counter2[pair.Key]; var difList = list1.Where(a => !list2.Any(a1 => a1 == a)) .Union(list2.Where(a => !list1.Any(a1 => a1 == a))); if (difList.Any()) { throw new Exception("Not the same results for a part."); } } } }
public async Task<ActionResult> RegSend(RegSendViewModels dataRequestViewModel, string expertType, IEnumerable<HttpPostedFileBase> files) { ViewBag.LeftMenu = Global.ExpertService; if (ModelState.IsValid) { var scReqDoc = Mapper.Map<ScReqDoc>(dataRequestViewModel); //회원정보 추가 정보 설정 scReqDoc.ChkYn = "N"; scReqDoc.ReqDt = DateTime.Now; scReqDoc.SenderId = Session[Global.LoginID].ToString(); scReqDoc.Status = "N"; //신규파일정보저장 및 파일업로드 foreach (var file in files) { if (file != null) { var fileHelper = new FileHelper(); var savedFileName = fileHelper.GetUploadFileName(file); var subDirectoryPath = Path.Combine(FileType.Document.ToString(), DateTime.Now.Year.ToString(), DateTime.Now.Month.ToString()); var savedFilePath = Path.Combine(subDirectoryPath, savedFileName); var scFileInfo = new ScFileInfo { FileNm = Path.GetFileName(file.FileName), FilePath = savedFilePath, Status = "N", RegId = Session[Global.LoginID].ToString(), RegDt = DateTime.Now }; var scReqDocFile = new ScReqDocFile { ScFileInfo = scFileInfo }; scReqDocFile.RegType = "S"; scReqDoc.ScReqDocFiles.Add(scReqDocFile); await fileHelper.UploadFile(file, subDirectoryPath, savedFileName); } } //저장 int result = await _scReqDocService.AddReqDocAsync(scReqDoc); if (result != -1) return RedirectToAction("SendList", "ExpertService", new {expertType = expertType }); else { ModelState.AddModelError("", "자료요청 등록 실패."); return View(dataRequestViewModel); } } ModelState.AddModelError("", "입력값 검증 실패."); return View(dataRequestViewModel); }
private void ResolveFilesConflict(ConflictData item) { string[] filenames = Module.CheckoutConflictedFiles(item); try { if (CheckForLocalRevision(item) && CheckForRemoteRevision(item)) { if (TryMergeWithScript(item.Filename, filenames[0], filenames[1], filenames[2])) { Cursor.Current = Cursors.Default; return; } if (FileHelper.IsBinaryFile(Module, item.Local.Filename)) { if (MessageBox.Show(this, string.Format(fileIsBinary.Text, _mergetool), _binaryFileWarningCaption.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No) { BinairyFilesChooseLocalBaseRemote(item); return; } } string arguments = _mergetoolCmd; //Check if there is a base file. If not, ask user to fall back to 2-way merge. //git doesn't support 2-way merge, but we can try to adjust attributes to fix this. //For kdiff3 this is easy; just remove the 3rd file from the arguments. Since the //filenames are quoted, this takes a little extra effort. We need to remove these //quotes also. For tortoise and araxis a little bit more magic is needed. if (item.Base.Filename == null) { var text = string.Format(noBaseRevision.Text, item.Filename); DialogResult result = MessageBox.Show(this, text, _noBaseFileMergeCaption.Text, MessageBoxButtons.YesNoCancel); if (result == DialogResult.Yes) { Use2WayMerge(ref arguments); } if (result == DialogResult.Cancel) { return; } } arguments = arguments.Replace("$BASE", filenames[0]); arguments = arguments.Replace("$LOCAL", filenames[1]); arguments = arguments.Replace("$REMOTE", filenames[2]); arguments = arguments.Replace("$MERGED", item.Filename); //get timestamp of file before merge. This is an extra check to verify if merge was successful DateTime lastWriteTimeBeforeMerge = DateTime.Now; if (File.Exists(Path.Combine(Module.WorkingDir, item.Filename))) { lastWriteTimeBeforeMerge = File.GetLastWriteTime(Path.Combine(Module.WorkingDir, item.Filename)); } var res = Module.RunCmdResult(_mergetoolPath, "" + arguments + ""); DateTime lastWriteTimeAfterMerge = lastWriteTimeBeforeMerge; if (File.Exists(Path.Combine(Module.WorkingDir, item.Filename))) { lastWriteTimeAfterMerge = File.GetLastWriteTime(Path.Combine(Module.WorkingDir, item.Filename)); } //Check exitcode AND timestamp of the file. If exitcode is success and //time timestamp is changed, we are pretty sure the merge was done. if (res.ExitCode == 0 && lastWriteTimeBeforeMerge != lastWriteTimeAfterMerge) { StageFile(item.Filename); } //If the exitcode is 1, but the file is changed, ask if the merge conflict is solved. //If the exitcode is 0, but the file is not changed, ask if the merge conflict is solved. if ((res.ExitCode == 1 && lastWriteTimeBeforeMerge != lastWriteTimeAfterMerge) || (res.ExitCode == 0 && lastWriteTimeBeforeMerge == lastWriteTimeAfterMerge)) { if (MessageBox.Show(this, askMergeConflictSolved.Text, askMergeConflictSolvedCaption.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { StageFile(item.Filename); } } } } finally { DeleteTemporaryFiles(filenames); } }
public Http2ClientMessageHandler(DuplexStream stream, ConnectionEnd end, TransportInformation transportInfo, CancellationToken cancel) : base(stream, end, stream.IsSecure, transportInfo, cancel) { _fileHelper = new FileHelper(ConnectionEnd.Client); stream.OnClose += delegate { Dispose(); }; }
/// <summary> /// 写异常信息 /// </summary> /// <param name="ex"></param> /// <param name="path"></param> public static void WriteTo(this Exception ex, string path) { FileHelper.WriteException(path, ex); }