private void ExportChart(string fileName, ISymbolicDataAnalysisSolution solution, string formula) { FileInfo newFile = new FileInfo(fileName); if (newFile.Exists) { newFile.Delete(); newFile = new FileInfo(fileName); } var formulaParts = formula.Split(new string[] { Environment.NewLine }, StringSplitOptions.None); using (ExcelPackage package = new ExcelPackage(newFile)) { ExcelWorksheet modelWorksheet = package.Workbook.Worksheets.Add("Model"); FormatModelSheet(modelWorksheet, solution, formulaParts); ExcelWorksheet datasetWorksheet = package.Workbook.Worksheets.Add("Dataset"); WriteDatasetToExcel(datasetWorksheet, solution.ProblemData); ExcelWorksheet inputsWorksheet = package.Workbook.Worksheets.Add("Inputs"); WriteInputSheet(inputsWorksheet, datasetWorksheet, formulaParts.Skip(2), solution.ProblemData.Dataset); if (solution is IRegressionSolution) { ExcelWorksheet estimatedWorksheet = package.Workbook.Worksheets.Add("Estimated Values"); WriteEstimatedWorksheet(estimatedWorksheet, datasetWorksheet, formulaParts, solution as IRegressionSolution); ExcelWorksheet chartsWorksheet = package.Workbook.Worksheets.Add("Charts"); AddCharts(chartsWorksheet); } package.Workbook.Properties.Title = "Excel Export"; package.Workbook.Properties.Author = "HEAL"; package.Workbook.Properties.Comments = "Excel export of a symbolic data analysis solution from HeuristicLab"; package.Save(); } }
public static string UpdateStatus(string status, TwUser user, string replyId) { Regex regex = new Regex(@"\[(.*?)\]"); List<FileInfo> media = new List<FileInfo>(); foreach (System.Text.RegularExpressions.Match match in regex.Matches(status)) { status = status.Replace(match.Value, ""); FileInfo file = new FileInfo(match.Value.Replace("[", "").Replace("]", "")); if (!file.Exists) throw new FileNotFoundException("File not found", file.FullName); media.Add(file); } if (media.Count > 4) //limited by the twitter API throw new ArgumentOutOfRangeException("media", "Up to 4 media files are allowed per tweet"); if (user == null) user = TwUser.LoadCredentials(); string encodedStatus = Util.EncodeString(status); if (media.Count == 0) return InternalUpdateStatus(user, encodedStatus, replyId); else return InternalUpdateWithMedia(user, encodedStatus, replyId, media); }
/// <summary> /// Writes the database to the location defined in the configuration file if it doesn't exist. /// </summary> public static void CheckForDatabase() { // A LocalSqlServer connection string get's added by default. Don't look at that one. foreach (ConnectionStringSettings connection in ConfigurationManager.ConnectionStrings.OfType<ConnectionStringSettings>().Where(c => c.Name != "LocalSqlServer")) { try { EntityConnectionStringBuilder builder = new EntityConnectionStringBuilder(connection.ConnectionString); SqlCeConnectionStringBuilder sqlCEBuilder = new SqlCeConnectionStringBuilder(builder.ProviderConnectionString); if (!File.Exists(sqlCEBuilder.DataSource)) { FileInfo info = new FileInfo(sqlCEBuilder.DataSource); if (!Directory.Exists(info.Directory.FullName)) { Directory.CreateDirectory(info.Directory.FullName); } File.WriteAllBytes(info.FullName, EncounterTracker.Properties.Resources.EncounterTracker); } break; } catch { } } }
/// <summary> /// Экспортирует массив данных в XLSX формат с учетом выбранной локали /// </summary> /// <param name="path">Путь к файлу, в который нужно сохранить данные</param> /// <param name="localisation">Локализация</param> /// <returns>Успешное завершение операции</returns> public override bool Export(String path, Localisation localisation) { try { if (!path.EndsWith(".xlsx")) path += ".xlsx"; log.Info(String.Format("Export to .xlsx file to: {0}", path)); var timer = new Stopwatch(); timer.Start(); var file = new FileInfo(path); using (var pck = new ExcelPackage(file)) { ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Sheet1"); ws.Cells["A1"].LoadFromDataTable(dataTable, true); ws.Cells.AutoFitColumns(); pck.Save(); } timer.Stop(); log.Info(String.Format("Export complete! Elapsed time: {0} ms", timer.Elapsed.Milliseconds)); return true; } catch (Exception ex) { log.Error("Can't export to .xlsx file!", ex); return false; } }
/// <summary> /// Archives the exception report. /// The name of the PDF file is modified to make it easier to identify. /// </summary> /// <param name="pdfFile">The PDF file.</param> /// <param name="archiveDirectory">The archive directory.</param> public static void ArchiveException(FileInfo pdfFile, string archiveDirectory) { // Create a new subdirectory in the archive directory // This is based on the date of the report being archived DirectoryInfo di = new DirectoryInfo(archiveDirectory); string archiveFileName = pdfFile.Name; string newSubFolder = ParseFolderName(archiveFileName); try { di.CreateSubdirectory(newSubFolder); } catch (Exception ex) { // The folder already exists so don't create it } // Create destination path // Insert _EXCEPT into file name // This will make it easier to identify as an exception in the archive folder string destFileName = archiveFileName.Insert(archiveFileName.IndexOf("."), "_EXCEPT"); string destFullPath = archiveDirectory + "\\" + newSubFolder + "\\" + destFileName; // Move the file to the archive directory try { pdfFile.MoveTo(destFullPath); } catch (Exception ex) { } }
private void ExecuteScript(FileInfo code) { this.progressLabel.Text = "Evaluating: " + code.Name; Application.DoEvents(); this.Client.CodeManager.Execute<Object>(code, Make.Dictionary<Object>(host => this.Client)); this.progressBar.Increment(1); }
public static void SortLogs(string[] logs) { foreach (var logfile in logs) { FileInfo info = new FileInfo(logfile); if (info.Length <= 1024) { try { string destdir = Path.GetDirectoryName(logfile) + Path.DirectorySeparatorChar + "SMALL" + Path.DirectorySeparatorChar; if (!Directory.Exists(destdir)) Directory.CreateDirectory(destdir); File.Move(logfile, destdir + Path.GetFileName(logfile)); File.Move(logfile.Replace(".tlog", ".rlog"), destdir + Path.GetFileName(logfile).Replace(".tlog", ".rlog")); } catch { } continue; } MAVLinkInterface mine = new MAVLinkInterface(); try { using (mine.logplaybackfile = new BinaryReader(File.Open(logfile, FileMode.Open, FileAccess.Read, FileShare.Read))) { mine.logreadmode = true; byte[] hbpacket = mine.getHeartBeat(); if (hbpacket.Length == 0) continue; MAVLink.mavlink_heartbeat_t hb = (MAVLink.mavlink_heartbeat_t)mine.DebugPacket(hbpacket); mine.logreadmode = false; mine.logplaybackfile.Close(); string destdir = Path.GetDirectoryName(logfile) + Path.DirectorySeparatorChar + mine.MAV.aptype.ToString() + Path.DirectorySeparatorChar + hbpacket[3] + Path.DirectorySeparatorChar; if (!Directory.Exists(destdir)) Directory.CreateDirectory(destdir); File.Move(logfile, destdir + Path.GetFileName(logfile)); try { File.Move(logfile.Replace(".tlog", ".rlog"), destdir + Path.GetFileName(logfile).Replace(".tlog", ".rlog")); } catch { } } } catch { continue; } } }
internal static bool ExtractArchive(string archive, string destination) { //REFACTOR: Only create RAR and ZIP classes after discovering that the file actually has a .zip or .rar extension FileInfo archiveFI = new FileInfo(archive); Rar rar = new Rar(); FastZip fz = new FastZip(); double archivesize = archiveFI.Length * 2; char driveLetter = archiveFI.FullName[0]; if (!CheckDiskSpaceQuota(archivesize, driveLetter)) return false; if (archiveFI.Extension == ".rar" || archiveFI.Extension == ".RAR") return ExtractRarArchive(archive, destination, archiveFI, rar); // ReSharper disable ConvertIfStatementToReturnStatement if (archiveFI.Extension == ".zip" || archiveFI.Extension == ".ZIP") // ReSharper restore ConvertIfStatementToReturnStatement return ExtractZipArchive(archive, destination, fz); //TODO: Should this return false? return true; }
public void Execute() { var files = Directory.GetFiles(SourceFolder, "*.jpg"); foreach (var file in files) { try { DateTime dt; using (var em = new ExifManager(file)) { dt = em.DateTimeOriginal; } if (dt == DateTime.MinValue) continue; var fi = new FileInfo(file); var newName = Path.Combine(DestinantionFolder, string.Format("{0}.jpg", dt.ToString("yyyy-MM-dd_HH.mm.ss"))); fi.MoveTo(newName); } catch { } } }
// http://stackoverflow.com/questions/12811850/setting-a-files-acl-to-be-inherited private static void RemoveCustomACLs(string destination) { FileInfo fileInfo; FileSecurity fileSecurity; AuthorizationRuleCollection fileRules; fileInfo = new FileInfo(destination); fileSecurity = fileInfo.GetAccessControl(); fileSecurity.SetAccessRuleProtection(false, false); fileSecurity.SetOwner(WindowsIdentity.GetCurrent().User); /* * Only fetch the explicit rules since I want to keep the inherited ones. Not * sure if the target type matters in this case since I am not examining the * IdentityReference. */ fileRules = fileSecurity.GetAccessRules(includeExplicit: true, includeInherited: false, targetType: typeof(NTAccount)); /* * fileRules is a AuthorizationRuleCollection object, which can contain objects * other than FileSystemAccessRule (in theory), but GetAccessRules should only * ever return a collection of FileSystemAccessRules, so we will just declare * rule explicitly as a FileSystemAccessRule. */ foreach (FileSystemAccessRule rule in fileRules) { /* * Remove any explicit permissions so we are just left with inherited ones. */ fileSecurity.RemoveAccessRule(rule); } fileInfo.SetAccessControl(fileSecurity); }
/// <summary> /// The process for backing up a directory index is simple: /// a) create hard links to all the files in the lucene directory in a temp director /// that gives us the current snapshot, and protect us from lucene's /// deleting files. /// b) copy the hard links to the destination directory /// c) delete the temp directory /// </summary> public void Execute() { foreach (var file in Directory.EnumerateFiles(tempPath)) { Notify("Copying " + Path.GetFileName(file), BackupStatus.BackupMessageSeverity.Informational); var fullName = new FileInfo(file).FullName; FileCopy(file, Path.Combine(destination, Path.GetFileName(file)), fileToSize[fullName]); Notify("Copied " + Path.GetFileName(file), BackupStatus.BackupMessageSeverity.Informational); } try { IOExtensions.DeleteDirectory(tempPath); } catch (Exception e) //cannot delete, probably because there is a file being written there { logger.WarnException( string.Format("Could not delete {0}, will delete those on startup", tempPath), e); foreach (var file in Directory.EnumerateFiles(tempPath)) { MoveFileEx(file, null, MoveFileDelayUntilReboot); } MoveFileEx(tempPath, null, MoveFileDelayUntilReboot); } }
public void LoadPlugins(string pluginPath, bool checkSubDirs) { if(!Directory.Exists(pluginPath)) return; if(Plugins.Any()) UnloadPlugins(); var dirInfo = new DirectoryInfo(pluginPath); var files = dirInfo.GetFiles().Select(f => f.FullName).ToList(); if(checkSubDirs) { foreach(var dir in dirInfo.GetDirectories()) files.AddRange(dir.GetFiles().Select(f => f.FullName)); } foreach(var file in files) { var fileInfo = new FileInfo(file); if(fileInfo.Extension.Equals(".dll")) { var plugins = GetModule(file, typeof(IPlugin)); foreach(var p in plugins) Plugins.Add(p); } } Logger.WriteLine("Loading Plugins...", "PluginManager"); LoadPluginSettings(); }
public void TestWriteStructures(string file) { var structureReader = new StructureParsingManager(); var fileInfo = new FileInfo(file); IStructureWorkspace structureWorkspace; using (var readable = new FileReadableDataLocation(fileInfo)) { structureWorkspace = structureReader.ParseStructures(readable); } ISdmxObjects structureBeans = structureWorkspace.GetStructureObjects(false); string output = string.Format(CultureInfo.InvariantCulture, "test-sdmxv2.1-{0}", fileInfo.Name); var writtingManager = new StructureWriterManager(); using (var outputStream = new FileStream(output, FileMode.Create)) { writtingManager.WriteStructures(structureBeans, new SdmxStructureFormat(StructureOutputFormat.GetFromEnum(StructureOutputFormatEnumType.SdmxV21StructureDocument)), outputStream); } using (var readable = new FileReadableDataLocation(output)) { XMLParser.ValidateXml(readable, SdmxSchemaEnumType.VersionTwoPointOne); var structures = structureReader.ParseStructures(readable); Assert.NotNull(structures); } }
public static ProcessStartInfo CreateTestAndCoverageProcessStartInfo(Settings settings, string[] fileNames) { ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.CreateNoWindow = true; startInfo.UseShellExecute = false; startInfo.FileName = @"""" + settings.PartCoverPath + @""""; startInfo.Arguments += " --target "; startInfo.Arguments += @"""" + settings.MSTestPath + @""""; startInfo.Arguments += " --target-work-dir "; startInfo.Arguments += @"""" + settings.OutputPath + @""""; // trim trailing slash? startInfo.Arguments += " --target-args "; startInfo.Arguments += @""""; foreach (string fileName in fileNames) { FileInfo f = new FileInfo(fileName); startInfo.Arguments += " /testcontainer:"; startInfo.Arguments += f.Name; } startInfo.Arguments += " /noisolation"; startInfo.Arguments += " /nologo"; startInfo.Arguments += " /resultsfile:"; startInfo.Arguments += settings.TestLogFileName; startInfo.Arguments += @""""; startInfo.Arguments += " --include " + settings.CoverageReportingAssembliesRegEx; startInfo.Arguments += " --output " + @"""" + Path.Combine(settings.OutputPath, settings.CoverageLogFileName) + @""""; return startInfo; }
public WebViewer(FileInfo file) { InitializeComponent(); File = file; Text = Path.GetFileNameWithoutExtension(File.FullName); _childBrowser = new WebControl(); _childBrowser.WebView = new WebView(); _childBrowser.WebView.FileDialog += OnProcessFileDialog; _childBrowser.WebView.BeforeDownload += OnWebViewBeforeDownload; _childBrowser.WebView.DownloadUpdated += OnWebViewDownloadUpdated; _childBrowser.WebView.DownloadCompleted += OnWebViewDownloadCompleted; _childBrowser.WebView.DownloadCanceled += OnWebViewDownloadCanceled; _childBrowser.WebView.CustomUserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Essential Objects Chrome/41.0.2272.16 Safari/537.36"; Controls.Add(_childBrowser); _browser = new WebControl(); _browser.WebView = new WebView(); _browser.Dock = DockStyle.Fill; _browser.WebView.LoadCompleted += OnMainWebViewLoadComplete; _browser.WebView.NewWindow += OnMainWebViewNewWindow; _browser.WebView.BeforeDownload += OnWebViewBeforeDownload; _browser.WebView.CustomUserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Essential Objects Chrome/41.0.2272.16 Safari/537.36"; Controls.Add(_browser); _browser.BringToFront(); }
private static bool ExtractRarArchive(string archive, string destination, FileInfo archiveFI, Rar rar) { Debugger.LogMessageToFile("[Archive extractor] Found RAR archive: " + archiveFI.FullName); #region Open if (!rar.Open(archive)) { Debugger.LogMessageToFile("[Archive extractor] Failed to open archive: " + rar.LastErrorText); //MessageBox.Show("Failed to open archive " + rar.LastErrorText); return false; } Debugger.LogMessageToFile("[Archive extractor] Archive opened succesfully."); #endregion #region Extract //TODO: Check if destination directory exists and if not, create it if (!rar.Unrar(destination)) { Debugger.LogMessageToFile("[Archive extractor] Failed to extract archive: " + rar.LastErrorText); //MessageBox.Show("Failed to extract archive " + rar.LastErrorText); return false; } Debugger.LogMessageToFile("[Archive extractor] Archive was extracted succesfully."); #endregion rar.Close(); DeleteLeftOfMultiparts(rar); return true; }
public DecryptFile(FileInfo decryptedFile, FileInfo encryptedFile) : this() { if (decryptedFile != null) { ID = System.IO.Path.GetFileNameWithoutExtension(decryptedFile.Name); Name = decryptedFile.Name; Path = decryptedFile.DirectoryName; FileDateTime = decryptedFile.LastWriteTime.ToString(); Exists = decryptedFile.Exists; } else { Exists = false; } if (encryptedFile != null) { if (ID == null) { ID = System.IO.Path.GetFileNameWithoutExtension(encryptedFile.Name); } EncryptName = encryptedFile.Name; EncryptPath = encryptedFile.DirectoryName; EncryptDateTime = encryptedFile.LastWriteTime.ToString(); EncryptExists = encryptedFile.Exists; } else { EncryptExists = false; } }
public void test000_FirstPack() { FileInfo packFile = getPack("pack-34be9032ac282b11fa9babdc2b2a93ca996c9c2f.pack"); Stream @is = packFile.Open(System.IO.FileMode.Open, FileAccess.Read); try { FileInfo tmppack = new FileInfo(Path.Combine(trash.ToString(), "tmp_pack1")); FileInfo idxFile = new FileInfo(Path.Combine(trash.ToString(), "tmp_pack1.idx")); FileInfo tmpPackFile = new FileInfo(Path.Combine(trash.ToString(), "tmp_pack1.pack")); tmppack.Create().Close(); idxFile.Create().Close(); tmpPackFile.Create().Close(); IndexPack pack = new IndexPack(db, @is, tmppack); pack.index(new TextProgressMonitor()); PackFile file = new PackFile(idxFile, tmpPackFile); Assert.IsTrue(file.HasObject(ObjectId.FromString("4b825dc642cb6eb9a060e54bf8d69288fbee4904"))); Assert.IsTrue(file.HasObject(ObjectId.FromString("540a36d136cf413e4b064c2b0e0a4db60f77feab"))); Assert.IsTrue(file.HasObject(ObjectId.FromString("5b6e7c66c276e7610d4a73c70ec1a1f7c1003259"))); Assert.IsTrue(file.HasObject(ObjectId.FromString("6ff87c4664981e4397625791c8ea3bbb5f2279a3"))); Assert.IsTrue(file.HasObject(ObjectId.FromString("82c6b885ff600be425b4ea96dee75dca255b69e7"))); Assert.IsTrue(file.HasObject(ObjectId.FromString("902d5476fa249b7abc9d84c611577a81381f0327"))); Assert.IsTrue(file.HasObject(ObjectId.FromString("aabf2ffaec9b497f0950352b3e582d73035c2035"))); Assert.IsTrue(file.HasObject(ObjectId.FromString("c59759f143fb1fe21c197981df75a7ee00290799"))); } finally { @is.Close(); } }
public DisassembleResult Disassemble(string compiledFilePath, string additionalArguments = null) { if (!File.Exists(compiledFilePath)) { throw new ArgumentException( $"Compiled file not found in: {compiledFilePath}.", nameof(compiledFilePath)); } var workingDirectory = new FileInfo(this.DisassemblerPath).DirectoryName; var arguments = this.BuildDisassemblerArguments(compiledFilePath, additionalArguments); var disassemblerProcessStartInfo = new ProcessStartInfo(this.DisassemblerPath) { RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden, WorkingDirectory = workingDirectory, Arguments = arguments }; this.UpdateDisassemblerProcessStartInfo(disassemblerProcessStartInfo); string disassambledCode; var isDisassembledSuccessfully = this.ExecuteDisassemblerProcess(disassemblerProcessStartInfo, out disassambledCode); return new DisassembleResult(isDisassembledSuccessfully, disassambledCode); }
public void Load(FileInfo file) { using (var stream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read)) { Load(stream); } }
internal static IList<Test> LoadAll() { var file = new FileInfo("tests.xml"); if (!file.Exists) return new Test[0]; XmlDocument xml = new XmlDocument(); using (var fs = file.OpenRead()) xml.Load(fs); var ret = new List<Test>(); foreach (XmlNode node in xml.SelectNodes("/Tests/*")) { var n = node.SelectSingleNode("./Type"); if (n == null) throw new InvalidOperationException("Test Type must be informed."); var typeName = n.InnerText; var type = FindType(typeName); if (type == null) throw new InvalidOperationException(string.Format("'{0}' is not a valid Test.", typeName)); var obj = (Test)Activator.CreateInstance(type); node.ToEntity(obj); ret.Add(obj); } return ret; }
/// <summary> /// Explores the content of the folder using the given set of file masks. /// </summary> /// <param name="path">The root folder to explore.</param> /// <param name="masks">A collection of file masks to match against.</param> private void ExploreFolderWithMasks(String path, String[] masks) { this.knownPathes.Add(path); //checks the directory for each mask provided foreach (String mask in masks) { String[] files = Directory.GetFiles(path, mask); foreach (String file in files) { //prevents the addition of the same file multiple times if it happens to match multiple masks if (!this.foundFiles.Contains(file)) { this.foundFiles.Add(file); } } } if (!recursive) return; String[] dirs = Directory.GetDirectories(path); foreach (String dir in dirs) { try { if (!this.knownPathes.Contains(dir)) { FileInfo info = new FileInfo(dir); if ((info.Attributes & FileAttributes.Hidden) == 0) this.ExploreFolderWithMasks(dir, masks); } } catch { /* Might be system folder.. */ }; } }
public string Save(FileInfo file) { using (FileStream fileStream = new FileStream(file.FullName, FileMode.Open)) { return Save(file.Name, fileStream); } }
public CmsProcessableFile( FileInfo file, int bufSize) { _file = file; _bufSize = bufSize; }
public Credentials() { string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + Path.DirectorySeparatorChar + "Gradians.com" ; string local = desktop + Path.DirectorySeparatorChar + ".local" ; FileInfo localCnfg = new FileInfo(local) ; remote = !localCnfg.Exists ; if (remote) { ftpServer = "109.74.201.62" ; username = "******" ; password = "******" ; bankRelPath = "bank" ; } else { // parse the local configuration file string[] lines = File.ReadAllLines(local) ; foreach (string line in lines) { string[] tokens = line.Split('=') ; if (tokens.Length != 2) continue ; if (String.Compare(tokens[0],"username", true) == 0) { username = tokens[1]; } else if (String.Compare(tokens[0],"password", true) == 0) { password = tokens[1] ; } else if (String.Compare(tokens[0], "bank", true) == 0) { bankRelPath = tokens[1] ; } } ftpServer = "localhost" ; } }
/// <summary> /// The normal PDF archival method. /// </summary> /// <param name="pdfFile">The PDF file.</param> /// <param name="archiveDirectory">The archive directory.</param> public static void ArchiveNormal(FileInfo pdfFile, string archiveDirectory) { // Create a new subdirectory in the archive directory // This is based on the date of the report being archived DirectoryInfo di = new DirectoryInfo(archiveDirectory); string archiveFileName = pdfFile.Name; string newSubFolder = ParseFolderName(archiveFileName); try { di.CreateSubdirectory(newSubFolder); } catch (Exception ex) { // The folder already exists so don't create it } // Create destination path string destFullPath = archiveDirectory + "\\" + newSubFolder + "\\" + pdfFile.Name; // Move the file to the archive directory try { pdfFile.MoveTo(destFullPath); } catch (Exception ex) { // Unable to move the PDF to the archive } }
public byte[] FilenameToBytes(string filename) { byte[] data = null; // get the file information form the selected file FileInfo fInfo = new FileInfo(filename); // get the length of the file to see if it is possible // to upload it (with the standard 4 MB limit) long numBytes = fInfo.Length; double dLen = Convert.ToDouble(fInfo.Length / 1000000); // set up a file stream and binary reader for the // selected file FileStream fStream = new FileStream(filename, FileMode.Open, FileAccess.Read); BinaryReader br = new BinaryReader(fStream); // convert the file to a byte array data = br.ReadBytes((int)numBytes); br.Close(); fStream.Close(); fStream.Dispose(); return data; }
internal static void Main(string[] args) { if (args.Length < 1) { System.Console.WriteLine(String.Format(CultureInfo.InvariantCulture, "Usage: SetFileModifiedDate \"FilePath\"")); return; } string filePath = args[0]; if (!File.Exists(filePath)) { System.Console.WriteLine("File: \"" + filePath + "\" doesn't exist!"); return; } FileAttributes attr = File.GetAttributes(filePath); if ((attr & FileAttributes.ReadOnly) > 0) { System.Console.WriteLine("File: \"" + filePath + "\" is readonly!"); return; } FileInfo fi = new FileInfo(filePath); fi.LastWriteTime = DateTime.Now.AddDays(-1); System.Console.WriteLine("Modified date is now set to: " + fi.LastWriteTime.ToString("ddMMMyyTHH:mm:ss fff")); }
public void Load() { // If configuration file exists then... if (System.IO.File.Exists(FileName)) { SettingsFile data; // Deserialize and load data. lock (saveReadFileLock) { data = Serializer.DeserializeFromXmlFile<SettingsFile>(FileName); } if (data == null) return; //Programs.Clear(); //if (data.Programs != null) for (int i = 0; i < data.Programs.Count; i++) Programs.Add(data.Programs[i]); Games.Clear(); if (data.Games != null) for (int i = 0; i < data.Games.Count; i++) Games.Add(data.Games[i]); Pads.Clear(); if (data.Pads != null) for (int i = 0; i < data.Pads.Count; i++) Pads.Add(data.Pads[i]); } // Check if current app doesn't exist in the list then... var currentFile = new System.IO.FileInfo(Application.ExecutablePath); var currentGame = Games.FirstOrDefault(x => x.FileName == currentFile.Name); if (currentGame == null) { // Add x360ce.exe var item = x360ce.Engine.Data.Game.FromDisk(currentFile.Name); var program = Programs.FirstOrDefault(x => x.FileName == currentFile.Name); item.LoadDefault(program); SettingsFile.Current.Games.Add(item); } else { currentGame.FullPath = currentFile.FullName; } }
/// <summary> /// Gets the file fingerprints from the application folder /// As the sha1 is calculated based on the content of the file, /// there is a possibility that one key can have multiple fingerprints (duplicate files) /// </summary> /// <param name="appPath">The path to the application folder</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>Return a dictionary of file fingerprints, with sha1 as key and a list of file fingerprints as value.</returns> public async Task<Dictionary<string, List<FileFingerprint>>> GetFileFingerprints(string appPath, System.Threading.CancellationToken cancellationToken) { Dictionary<string, List<FileFingerprint>> fingerprints = new Dictionary<string, List<FileFingerprint>>(); appPath = Path.GetFullPath(appPath); foreach (string file in Directory.GetFiles(appPath, "*", SearchOption.AllDirectories)) { FileInfo fileInfo = new FileInfo(file); FileFingerprint print = new FileFingerprint(); print.Size = fileInfo.Length; print.FileName = fileInfo.FullName.Replace(appPath, string.Empty).TrimStart('\\'); print.SHA1 = await this.CalculateSHA1(fileInfo.FullName, cancellationToken); if (fingerprints.ContainsKey(print.SHA1)) { fingerprints[print.SHA1].Add(print); } else { fingerprints.Add(print.SHA1, new List<FileFingerprint>() { print }); } } return fingerprints; }
// Add image generation logic here and return an instance of ImageInfo public override ImageInfo GenerateImage(NameValueCollection parameters) { SetupCulture(); //which type of image should be generated ? string mode = string.IsNullOrEmpty(parameters["mode"]) ? "profilepic" : parameters["mode"].ToLower(); // We need to determine the output format string format = string.IsNullOrEmpty(parameters["format"]) ? "jpg" : parameters["format"].ToLower(); // Lets retrieve the color Color color = string.IsNullOrEmpty(parameters["color"]) ? Color.White : (parameters["color"].StartsWith("#") ? ColorTranslator.FromHtml(parameters["color"]) : Color.FromName(parameters["color"])); Color backColor = string.IsNullOrEmpty(parameters["backcolor"]) ? Color.White : (parameters["backcolor"].StartsWith("#") ? ColorTranslator.FromHtml(parameters["backcolor"]) : Color.FromName(parameters["backcolor"])); // Do we have a border ? int border = string.IsNullOrEmpty(parameters["border"]) ? 0 : Convert.ToInt32(parameters["border"]); // Do we have a resizemode defined ? var resizeMode = string.IsNullOrEmpty(parameters["resizemode"]) ? ImageResizeMode.Fit : (ImageResizeMode)Enum.Parse(typeof(ImageResizeMode), parameters["ResizeMode"], true); // Maximum sizes int maxWidth = string.IsNullOrEmpty(parameters["MaxWidth"]) ? 0 : Convert.ToInt32(parameters["MaxWidth"]); int maxHeight = string.IsNullOrEmpty(parameters["MaxHeight"]) ? 0 : Convert.ToInt32(parameters["MaxHeight"]); // Any text ? string text = string.IsNullOrEmpty(parameters["text"]) ? "" : parameters["text"]; // Default Image _defaultImageFile = string.IsNullOrEmpty(parameters["NoImage"]) ? string.Empty : parameters["NoImage"]; // Do we override caching for this image ? if (!string.IsNullOrEmpty(parameters["NoCache"])) { EnableClientCache = false; EnableServerCache = false; } try { ContentType = GetImageFormat(format); switch (mode) { case "profilepic": int uid; if (!int.TryParse(parameters["userid"], out uid) || uid <= 0) { uid = -1; } var uppTrans = new UserProfilePicTransform { UserID = uid }; IFileInfo photoFile; ContentType = !uppTrans.TryGetPhotoFile(out photoFile) ? ImageFormat.Gif : GetImageFormat(photoFile?.Extension ?? "jpg"); ImageTransforms.Add(uppTrans); break; case "placeholder": var placeHolderTrans = new PlaceholderTransform(); int width, height; if (TryParseDimension(parameters["w"], out width)) { placeHolderTrans.Width = width; } if (TryParseDimension(parameters["h"], out height)) { placeHolderTrans.Height = height; } if (!string.IsNullOrEmpty(parameters["Color"])) { placeHolderTrans.Color = color; } if (!string.IsNullOrEmpty(parameters["Text"])) { placeHolderTrans.Text = text; } if (!string.IsNullOrEmpty(parameters["BackColor"])) { placeHolderTrans.BackColor = backColor; } ImageTransforms.Add(placeHolderTrans); break; case "securefile": var secureFileTrans = new SecureFileTransform(); if (!string.IsNullOrEmpty(parameters["FileId"])) { var fileId = Convert.ToInt32(parameters["FileId"]); var file = FileManager.Instance.GetFile(fileId); if (file == null) { return(GetEmptyImageInfo()); } var folder = FolderManager.Instance.GetFolder(file.FolderId); if (!secureFileTrans.DoesHaveReadFolderPermission(folder)) { return(GetEmptyImageInfo()); } ContentType = GetImageFormat(file.Extension); secureFileTrans.SecureFile = file; secureFileTrans.EmptyImage = EmptyImage; ImageTransforms.Add(secureFileTrans); } break; case "file": var imgFile = string.Empty; var imgUrl = string.Empty; // Lets determine the 2 types of Image Source: Single file, file url var filePath = parameters["File"]; if (!string.IsNullOrEmpty(filePath)) { filePath = filePath.Trim(); var fullFilePath = HttpContext.Current.Server.MapPath(filePath); if (!File.Exists(fullFilePath) || !IsAllowedFilePathImage(filePath)) { return(GetEmptyImageInfo()); } imgFile = fullFilePath; } else if (!string.IsNullOrEmpty(parameters["Url"])) { if (!parameters["Url"].StartsWith("http")) { return(GetEmptyImageInfo()); } imgUrl = parameters["Url"]; } if (string.IsNullOrEmpty(parameters["format"])) { string extension; if (string.IsNullOrEmpty(parameters["Url"])) { var fi = new System.IO.FileInfo(imgFile); extension = fi.Extension.ToLower(); } else { string[] parts = parameters["Url"].Split('.'); extension = parts[parts.Length - 1].ToLower(); } ContentType = GetImageFormat(extension); } var imageFileTrans = new ImageFileTransform { ImageFilePath = imgFile, ImageUrl = imgUrl }; ImageTransforms.Add(imageFileTrans); break; default: string imageTransformClass = ConfigurationManager.AppSettings["DnnImageHandler." + mode]; string[] imageTransformClassParts = imageTransformClass.Split(','); var asm = Assembly.LoadFrom(Globals.ApplicationMapPath + @"\bin\" + imageTransformClassParts[1].Trim() + ".dll"); var t = asm.GetType(imageTransformClassParts[0].Trim()); var imageTransform = (ImageTransform)Activator.CreateInstance(t); foreach (var key in parameters.AllKeys) { var pi = t.GetProperty(key, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); if (pi != null && key != "mode") { switch (key.ToLower()) { case "color": pi.SetValue(imageTransform, color, null); break; case "backcolor": pi.SetValue(imageTransform, backColor, null); break; case "border": pi.SetValue(imageTransform, border, null); break; default: switch (pi.PropertyType.Name) { case "Int32": pi.SetValue(imageTransform, Convert.ToInt32(parameters[key]), null); break; case "String": pi.SetValue(imageTransform, parameters[key], null); break; } break; } } } ImageTransforms.Add(imageTransform); break; } } catch (Exception ex) { Exceptions.Exceptions.LogException(ex); return(GetEmptyImageInfo()); } // Resize-Transformation if (mode != "placeholder") { int width, height; TryParseDimension(parameters["w"], out width); TryParseDimension(parameters["h"], out height); var size = string.IsNullOrEmpty(parameters["size"]) ? "" : parameters["size"]; switch (size) { case "xxs": width = 16; height = 16; break; case "xs": width = 32; height = 32; break; case "s": width = 50; height = 50; break; case "l": width = 64; height = 64; break; case "xl": width = 128; height = 128; break; case "xxl": width = 256; height = 256; break; } if (mode == "profilepic") { resizeMode = ImageResizeMode.FitSquare; if (width > 0 && height > 0 && width != height) { resizeMode = ImageResizeMode.Fill; } } if (width > 0 || height > 0) { var resizeTrans = new ImageResizeTransform { Mode = resizeMode, BackColor = backColor, Width = width, Height = height, MaxWidth = maxWidth, MaxHeight = maxHeight, Border = border }; ImageTransforms.Add(resizeTrans); } } // Gamma adjustment if (!string.IsNullOrEmpty(parameters["Gamma"])) { var gammaTrans = new ImageGammaTransform(); double gamma; if (double.TryParse(parameters["Gamma"], NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out gamma) && gamma >= 0.2 && gamma <= 5) { gammaTrans.Gamma = gamma; ImageTransforms.Add(gammaTrans); } } // Brightness adjustment if (!string.IsNullOrEmpty(parameters["Brightness"])) { var brightnessTrans = new ImageBrightnessTransform(); int brightness; if (int.TryParse(parameters["Brightness"], out brightness)) { brightnessTrans.Brightness = brightness; ImageTransforms.Add(brightnessTrans); } } // Contrast adjustment if (!string.IsNullOrEmpty(parameters["Contrast"])) { var contrastTrans = new ImageContrastTransform(); double contrast; if (double.TryParse(parameters["Contrast"], NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out contrast) && (contrast >= -100 && contrast <= 100)) { contrastTrans.Contrast = contrast; ImageTransforms.Add(contrastTrans); } } // Greyscale if (!string.IsNullOrEmpty(parameters["Greyscale"])) { var greyscaleTrans = new ImageGreyScaleTransform(); ImageTransforms.Add(greyscaleTrans); } // Invert if (!string.IsNullOrEmpty(parameters["Invert"])) { var invertTrans = new ImageInvertTransform(); ImageTransforms.Add(invertTrans); } // Rotate / Flip if (!string.IsNullOrEmpty(parameters["RotateFlip"])) { var rotateFlipTrans = new ImageRotateFlipTransform(); var rotateFlipType = (RotateFlipType)Enum.Parse(typeof(RotateFlipType), parameters["RotateFlip"]); rotateFlipTrans.RotateFlip = rotateFlipType; ImageTransforms.Add(rotateFlipTrans); } // We start the chain with an empty image var dummy = new Bitmap(1, 1); using (var ms = new MemoryStream()) { dummy.Save(ms, ContentType); return(new ImageInfo(ms.ToArray())); } }
private void SetViewImage(System.IO.FileInfo fi, string requestedName) { if (fi != null) { lblInternalName.Text = ""; lblInternalReference.Text = ""; string varname = ""; fileType ft = LoadFile(fi, requestedName, out varname, out currentBitmap); pictureBox1.Image = currentBitmap; switch (ft) { case fileType.Image: Viewer1.Visible = false; Viewer1.Dock = DockStyle.None; lstInternalImages.Visible = false; lstInternalImages.Dock = DockStyle.None; txtBinaryHeader.Dock = DockStyle.Fill; txtBinaryHeader.Visible = true; pbPreviewImage.Dock = DockStyle.Fill; pbPreviewImage.Visible = true; WriteImageFileInfo(); break; case fileType.TextMdl: Viewer1.Visible = false; Viewer1.Dock = DockStyle.None; txtBinaryHeader.Visible = false; txtBinaryHeader.Dock = DockStyle.None; lstInternalImages.Dock = DockStyle.Fill; lstInternalImages.Visible = true; pbPreviewImage.Dock = DockStyle.Fill; pbPreviewImage.Visible = true; // deteremine if we need to reload the list. WriteTextFileInfo(varname); break; case fileType.ImageMdl: Viewer1.Visible = false; Viewer1.Dock = DockStyle.None; lstInternalImages.Visible = false; lstInternalImages.Dock = DockStyle.None; txtBinaryHeader.Dock = DockStyle.Fill; txtBinaryHeader.Visible = true; pbPreviewImage.Dock = DockStyle.Fill; pbPreviewImage.Visible = true; WriteBinaryFileInfo(currentBinaryMDL.header.ImportedSymbols[0].Name); break; case fileType.ModelMdl: pbPreviewImage.Visible = false; pbPreviewImage.Dock = DockStyle.None; lstInternalImages.Visible = false; lstInternalImages.Dock = DockStyle.None; WriteBinaryFileInfo(currentBinaryMDL.header.NameSpaces[0]); if (currentBinaryMDL.RootObject.Where(x => x.type == MDLType.mdl_mesh).Count() > 0) { // Lets load up any referenced Images Namespaces List <Bitmap> referencedImages = GetReferencedImages(currentBinaryMDL); // Lets send our file to the 3DViewer!! MDLViewer mv = Viewer1.Child as MDLViewer; mv.LoadMDLFile(currentBinaryMDL, referencedImages); } txtBinaryHeader.Dock = DockStyle.Fill; txtBinaryHeader.Visible = true; Viewer1.Dock = DockStyle.Fill; Viewer1.Visible = true; break; default: break; } if (currentBitmap != null) { if (ft != fileType.ModelMdl) { lblDetails.Text = string.Format("w:{0} h:{1} {2}", currentBitmap.Width, currentBitmap.Height, currentBitmap.PixelFormat.ToString()); // fill info on the details tab. lblFormat.Text = "Pixel: " + currentBitmap.PixelFormat.ToString(); lblWidth.Text = "Width: " + currentBitmap.Width.ToString(); lblHeight.Text = "Height: " + currentBitmap.Height.ToString(); if (numericUpDown1.Value == 100 || Properties.Settings.Default.RememberZoom == false) { pictureBox1.Width = pictureBox1.Image.Width; pictureBox1.Height = pictureBox1.Image.Height; numericUpDown1.Value = 100; } else { pictureBox1.Image = Scale(currentBitmap, Convert.ToSingle(numericUpDown1.Value) / 100, Convert.ToSingle(numericUpDown1.Value) / 100); pictureBox1.Width = pictureBox1.Image.Width; pictureBox1.Height = pictureBox1.Image.Height; } pbPreviewImage.Image = pictureBox1.Image; } } else { lblDetails.Text = "No Images Found"; // fill info on the details tab. lblFormat.Text = "Pixel: "; lblWidth.Text = "Width: "; lblHeight.Text = "Height: "; lstInternalImages.Items.Clear(); pictureBox1.Image = null; pbPreviewImage.Image = null; } this.Text = windowTitle + " .. " + currentFile.Name; // the status label lblFileName.Text = "File Name: " + currentFile.Name; } }
public virtual string ToHTML(string htmlFileName = "", int count = 0, bool includeImage = true, bool includeFullData = false, bool ForWeb = false) { StringBuilder htmlBuilder = new StringBuilder(); StringBuilder _color = new StringBuilder(); StringBuilder _Groups = new StringBuilder(); string Composition = ""; if (!ForWeb) { string imageFileName = string.Empty; if (htmlFileName.EndsWith(".html")) { imageFileName = htmlFileName.Remove(htmlFileName.Length - 5, 5); } else if (htmlFileName.EndsWith(".htm")) { imageFileName = htmlFileName.Remove(htmlFileName.Length - 4, 4); } imageFileName = imageFileName + "_" + count.ToString() + ".png"; System.IO.FileInfo fi = new System.IO.FileInfo(imageFileName); ToImageFile(imageFileName, false); htmlBuilder.AppendLine("<h3>" + this.StrataTitle + "</h3>"); if (includeImage) { htmlBuilder.AppendLine("<img src=\"" + fi.Name + "\" />"); } htmlBuilder.AppendLine("<p> </p>"); htmlBuilder.AppendLine("<p> </p>"); htmlBuilder.AppendLine("<p> </p>"); } else { List <string> color = new List <string>(); var ChartType = this.GetType().Name; if (ChartType == "LineChart") { htmlBuilder.AppendLine("<h2 class=\"gadgetHeading\">" + ((EpiDashboard.Controls.Charting.LineChartBase) this).LineChartParameters.GadgetTitle + "</h2>"); color = ((EpiDashboard.Controls.Charting.LineChartBase) this).LineChartParameters.PaletteColors; } else if (ChartType == "ParetoChart") { htmlBuilder.AppendLine("<h2 class=\"gadgetHeading\">" + ((EpiDashboard.Controls.Charting.ParetoChart) this).ParetoChartParameters.GadgetTitle + "</h2>"); color = ((EpiDashboard.Controls.Charting.ParetoChart) this).ParetoChartParameters.PaletteColors; } else if (ChartType == "ColumnChart") { htmlBuilder.AppendLine("<h2 class=\"gadgetHeading\">" + ((EpiDashboard.Controls.Charting.ColumnChartBase) this).ColumnChartParameters.GadgetTitle + "</h2>"); color = ((EpiDashboard.Controls.Charting.ColumnChartBase) this).ColumnChartParameters.PaletteColors; Composition = ((EpiDashboard.Controls.Charting.ColumnChartBase) this).ColumnChartParameters.Composition.ToString(); bool UseDiffColors = ((EpiDashboard.Controls.Charting.ColumnChartBase) this).ColumnChartParameters.UseDiffColors; if (UseDiffColors) { _color.AppendLine(" var colors = ["); for (int i = 0; i < color.Count(); i++) { if (color[i].Length == 9) { _color.AppendLine(" '" + color[i].Remove(1, 2) + "' ,"); } } _color.AppendLine(" ];"); } } else if (ChartType == "AreaChart") { htmlBuilder.AppendLine("<h2 class=\"gadgetHeading\">" + ((EpiDashboard.Controls.Charting.AreaChartBase) this).AreaChartParameters.GadgetTitle + "</h2>"); color = ((EpiDashboard.Controls.Charting.AreaChartBase) this).AreaChartParameters.PaletteColors; } else if (ChartType == "HistogramChart") { color = ((EpiDashboard.Controls.Charting.HistogramChartBase) this).HistogramChartParameters.PaletteColors; htmlBuilder.AppendLine("<h2 class=\"gadgetHeading\">" + ((EpiDashboard.Controls.Charting.HistogramChartBase) this).HistogramChartParameters.GadgetTitle + "</h2>"); } htmlBuilder.AppendLine("<div id=\"Linechart" + count + "\" style=\"float:left\"></div>"); if (!string.IsNullOrEmpty(_color.ToString())) { htmlBuilder.AppendLine("<script> " + _color.ToString()); } else { htmlBuilder.AppendLine("<script> "); } htmlBuilder.AppendLine(" var Linechart" + count + " = c3.generate({bindto: '#Linechart" + count + "',data: { columns: ["); try{ try { if (ChartType == "HistogramChart") { List <EpiDashboard.Controls.Charting.HistogramChart.XYHistogramChartData> _HChartdataList = (List <EpiDashboard.Controls.Charting.HistogramChart.XYHistogramChartData>) this.Chart.DataSource; var HChartGroups = _HChartdataList.GroupBy(x => x.X); foreach (var DataItem in HChartGroups) { htmlBuilder.AppendLine("['" + DataItem.ToList()[0].X + "', "); _Groups.AppendLine("'" + DataItem.ToList()[0].X + "', "); foreach (var item in DataItem) { htmlBuilder.AppendLine(item.Y + ", "); } htmlBuilder.AppendLine("],"); } htmlBuilder.AppendLine("]"); } else if (ChartType == "ParetoChart") { List <EpiDashboard.Gadgets.Charting.XYParetoChartData> _ParetoChartList = (List <EpiDashboard.Gadgets.Charting.XYParetoChartData>) this.Chart.DataSource; var ParetoChartList = _ParetoChartList.GroupBy(x => x.X); htmlBuilder.AppendLine("['Percentage', "); foreach (var DataItem in ParetoChartList) { foreach (var item in DataItem) { htmlBuilder.AppendLine(item.Z + ", "); } } htmlBuilder.AppendLine("],"); htmlBuilder.AppendLine("['Count', "); foreach (var DataItem in ParetoChartList) { foreach (var item in DataItem) { htmlBuilder.AppendLine(item.Y + ", "); } } htmlBuilder.AppendLine("]"); htmlBuilder.AppendLine("]"); } else { List <EpiDashboard.Gadgets.Charting.XYColumnChartData> _dataList = (List <EpiDashboard.Gadgets.Charting.XYColumnChartData>) this.Chart.DataSource; var Groups = _dataList.GroupBy(x => x.X); foreach (var DataItem in Groups) { htmlBuilder.AppendLine("['" + DataItem.ToList()[0].X + "', "); _Groups.AppendLine("'" + DataItem.ToList()[0].X + "', "); foreach (var item in DataItem) { htmlBuilder.AppendLine(item.Y + ", "); } htmlBuilder.AppendLine("],"); } htmlBuilder.AppendLine("]"); } if (ChartType == "LineChart") { htmlBuilder.AppendLine(" , type : 'line' }, legend: { show: true }, size: { width: " + this.ActualWidth + ", height: " + this.ActualHeight + " },"); } else if (ChartType == "ColumnChart") { bool UseDiffColors = ((EpiDashboard.Controls.Charting.ColumnChartBase) this).ColumnChartParameters.UseDiffColors; if (UseDiffColors) { htmlBuilder.AppendLine(" , type : 'bar' ,color: function (color, d) { return colors[d.index];} }, legend: { show: true }, size: { width: " + this.ActualWidth + ", height: " + this.ActualHeight + " },bar: {width: {ratio: .8}},"); } else { htmlBuilder.AppendLine(" , type : 'bar' }, legend: { show: true }, size: { width: " + this.ActualWidth + ", height: " + this.ActualHeight + " },bar: {width: {ratio: .8}},"); } } else if (ChartType == "ParetoChart") { htmlBuilder.AppendLine(" , type : 'bar' ,axes: { Percentage: 'y2'},types: {Percentage: 'line'} }, legend: { show: true }, size: { width: " + this.ActualWidth + ", height: " + this.ActualHeight + " },"); } else if (ChartType == "AreaChart") { htmlBuilder.AppendLine(" , type : 'area' }, legend: { show: true }, size: { width: " + this.ActualWidth + ", height: " + this.ActualHeight + " },"); } else if (ChartType == "HistogramChart") { htmlBuilder.AppendLine(" , type : 'bar' }, legend: { show: true }, size: { width: " + this.ActualWidth + ", height: " + this.ActualHeight + " }, bar: {width: {ratio: .8}},"); } if (ChartType == "HistogramChart") { List <EpiDashboard.Controls.Charting.HistogramChart.XYHistogramChartData> _HChartdataList = (List <EpiDashboard.Controls.Charting.HistogramChart.XYHistogramChartData>) this.Chart.DataSource; HistogramChartParameters HistogramChartParameters = new HistogramChartParameters(); // (List<EpiDashboard.Controls.Charting.HistogramChart.XYHistogramChartData>)this.Parameters.Parameters = new HistogramChartParameters(); //this.Parameters = new HistogramChartParameters(); EpiDashboard.Controls.Charting.HistogramChart _HCharList = (EpiDashboard.Controls.Charting.HistogramChart) this; if (color.Count() > 0) { htmlBuilder.AppendLine(" color: { pattern: ["); for (int i = 0; i < color.Count(); i++) { if (color[i].Length == 9) { htmlBuilder.AppendLine(" '" + color[i].Remove(1, 2) + "' ,"); } } htmlBuilder.AppendLine(" ]},"); } // htmlBuilder.AppendLine("axis: { x : {type: 'timeseries', tick: { format: '%m/%d/%Y', rotate: 90, multiline: false}}}"); htmlBuilder.AppendLine("axis: { x : {type: 'category' ,tick: { rotate: 90, multiline: false} , categories: ["); foreach (var item in _HChartdataList) { htmlBuilder.AppendLine("'" + item.S + "', "); } } else if (ChartType == "ParetoChart") { List <EpiDashboard.Gadgets.Charting.XYParetoChartData> _dataList = (List <EpiDashboard.Gadgets.Charting.XYParetoChartData>) this.Chart.DataSource; htmlBuilder.AppendLine(" color: { pattern: ["); for (int i = 0; i < color.Count(); i++) { if (color[i].Length == 9) { htmlBuilder.AppendLine(" '" + color[i].Remove(1, 2) + "' ,"); } } htmlBuilder.AppendLine(" ]},"); htmlBuilder.AppendLine("axis: { x : { label:{ text:'" + ((EpiDashboard.Controls.Charting.ParetoChart) this).ParetoChartParameters.XAxisLabel + "' , position: 'outer-center'}, type: 'category' , categories: ["); foreach (var item in _dataList) { htmlBuilder.AppendLine("'" + item.X + "', "); } } else { List <EpiDashboard.Gadgets.Charting.XYColumnChartData> _dataList = (List <EpiDashboard.Gadgets.Charting.XYColumnChartData>) this.Chart.DataSource; htmlBuilder.AppendLine(" color: { pattern: ["); for (int i = 0; i < color.Count(); i++) { if (color[i].Length == 9) { htmlBuilder.AppendLine(" '" + color[i].Remove(1, 2) + "' ,"); } } htmlBuilder.AppendLine(" ]},"); htmlBuilder.AppendLine("axis: { x : {show:false,type: 'category' , categories: ["); foreach (var item in _dataList) { htmlBuilder.AppendLine("'" + item.S + "', "); } } htmlBuilder.AppendLine("]}"); if (ChartType == "LineChart") { htmlBuilder.AppendLine(" , y: { label: { text:'" + ((EpiDashboard.Controls.Charting.LineChartBase) this).LineChartParameters.YAxisLabel + "' , position: 'outer-middle'}}"); } else if (ChartType == "ColumnChart") { htmlBuilder.AppendLine(", y: { label: { text: '" + ((EpiDashboard.Controls.Charting.ColumnChartBase) this).ColumnChartParameters.YAxisLabel + "', position: 'outer-middle'}}"); } else if (ChartType == "AreaChart") { htmlBuilder.AppendLine(", y: { label: { text:'" + ((EpiDashboard.Controls.Charting.AreaChartBase) this).AreaChartParameters.YAxisLabel + "', position: 'outer-middle'}}"); } else if (ChartType == "ParetoChart") { htmlBuilder.AppendLine(", y: { label:{ text:'" + ((EpiDashboard.Controls.Charting.ParetoChart) this).ParetoChartParameters.YAxisLabel + "' , position: 'outer-middle'}},y2: {show: true,label: {text: 'Percentage',position: 'outer-middle'},tick:{format:d3.format('100.0%')} }"); } // tick: { format: '%m/%d/%Y', rotate: 90, multiline: false} // htmlBuilder.AppendLine(",tick: { x:{ multiline:true, culling: { max: 1 }, }, label : { text: 'Days', position: 'center-bottom', }, },"); // htmlBuilder.AppendLine(",tick: { format: '%m/%d/%Y', rotate: 90, multiline: false},"); htmlBuilder.AppendLine("}}); "); if (!string.IsNullOrEmpty(_Groups.ToString()) && Composition == "Stacked") { htmlBuilder.AppendLine("setTimeout(function() { Linechart" + count + ".groups([[" + _Groups + "]])}, 000);"); } htmlBuilder.AppendLine("</script> "); } catch (Exception ex) { //var _dataList = this.Chart.DataSource; // if (ChartType == "HistogramChart") // { // List<EpiDashboard.Controls.Charting.HistogramChart.XYHistogramChartData> _dataList = (List<EpiDashboard.Controls.Charting.HistogramChart.XYHistogramChartData>)this.Chart.DataSource; // htmlBuilder.AppendLine("<h2 class=\"gadgetHeading\">" + this.ChartTitle + "</h2>"); // htmlBuilder.AppendLine("<div id=\"piechart" + count + "\"></div>"); // htmlBuilder.AppendLine("<script>"); // htmlBuilder.AppendLine(" var piechart" + count + " = c3.generate({bindto: '#piechart" + count + "',data: { columns: ["); // var temp = _dataList; // foreach (var item in _dataList) // { // htmlBuilder.AppendLine("['" + item.S + "', " + item.Y + "], "); // } // //string colorString = ""; // htmlBuilder.AppendLine(" ], type : 'bar' },"); // htmlBuilder.AppendLine(" color: { pattern: ["); // if (color.Count() > 0) // { // for (int i = 0; i < _dataList.Count(); i++) // { // htmlBuilder.AppendLine(" '" + color[i].Remove(1,2) + "' ,"); // } // } // htmlBuilder.AppendLine(" ]},"); // htmlBuilder.AppendLine(" legend: { show: true , position: top }, size: { width: " + this.ActualWidth + ", height: " + this.ActualHeight + " },label: { format: function(value, ratio, id){return d3.format('$')(value);}}});"); // htmlBuilder.AppendLine(" </script> "); // } } } catch (Exception ex) { throw ex; } } return(htmlBuilder.ToString()); }
private void ActualizarePoze() { imagini.Clear(); listaFisiere.Clear(); Alignment Ax = comboBoxAx.SelectedItem as Alignment; if (Ax == null) { WF.MessageBox.Show((string)comboBoxAx.SelectedItem); } var fisiere = from string fisier in IO.Directory.GetFiles(textBoxDir.Text, "*.*", IO.SearchOption.AllDirectories) where ".jpg.bmp.png.gif.jpeg.tiff".Contains(new IO.FileInfo(fisier).Extension.ToLower()) orderby fisier select fisier; if (fisiere.Count() == 0) { WF.MessageBox.Show("Directorul nu contine imagini!"); return; } else { listaFisiere.AddRange(fisiere); } double lungimeAx = Ax.EndingStation - Ax.StartingStation; if (imaginiCheie.Count == 0) { imaginiCheie.Add((int)(Ax.StartingStation * 1000), fisiere.First()); imaginiCheie.Add((int)(Ax.EndingStation * 1000), fisiere.Last()); //double interval = (Ax.EndingStation - Ax.StartingStation) / (fisiere.Count() - 1); //for (int i = 0; i < fisiere.Count(); i++) //{ // double km = i * interval; // //WF.MessageBox.Show(string.Format("Lungime ax: {0}\nInterval intre poze: {1}\nPozitia curenta:{2}", lungimeAx, interval, km)); //Raport individual imagini // imagini.Add((int)(km * 1000), fisiere.ElementAt(i)); //} } else if (imaginiCheie.Count == 1) { if (imaginiCheie.First().Key < (int)(Ax.EndingStation * 1000)) { imaginiCheie.Add((int)(Ax.EndingStation * 1000), fisiere.Last()); } else { imaginiCheie.Add((int)(Ax.StartingStation * 1000), fisiere.First()); } } for (int j = 1; j < imaginiCheie.Count; j++) { double interval = (double)(imaginiCheie.ElementAt(j).Key - imaginiCheie.ElementAt(j - 1).Key) / (listaFisiere.IndexOf(imaginiCheie.ElementAt(j).Value) - listaFisiere.IndexOf(imaginiCheie.ElementAt(j - 1).Value) - 0); if (j == 1 && listaFisiere.IndexOf(imaginiCheie.ElementAt(j - 1).Value) > 0) { for (int nr = 1; nr < listaFisiere.IndexOf(imaginiCheie.ElementAt(j - 1).Value) - 1; nr++) { int index = listaFisiere.IndexOf(imaginiCheie.ElementAt(j - 1).Value) - nr; imagini.Add((int)(imaginiCheie.ElementAt(j - 1).Key - nr * interval), listaFisiere[index]); } } for (int nr = 0; nr <= (listaFisiere.IndexOf(imaginiCheie.ElementAt(j).Value) - listaFisiere.IndexOf(imaginiCheie.ElementAt(j - 1).Value) - 0); nr++) { int index = listaFisiere.IndexOf(imaginiCheie.ElementAt(j - 1).Value) + nr; int cheie = (int)(imaginiCheie.ElementAt(j - 1).Key + nr * interval); if (!imagini.Keys.Contains(cheie)) { imagini.Add((int)(imaginiCheie.ElementAt(j - 1).Key + nr * interval), listaFisiere[index]); } } if (j == imaginiCheie.Count - 1 && listaFisiere.IndexOf(imaginiCheie.ElementAt(j).Value) < listaFisiere.Count - 1) { for (int nr = 1; nr < listaFisiere.Count - listaFisiere.IndexOf(imaginiCheie.ElementAt(j).Value) - 0; nr++) { int index = listaFisiere.IndexOf(imaginiCheie.ElementAt(j).Value) + nr; imagini.Add((int)(imaginiCheie.ElementAt(j).Key + nr * interval), listaFisiere[index]); } } } //Scriere rezultat calibrare IO.FileInfo calibrare = new IO.FileInfo(textBoxDir.Text + @"\CALIBRARE.TXT"); using (IO.StreamWriter SR = calibrare.CreateText()) { foreach (int cheie in imagini.Keys) { string fix = string.Empty; if (imaginiCheie.Keys.Contains(cheie)) { fix = "********"; } SR.WriteLine(string.Format("Km: {0} -> {1}{2}", cheie, imagini[cheie], fix)); } } //WF.Binding Bind = new WF.Binding("Value", imagini, "Keys"); //trackBar1.DataBindings.Add(Bind); // trackBar1.Minimum = (int)(Ax.StartingStation * 1000); //trackBar1.Maximum = (int)(Ax.EndingStation * 1000) + 1000; trackBar1.Minimum = imagini.ElementAt(0).Key; trackBar1.Maximum = imagini.Last().Key; trackBar1.Value = trackBar1.Minimum; trackBar1.SmallChange = 5000; try { trackBar1.LargeChange = int.Parse(textBoxInterval.Text) * 1000; } catch { trackBar1.LargeChange = trackBar1.SmallChange * 5; } //trackBar1.SmallChange = (int)(interval * 1000); trackBar1.LargeChange = int.Parse(textBoxInterval.Text) * 1000; //trackBar1.LargeChange = trackBar1.SmallChange * 5; trackBar1.TickFrequency = trackBar1.SmallChange; trackBar1.TickStyle = System.Windows.Forms.TickStyle.BottomRight; textBoxKm.Leave += TextBoxKm_Leave; textBoxKm.KeyPress += TextBoxKm_KeyPress; textBoxSalt.KeyPress += TextBoxSalt_KeyPress; AfisarePoza(); }
static void Main(string[] args) { try { string startPath; string INIfolderPath; string INIfilePath; INIfolderPath = System.IO.Directory.GetCurrentDirectory(); INIfolderPath = INIfolderPath + "\\data.ini"; string zipPath; string fileNames = ""; string extractPath; string s = ""; string dt = DateTime.Now.ToShortDateString(); dt = dt.Replace(".", "_"); dt = dt.Replace(":", "_"); using (StreamReader sr = File.OpenText(INIfolderPath)) { //ini data file //1st line: source log files folder s = sr.ReadLine(); var rx = new System.Text.RegularExpressions.Regex(";"); var array = rx.Split(s); //if we have several log folders if (array.Length > 1) { for (int i = 0; i < array.Length; i++) { startPath = array[i]; fileNames = Environment.NewLine + fileNames + Environment.NewLine; zipPath = startPath + "\\" + "archive_" + dt + "_" + i + ".zip"; fileNames = fileNames + zipPath + ":" + Environment.NewLine; s = sr.ReadLine(); extractPath = s; string newFile; using (ZipArchive archive = ZipFile.Open(zipPath, ZipArchiveMode.Update)) { //archive.CreateEntryFromFile(newFile, "NewEntry.txt"); } DateTime TodayDate = DateTime.Now; DateTime WeekAgo = TodayDate.AddDays(-7); foreach (string file in Directory.EnumerateFiles(startPath, "*.*")) { newFile = file; using (ZipArchive archive = ZipFile.Open(zipPath, ZipArchiveMode.Update)) { string fileName = file.ToString().TrimEnd(); string result; result = Path.GetFileName(fileName); DateTime fileCreatedDate = File.GetLastWriteTime(fileName); if (fileCreatedDate < WeekAgo) { long length = new System.IO.FileInfo(file).Length; if (length < 300000000) { archive.CreateEntryFromFile(newFile, result); File.Delete(file); fileNames = fileNames + Environment.NewLine + file + "; "; } } } } } } else { startPath = array[0]; s = sr.ReadLine(); //3rd line: zip file zipPath = startPath + "\\" + "archive_" + dt + ".zip"; fileNames = Environment.NewLine + fileNames + zipPath + ":" + Environment.NewLine; s = sr.ReadLine(); extractPath = s; string newFile; using (ZipArchive archive = ZipFile.Open(zipPath, ZipArchiveMode.Update)) { //archive.CreateEntryFromFile(newFile, "NewEntry.txt"); } DateTime TodayDate = DateTime.Now; DateTime WeekAgo = TodayDate.AddDays(-7); foreach (string file in Directory.EnumerateFiles(startPath, "*.*")) { newFile = file; //if (Directory.Exists("FOLDER_PATH")) //{ // var directory = new DirectoryInfo("FOLDER_PATH"); // foreach (FileInfo file1 in directory.GetFiles()) // { // if (!IsFileLocked(file1)) file1.Delete(); // } //} using (ZipArchive archive = ZipFile.Open(zipPath, ZipArchiveMode.Update)) { string fileName = file.ToString().TrimEnd(); string result; result = Path.GetFileName(fileName); DateTime fileCreatedDate = File.GetLastWriteTime(fileName); //string str = null; //string retString = null; //retString = fileName.Substring(fileName.Length - startPath.Length-2); //retString = str.Substring(0, 3); if (fileCreatedDate < WeekAgo) { var directory = new DirectoryInfo(startPath); // foreach (FileInfo file1 in directory.GetFiles()) { //if (!IsFileLocked(file1) //&& (result ==file1.ToString())) //file1.Delete(); { long length = new System.IO.FileInfo(file).Length; if (length < 300000000) { archive.CreateEntryFromFile(newFile, result); File.Delete(file); fileNames = fileNames + Environment.NewLine + file + "; "; } } } } } } } } SendEmail("Server:" + Environment.MachineName + " " + (char)13 + (char)10 + fileNames); } catch (IOException e) { // Extract some information from this exception, and then // throw it to the parent method. if (e.Source != null) { Console.WriteLine("IOException source: {0}", e.Source); } throw; } }
//------------------------------------------------------------ // CSConsoleArgs.wcstoul64 //------------------------------------------------------------ // to \Utilities //------------------------------------------------------------ // CSConsoleArgs.ExamineNoConfigOption // /// <summary> /// <para>(ConsoleArgs::ProcessAutoConfig in sscli)</para> /// <para>Process '/noconfig', and CSC.CFG, modifying the argument list</para> /// <para>Process Auto Config options: /// #1 search for '/noconfig' /// if not present and csc.cfg exists in EXE dir, inject after env var stuff</para> /// <para>/noconfig が指定されていなければ、 /// csc.rsp ファイルの内容をオプションリストに追加する。</para> /// </summary> //------------------------------------------------------------ private void ExamineNoConfigOption() { this.NoConfig = false; //-------------------------------------------------- // Scan the argument list for the "/noconfig" options. If present, just kill it and bail. // /noconfig または -noconfig が指定されていれば foundNoConfig に true をセットする。 //-------------------------------------------------- for (int i = 0; i < this.OptionList.Count; ++i) { string[] opt = this.OptionList[i]; // Skip everything except options if ((opt.Length < 3 || opt[1] != "/")) { continue; } if (String.Compare(opt[2], "noconfig", true) == 0) { this.NoConfig = true; // /noconfig オプションは引数リストから削除する。 // 複数回指定されている可能性もあるので break しない。 this.OptionList[i] = null; } } // /noconfig が指定されている場合は終了する。 if (this.NoConfig) { return; } //-------------------------------------------------- // 指定されていない場合は csc.rsp をレスポンスファイルとしてオプションに追加する。 // まずこのアセンブリと同じディレクトリに csc.rsp があるか調べる。 //-------------------------------------------------- string rspFullName = null; System.IO.FileInfo finfo = null; Exception excp = null; try { rspFullName = Path.Combine( Path.GetDirectoryName(Assembly.GetAssembly(typeof(Util)).Location), @"csc.rsp"); } catch (ArgumentException ex) { this.Controller.ReportError(ERRORKIND.ERROR, ex); return; } catch (PathTooLongException ex) { this.Controller.ReportError(ERRORKIND.ERROR, ex); return; } if (!IOUtil.CreateFileInfo(rspFullName, out finfo, out excp) || finfo == null) { if (excp != null) { this.Controller.ReportError(ERRORKIND.ERROR, excp); } else { this.Controller.ReportInternalCompilerError("ExamineNoConfigOption"); } return; } if (!finfo.Exists) { // In this project, mscorlib.dll and system.dll are always imported. // So, it is not an error that csc.rsp is not found. this.Controller.WriteLine("no csc.rsp"); return; } // If cannot open csc.rsp, show warning. if ((finfo.Attributes & ( System.IO.FileAttributes.Compressed | System.IO.FileAttributes.Directory | System.IO.FileAttributes.Encrypted)) != 0) { this.Controller.ReportError(ERRORKIND.WARNING, "csc.rsp could not be opened."); return; } //-------------------------------------------------- // この時点では実際に csc.rsp が存在し読み取り可能である。 // 先頭に @ をつけてオプションリストの先頭に追加する。 //-------------------------------------------------- this.OptionList.Insert(0, new string[3] { "@" + rspFullName, "@", rspFullName }); }
public static bool CheckIfFileIsReadOnly(string filePath) { System.IO.FileInfo fi = new System.IO.FileInfo(filePath); return(fi.Attributes == System.IO.FileAttributes.ReadOnly); }
static void Main(string[] args) { Console.WriteLine("Starting video drop..."); // TODO: Make fileList -> argList and then make fileList a List(Of FileInfo), that way other parameters can be passed // from the command line List <string> fileList = new List <string>(args); bool noArchive = false; WriteInfo(GetMethodName(), "Video files to convert:", DEBUGLEVEL.INFO); if (fileList.Count == 0) { fileList = new List <string>() { "test.mp4" }; //, "hevc_test.mp4" }; //noArchive = true; } string startTag = "StartTag"; string middleTag = "MiddleTag"; string endTag = "EndTag"; var line = "<" + startTag + "> --colormatrix bt709 --range pc --input - range pc <" + middleTag + "^ --seek 2500 --frames 300 <" + endTag + ">"; var tagList = VideoDropSettings.GetTags(line, new string[] { "<", ">" }); INIReader.iniPath = DirectoryToString(Directory.GetCurrentDirectory()) + "VideoDrop.ini"; Dictionary <string, string> newSettings = ReadINI(); VideoDropSettings vdSettings = new VideoDropSettings(ref newSettings); vdSettings.SetDebugLevel(); WriteInfo("ConsoleUI", "Settings List:", DEBUGLEVEL.DEBUG); foreach (string key in vdSettings.GlobalSettings.Keys) { WriteInfo(" ConsoleUI", "Key: " + key + "=" + vdSettings.GlobalSettings[key], DEBUGLEVEL.DEBUG); } List <string> activeProfiles = vdSettings.ActiveProfiles; int totalVideos = activeProfiles.Count * fileList.Count; int numFinished = 0; int numFailed = 0; // Setup_Encoder() VideoDropJob vjob = null; /* TODO: Change to default(_) if this is not a reference type */ foreach (var arg in fileList) { bool successful = true; Console.WriteLine(" Current file: " + arg); foreach (var profile in activeProfiles) { // Generate AVS and set paths FileInfo file = new System.IO.FileInfo(arg); Console.WriteLine(" Starting video #" + (numFinished + 1) + " of " + totalVideos); vjob = new VideoDropJob(arg, vdSettings, profile); Console.WriteLine(" Using profile: " + vjob.ActiveProfile); vjob.GeneratePaths(); vjob.PrintPaths(); if (!vjob.Run()) { successful = false; numFailed += 1; } numFinished += 1; } // Done with all jobs for this video, archive it if (successful && !noArchive) { vjob.ArchiveSource(); } } Console.WriteLine("Finished..."); if (numFailed > 0) { Console.WriteLine(" Failed " + numFailed + " jobs."); } Console.Read(); }
void handleFile(string fullPath) { try { // In case this is data-url download, at least Chrome will not rename file, but instead write to it // directly. This mean we may catch it in the act. Let's leave it some time to finish writing. Thread.Sleep(500); var info = new System.IO.FileInfo(fullPath); Trace.WriteLine("download: " + info.FullName); if (info.Extension != ".hex") { return; } var infoName = info.Name; Trace.WriteLine("download name: " + info.Name); if (!infoName.StartsWith("microbit-", StringComparison.OrdinalIgnoreCase)) { return; } if (info.Name.EndsWith(".uploaded.hex", StringComparison.OrdinalIgnoreCase)) { return; } if (info.Length > 1000000) { return; // make sure we don't try to copy large files } // already copying? if (Interlocked.Exchange(ref this.copying, 1) == 1) { return; } try { var driveletters = getMicrobitDrives(); List <String> drives = new List <String>(); foreach (var d in driveletters) { drives.Add(d.RootDirectory.FullName); } if (!String.IsNullOrEmpty(customcopypath) && Directory.Exists(customcopypath)) { drives.Add(customcopypath); } if (drives.Count == 0) { this.updateStatus("no board found"); this.trayIcon.ShowBalloonTip(3000, "cancelled uploading...", "no board found", ToolTipIcon.None); return; } this.updateStatus("uploading .hex file"); this.trayIcon.ShowBalloonTip(3000, "uploading...", "uploading .hex file", ToolTipIcon.None); // copy to all boards copyFirmware(info.FullName, drives); // move away hex file var temp = System.IO.Path.ChangeExtension(info.FullName, ".uploaded.hex"); try { File.Copy(info.FullName, temp, true); File.Delete(info.FullName); } catch (IOException) { } catch (NotSupportedException) { } catch (UnauthorizedAccessException) { } catch (ArgumentException) { } // update ui this.updateStatus("uploading done"); this.waitingForHexFileStatus(); } finally { Interlocked.Exchange(ref this.copying, 0); } } catch (IOException) { } catch (NotSupportedException) { } catch (UnauthorizedAccessException) { } catch (ArgumentException) { } }
private void LoadToMfiles(string nameOrTitle, string documentDate, string ferretDocumentClass, string accountNumber, string clientName, string description, string extension, int docID, string filepath) { #region // Which vault are we connecting to? var vaultGuid = ((VaultComboBoxItem)vaultComboBox.SelectedItem).VaultGUID;//"{C840BE1A-5B47-4AC0-8EF7-835C166C8E24}"; // Connect to the vault using a client connection. // ref: http://developer.m-files.com/APIs/COM-API/#api-modes-client-vs-server // Note: this code will just return the first connection to the vault. var clientApplication = new MFilesClientApplication(); var vault = clientApplication .GetVaultConnectionsWithGUID(vaultGuid) .Cast <VaultConnection>() .FirstOrDefault()? .BindToVault(IntPtr.Zero, true, true); if (null == vault) { throw new NotImplementedException("Vault connection not found"); } long length = new System.IO.FileInfo("C:\\temp\\New_Sample.txt").Length; // Define the property values for the new object. var propertyValues = new MFilesAPI.PropertyValues(); // Class. var classPropertyValue = new MFilesAPI.PropertyValue() { PropertyDef = (int)MFBuiltInPropertyDef.MFBuiltInPropertyDefClass }; classPropertyValue.Value.SetValue( MFDataType.MFDatatypeLookup, // This must be correct for the property definition. //(int)MFBuiltInDocumentClass.MFBuiltInDocumentClassOtherDocument (int)vault.ClassOperations.GetObjectClassIDByAlias("Class.FerretArchiveDocument") ); propertyValues.Add(-1, classPropertyValue); // Name or title. var nameOrTitlePropertyValue = new MFilesAPI.PropertyValue() { PropertyDef = (int)MFBuiltInPropertyDef.MFBuiltInPropertyDefNameOrTitle }; nameOrTitlePropertyValue.Value.SetValue( MFDataType.MFDatatypeText, // This must be correct for the property definition. nameOrTitle ); propertyValues.Add(-1, nameOrTitlePropertyValue); //Douument Date var docDatePropertyValue = new MFilesAPI.PropertyValue() { PropertyDef = (int)vault.PropertyDefOperations.GetPropertyDefIDByAlias("Prop.DocumentDate") }; docDatePropertyValue.Value.SetValue( MFDataType.MFDatatypeDate, documentDate ); propertyValues.Add(-1, docDatePropertyValue); // Ferret Document Class var ferretDocumentClassPropertyValue = new MFilesAPI.PropertyValue() { PropertyDef = (int)vault.PropertyDefOperations.GetPropertyDefIDByAlias("Prop.FerretDocumentClass") }; ferretDocumentClassPropertyValue.Value.SetValue( MFDataType.MFDatatypeText, ferretDocumentClass ); propertyValues.Add(-1, ferretDocumentClassPropertyValue); // Account Number var accountNumberPropertyValue = new MFilesAPI.PropertyValue() { PropertyDef = (int)vault.PropertyDefOperations.GetPropertyDefIDByAlias("Prop.AccountNumber") }; accountNumberPropertyValue.Value.SetValue( MFDataType.MFDatatypeText, accountNumber ); propertyValues.Add(-1, accountNumberPropertyValue); // Client Name var clientNamePropertyValue = new MFilesAPI.PropertyValue() { PropertyDef = (int)vault.PropertyDefOperations.GetPropertyDefIDByAlias("Prop.ClientName") }; clientNamePropertyValue.Value.SetValue( MFDataType.MFDatatypeText, clientName ); propertyValues.Add(-1, clientNamePropertyValue); // Description var descriptionPropertyValue = new MFilesAPI.PropertyValue() { PropertyDef = (int)vault.PropertyDefOperations.GetPropertyDefIDByAlias("Prop.Description") }; descriptionPropertyValue.Value.SetValue( MFDataType.MFDatatypeText, description ); propertyValues.Add(-1, descriptionPropertyValue); //Ferret Doc Id var docIdPropertyValue = new MFilesAPI.PropertyValue() { PropertyDef = (int)vault.PropertyDefOperations.GetPropertyDefIDByAlias("Prop.FerretDocId") }; docIdPropertyValue.Value.SetValue( MFDataType.MFDatatypeInteger, docID ); propertyValues.Add(-1, docIdPropertyValue); // Define the source files to add. var sourceFiles = new MFilesAPI.SourceObjectFiles(); // Add one file. var myFile = new MFilesAPI.SourceObjectFile(); myFile.SourceFilePath = @"C:\temp\\New_Sample.txt"; myFile.Title = "My test document"; // For single-file-documents this is ignored. myFile.Extension = extension.Replace(".", ""); sourceFiles.Add(-1, myFile); // What object type is being created? var objectTypeID = (int)MFBuiltInObjectType.MFBuiltInObjectTypeDocument; // A "single file document" must be both a document and contain exactly one file. var isSingleFileDocument = objectTypeID == (int)MFBuiltInObjectType.MFBuiltInObjectTypeDocument && sourceFiles.Count == 1; #endregion // Create the object and check it in. try { if (length != 0) { var objectVersion = vault.ObjectOperations.CreateNewObjectEx( objectTypeID, propertyValues, sourceFiles, SFD: isSingleFileDocument, CheckIn: true); string msg = string.Format("Record {0}", docID); WriteLog("Success:", msg); } else { // Define the source files to add. //var sourceFiles1 = new MFilesAPI.SourceObjectFiles(); //// Add one file. //var myFile1 = new MFilesAPI.SourceObjectFile(); //myFile1.SourceFilePath = filepath; //myFile1.Title = "My test document"; // For single-file-documents this is ignored. //myFile1.Extension = extension.Replace(".", ""); //sourceFiles1.Add(-1, myFile1); //var objectVersion = vault.ObjectOperations.CreateNewObjectEx( // objectTypeID, // propertyValues, // sourceFiles1, // SFD: isSingleFileDocument, // CheckIn: true); //string msg = string.Format("Record {0}", docID); //WriteLog("Success:", msg); string ErrorMsg = string.Format("Record {0}, Document Name {1} dated {2} for account {3}. Msg is {4} ", docID, nameOrTitle, documentDate, accountNumber, "File size 0"); // e.Message); WriteLog("Error:", ErrorMsg); // string loadLog = string.Format("{0},(1},{2},{3},{4},{5},{6}", nameOrTitle, documentDate, ferretDocumentClass, accountNumber, clientName, description, filepath); // WriteErrorLog(loadLog); } } catch (System.IO.IOException e) { //try //{ // // Define the source files to add. // var sourceFiles1 = new MFilesAPI.SourceObjectFiles(); // // Add one file. // var myFile1 = new MFilesAPI.SourceObjectFile(); // myFile1.SourceFilePath = filepath; // myFile1.Title = "My test document"; // For single-file-documents this is ignored. // myFile1.Extension = extension.Replace(".", ""); // sourceFiles1.Add(-1, myFile1); // var objectVersion = vault.ObjectOperations.CreateNewObjectEx( // objectTypeID, // propertyValues, // sourceFiles1, // SFD: isSingleFileDocument, // CheckIn: true); // string msg = string.Format("Record {0}", docID); // WriteLog("Success:", msg); //} //catch { string ErrorMsg = string.Format("Record {0}, Document Name {1} dated {2} for account {3}. Msg is {4} ", docID, nameOrTitle, documentDate, accountNumber, e.Message); WriteLog("Error:", ErrorMsg); string loadLog = string.Format("{0},(1},{2},{3},{4},{5},{6}", nameOrTitle, documentDate, ferretDocumentClass, accountNumber, clientName, description, filepath); WriteErrorLog(loadLog); } } }
public void OnPostprocessBuild(BuildReport report) { #if UNITY_ANDROID if (autoIncrementVersion) { if ((report.summary.options & BuildOptions.Development) == 0) { PlayerSettings.Android.bundleVersionCode++; UnityEngine.Debug.Log("Incrementing version code to " + PlayerSettings.Android.bundleVersionCode); } } bool isExporting = true; foreach (var step in report.steps) { if (step.name.Contains("Compile scripts") || step.name.Contains("Building scenes") || step.name.Contains("Writing asset files") || step.name.Contains("Preparing APK resources") || step.name.Contains("Creating Android manifest") || step.name.Contains("Processing plugins") || step.name.Contains("Exporting project") || step.name.Contains("Building Gradle project")) { OVRPlugin.SendEvent("build_step_" + step.name.ToLower().Replace(' ', '_'), step.duration.TotalSeconds.ToString(), "ovrbuild"); #if BUILDSESSION UnityEngine.Debug.LogFormat("build_step_" + step.name.ToLower().Replace(' ', '_') + ": {0}", step.duration.TotalSeconds.ToString()); #endif if (step.name.Contains("Building Gradle project")) { isExporting = false; } } } OVRPlugin.AddCustomMetadata("build_step_count", report.steps.Length.ToString()); if (report.summary.outputPath.Contains("apk")) // Exclude Gradle Project Output { var fileInfo = new System.IO.FileInfo(report.summary.outputPath); OVRPlugin.AddCustomMetadata("build_output_size", fileInfo.Length.ToString()); } #endif if (!report.summary.outputPath.Contains("OVRGradleTempExport")) { OVRPlugin.SendEvent("build_complete", (System.DateTime.Now - buildStartTime).TotalSeconds.ToString(), "ovrbuild"); #if BUILDSESSION UnityEngine.Debug.LogFormat("build_complete: {0}", (System.DateTime.Now - buildStartTime).TotalSeconds.ToString()); #endif } #if UNITY_ANDROID if (!isExporting) { // Get the hosts path to Android SDK if (adbTool == null) { adbTool = new OVRADBTool(OVRConfig.Instance.GetAndroidSDKPath(false)); } if (adbTool.isReady) { // Check to see if there are any ADB devices connected before continuing. List <string> devices = adbTool.GetDevices(); if (devices.Count == 0) { return; } // Clear current logs on device Process adbClearProcess; adbClearProcess = adbTool.RunCommandAsync(new string[] { "logcat --clear" }, null); // Add a timeout if we cannot get a response from adb logcat --clear in time. Stopwatch timeout = new Stopwatch(); timeout.Start(); while (!adbClearProcess.WaitForExit(100)) { if (timeout.ElapsedMilliseconds > 2000) { adbClearProcess.Kill(); return; } } // Check if existing ADB process is still running, kill if needed if (adbProcess != null && !adbProcess.HasExited) { adbProcess.Kill(); } // Begin thread to time upload and install var thread = new Thread(delegate() { TimeDeploy(); }); thread.Start(); } } #endif }
/// <summary> /// Get file last access /// </summary> /// <param name="filename">file name</param> /// <returns></returns> public static System.DateTime GetLastAccess(string filename) { System.IO.FileInfo fi = new System.IO.FileInfo(filename); //get Create Time return(fi.LastAccessTime); }
private KeyValuePair <Dictionary <int, bool>, bool> solveCNF(FileInfo file) { //For omega3, threshold only works on existing pair, currently the new pair in D_N will all have constant cost, //so, no need to filter, either accept them all or not at all //Thus, we can use one threshold for both omega2 and omega3 (with option to accept new pair in D_N or not) //if (autoThreshold > 0) // omega2Threshold = autoThreshold; double threshold2 = 1000000000 * autoThreshold;// omega2Threshold; //double threshold3 = 100000000000 + (1000000000 * omega3Threshold); Dictionary <int, bool> inducedPairs = new Dictionary <int, bool>(); long time = DateTime.Now.Ticks; //solve string solverPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SATSolverConsole.jar"); string strCmdText = string.Format("/C java -jar {0} {1}", solverPath, file.FullName); System.Diagnostics.Process process = new System.Diagnostics.Process(); System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; startInfo.FileName = "cmd.exe"; startInfo.Arguments = strCmdText; process.StartInfo = startInfo; time = DateTime.Now.Ticks; process.Start(); process.WaitForExit(); long timeToSolve = (DateTime.Now.Ticks - time) / TimeSpan.TicksPerMillisecond; bool decision = false; System.IO.FileInfo solFile = new System.IO.FileInfo(file.FullName + ".sol"); System.IO.FileInfo costFile = new System.IO.FileInfo(file.FullName + ".inf"); string solution = System.IO.File.ReadAllText(solFile.FullName); if (string.IsNullOrEmpty(solution.Trim())) { return(new KeyValuePair <Dictionary <int, bool>, bool>(new Dictionary <int, bool>(), decision)); //unsatisfiable } else { string[] lines = System.IO.File.ReadAllLines(file.FullName + ".inf"); if (lines.Length > 1) { totalCost = long.Parse(lines[1]); currentCost = totalCost - totalCostHistory; totalCostHistory = totalCost; /*if (omega3Threshold > 0) * if (currentCost <= threshold3) * Debug.WriteLine("ACCEPTED PAIR: " + currentCost + " totalCost: " + totalCost); * else * Debug.WriteLine("REJECTED PAIR: " + currentCost + " totalCost: " + totalCost); * else if (omega2Threshold > 0) * if (currentCost <= threshold2) * Debug.WriteLine("ACCEPTED PAIR: " + currentCost + " totalCost: " + totalCost); * else * Debug.WriteLine("REJECTED PAIR: " + currentCost + " totalCost: " + totalCost); */ } } foreach (var item in solution.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)) { int varValue = int.Parse(item); bool b = varValue > 0 ? true : false; double currentThreshold = threshold2; /*bool useThreshold = false; * if (omega3Threshold > 0 && omega2Threshold == 0) * { * currentThreshold = threshold3; * useThreshold = true;// totalCost < omega3Threshold ? false : true; * } * else if (omega2Threshold > 0 && omega3Threshold == 0) * { * currentThreshold = threshold2; * useThreshold = true;// totalCost < omega2Threshold ? false : true; * } * if (b && varPairMap.ContainsKey(varValue)) * { * Debug.WriteLine("CurrentCost: " + currentCost); * if (!useThreshold && currentCost == 100000000000) * { * inducedPairs[varValue] = true; * Debug.WriteLine("#ACCEPTED PAIR: " + currentCost + " totalCost: " + totalCost); * } * else// if (currentCost <= currentThreshold) * { * inducedPairs[varValue] = false; * //Debug.WriteLine("ACCEPTED PAIR: " + currentCost); * Debug.WriteLine("REJECTED PAIR: " + currentCost + " totalCost: " + totalCost); * } * //else * // Debug.WriteLine("REJECTED PAIR: " + currentCost + " totalCost: " + totalCost); * //if (totalCost > 100000000000) * // Debug.WriteLine(totalCost); * }*/ if (b && varPairMap.ContainsKey(varValue)) { //if (languageOption == 2) //Change threshold // currentThreshold = 100000000000 + (1000000000 * omega2Threshold); if (currentCost > highestCost) { highestCost = currentCost; } if (autoThreshold < 0 || (autoThreshold >= 0 && currentCost <= currentThreshold)) { inducedPairs[varValue] = true; } else { inducedPairs[varValue] = false; } /*if (autoThreshold == 0 || (autoThreshold > 0 && currentCost <= currentThreshold)) * { * if (acceptOmega3NewPair) //Expecting Omega3 results with new pairs * inducedPairs[varValue] = true; * else //Expecting Omega2 results * { * double newPairsThreshold = 100000000000 + (1000000000 * autoThreshold); * if (currentCost <= newPairsThreshold) * inducedPairs[varValue] = true; * else * inducedPairs[varValue] = false; * } * }*/ } } return(new KeyValuePair <Dictionary <int, bool>, bool>(inducedPairs, decision)); }
protected void Page_Load(object sender, EventArgs e) { CtlLib.SetUser(Session["APP_DBUSER"].ToString()); string l_dtfrm = Request["p_dtfrom"]; string l_dtto = Request["p_dtto"]; string TemplateFile = "rpt_60240100_Allotment_Occupancy_Details.xls"; string TempFile = "../../../../system/temp/rpt_60240100_Allotment_Occupancy_Details_" + Session["User_ID"].ToString() + ".xls"; TemplateFile = Server.MapPath(TemplateFile); TempFile = Server.MapPath(TempFile); //Create a new workbook IWorkbook exBook = NativeExcel.Factory.OpenWorkbook(TemplateFile); //Add worksheet IWorksheet exSheet = exBook.Worksheets[1]; IRange range; //bind data to excel file string para = ""; DataTable dt; para = "'" + l_dtfrm + "','" + l_dtto + "'"; dt = CtlLib.TableReadOpenCursor("ht_rpt_60240100_allotment_occ", para); //-----header--- //---end--header--- //--set-----DataBind--in---Master--- if (dt.Rows.Count == 0) { exSheet.Cells[2, 3].Value = "There is not data!"; } if (dt.Rows.Count > 0) { exSheet.Cells[2, 7].Value = dt.Rows[0]["print_time"].ToString(); exSheet.Cells[2, 1].Value = dt.Rows[0]["para_date"].ToString(); /*exSheet.Cells[2, 1].Select(); * * byte[] MyData = new byte[0]; * MyData = (byte[])dt.Rows[0]["logo_lotus"]; * MemoryStream stream = new MemoryStream(MyData); * exSheet.Shapes.AddPicture(stream);*/ } //---------------------- ////end-set-----DataBind--in---Master--- for (int l_addrow = 1; l_addrow < dt.Rows.Count; l_addrow++) { exSheet.Range["A5"].Rows.EntireRow.Insert();//insert row new of sheet } //set date title of year //exSheet.Cells[2, 1].Value = "Income Statement Year" + " " + l_year; //set data to detail. // loop detail not percent double l_total_vnd = 0; float l_total_usd = 0; int l_cnt = dt.Rows.Count; for (int l_row = 1; l_row <= dt.Rows.Count; l_row++) { for (int col = 0; col <= 9; col++) { if (col == 5 || col == 7 || col == 8 || col == 9) { if (dt.Rows[l_row - 1][col].ToString() == "") { exSheet.Cells[3 + l_row, col + 1].Value = dt.Rows[l_row - 1][col].ToString(); } else { exSheet.Cells[3 + l_row, col + 1].Value = double.Parse(dt.Rows[l_row - 1][col].ToString()); exSheet.Cells[3, col + 1, l_row + 3, col + 1].NumberFormat = "#,##0"; exSheet.Cells[l_row + 3, col + 1].HorizontalAlignment = XlHAlign.xlHAlignRight; } } else { exSheet.Cells[3 + l_row, col + 1].Value = dt.Rows[l_row - 1][col].ToString(); exSheet.Cells[l_row + 3, col + 1].HorizontalAlignment = XlHAlign.xlHAlignLeft; } if (dt.Rows[l_row - 1][0].ToString() != "" && dt.Rows[l_row - 1][1].ToString() == "") { exSheet.Cells[l_row + 3, 1, l_row + 3, 10].Interior.Color = Color.Silver; } if (dt.Rows[l_row - 1][0].ToString() == "" && dt.Rows[l_row - 1][1].ToString() == "") { exSheet.Cells[l_row + 3, 1, l_row + 3, 10].Interior.Color = Color.Orange; } } } // end loop detail percent if (File.Exists(TempFile)) { File.Delete(TempFile); } // hide row firts range = exSheet.Range["A1"]; // hide row A5 range.Rows.Hidden = true; // font bold header exBook.SaveAs(TempFile); //CtlLib.ExcelToPdf(TempFile); //string pdfFilePath = TempFile.Replace(".xls", ".pdf"); //write out to client broswer System.IO.FileInfo file = new System.IO.FileInfo(TempFile); //System.IO.FileInfo file = new System.IO.FileInfo(pdfFilePath); Response.Clear(); Response.Charset = "UTF-8"; Response.ContentEncoding = System.Text.Encoding.UTF8; //Add header, give a default file name for "File Download/Store as" Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name)); //Add header, set file size to enable browser display download progress Response.AddHeader("Content-Length", file.Length.ToString()); //Set the return string is unavailable reading for client, and must be downloaded Response.ContentType = "application/ms-exSheet"; //Response.ContentType = "application/pdf"; //Send file string to client Response.WriteFile(TempFile); //Response.WriteFile(pdfFilePath); //Stop execute Response.End(); }
private void ExtractFile(SIO.FileInfo fileName, ExtendedDirectoryInfo targetDir) { Middle.Helpers.CompressionHelpers.Compression.Decompress(fileName, targetDir, string.Empty); //File.Delete(fileName.FullName); }
private async Task httpGet(string URL, string localpath) { string fileName = Path.GetFileName(localpath); if (fileName.EndsWith(".stream%7E")) { fileName = fileName.Remove(fileName.Length - 3); fileName = fileName + "~"; } filesToDownload.Add(localpath); numberOfActiveParallelDownloads++; if (!File.Exists(localpath)) { DownloadStatus dl = new DownloadStatus(); dl.File = localpath; dl.percent = 0.0; dl.active = true; statusOfDownloads.Add(dl); try { Action EmptyDelegate = delegate() { }; control.ShadowBoxText.Text = "Downloading '" + fileName + "'"; control.ShadowBox.Visibility = Visibility.Visible; control.shadowBoxCancelButton.Visibility = Visibility.Visible; control.UpdateLayout(); control.Dispatcher.Invoke(DispatcherPriority.Render, EmptyDelegate); // Create a new WebClient instance. WebClient client = new WebClient(); client.DownloadProgressChanged += (s, e) => { dl.percent = ((double)e.BytesReceived / (double)e.TotalBytesToReceive) * 100.0; control.Dispatcher.BeginInvoke(new Action <DownloadStatus>(UpdateOnDownload), DispatcherPriority.Normal, dl); }; client.DownloadFileCompleted += (s, e) => { try { //control.Dispatcher.BeginInvoke(new Action<string>(FinishedDownload), DispatcherPriority.Normal, localpath); string[] files = new string[filesToDownload.Count]; int i = 0; foreach (string path in filesToDownload) { long length = new System.IO.FileInfo(path).Length; if (length == 0) { if (File.Exists(path)) { File.Delete(path); } } else { files[i] = path; i++; } } loadFile(localpath); } catch { //Could happen when we cancel the download. } }; //tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; await Task.Run(() => { token.Register(() => { client.CancelAsync(); CanceledDownload(); return; }); client.DownloadFileAsync(new Uri(URL), localpath); }, token); } catch (Exception ex) { MessageTools.Error(ex.ToString()); } } else { await control.Dispatcher.BeginInvoke(new Action <string>(FinishedDownload), DispatcherPriority.Normal, ""); } }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string from = Request.QueryString["from"]; string to = Request.QueryString["to"]; string role, state, vids, yr, mon, folderpath; //string atmid = Request.QueryString["atmid"]; string user = Request.QueryString["user"]; string fname = Session["sess_userid"] + "_" + System.DateTime.Now.ToString("ddMMyyhhmmss"); if (Request.QueryString["role"] == "%") { role = "u.role in ('AO','DE','CM')"; } else { role = "u.role like '" + Request.QueryString["role"] + "'"; } if (Request.QueryString["state"] == "") { state = "a.state like '%'"; } else { state = "a.state in (" + Request.QueryString["state"] + ")"; } conn.ConnectionString = ConfigurationManager.ConnectionStrings["SQLConnstr"].ConnectionString; string query = @"select vid,d.atmid from dr_ctp d inner join atms a on d.atmid=a.atmid join users u on u.userid=d.userid where convert(date,vdate) between '" + from + "' and '" + to + "' and " + state + " and " + role + " and d.userid like '" + user + "'"; // Response.Write(query); SqlCommand cmd1 = new SqlCommand(query, conn); conn.Open(); SqlDataReader dr = cmd1.ExecuteReader(); while (dr.Read()) { string path = Server.MapPath("~/BulkDownload/" + fname + "/" + dr[1].ToString() + "/" + dr[0].ToString()); //System.IO.Directory.CreateDirectory(Server.MapPath("~/BulkDownload/" + fname)); if (!Directory.Exists(path)) { System.IO.Directory.CreateDirectory(path); } vids = dr[0].ToString(); yr = getvalue(vids, 2); mon = getvalue(vids, 1); folderpath = yr + @"\" + mon + @"\"; for (int i = 1; i <= 41; i++) { /*Add Files*/ try { if (File.Exists("C:\\Development\\CommonStorage\\Mphasis\\TransientStorage\\" + folderpath.Replace(@"\\", @"\\") + "PhotoQ" + i.ToString() + "_" + vids + ".jpg") == true) { File.Copy(@"C:\Development\CommonStorage\Mphasis\TransientStorage\" + folderpath + "PhotoQ" + i.ToString() + "_" + vids + ".jpg", @"C:\Development\v6_Mphasis\BulkDownload\" + fname + @"\" + dr[1].ToString() + @"\" + vids + @"\" + "PhotoQ" + i.ToString() + "_" + vids + ".jpg"); } } catch (Exception er) { // Response.Write(er.Message.ToString()); } } for (int i = 0; i <= 5; i++) { /*Add Files*/ try { if (File.Exists("C:\\Development\\CommonStorage\\Mphasis\\TransientStorage\\" + folderpath.Replace(@"\\", @"\\") + "Photo" + vids + "_" + i.ToString() + ".jpg") == true) { File.Copy(@"C:\Development\CommonStorage\Mphasis\TransientStorage\" + folderpath + "Photo" + vids + "_" + i.ToString() + ".jpg", @"C:\Development\v6_Mphasis\BulkDownload\" + fname + @"\" + dr[1].ToString() + @"\" + vids + @"\" + "Photo" + vids + "_" + i.ToString() + ".jpg"); } } catch (Exception er) { // Response.Write(er.Message.ToString()); } } } conn.Close(); /*Add Zip*/ using (ZipFile zip = new ZipFile()) { try { zip.AddDirectory(@"C:\Development\v6_Mphasis\BulkDownload\" + fname); //user = Session["sess_userid"].ToString() + "_" + System.DateTime.Now.ToString("hhmmss"); zip.Save(@"C:\Development\v6_Mphasis\BulkDownload\" + fname + ".zip"); /*Delete Folder*/ var dir = new DirectoryInfo(@"C:\Development\v6_Mphasis\BulkDownload\" + fname); dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly; dir.Delete(true); System.IO.FileInfo file = new System.IO.FileInfo(@"C:\Development\v6_Mphasis\BulkDownload\" + fname + ".zip"); Response.ClearContent(); Response.AddHeader("Content-Disposition", String.Format("attachment; filename=" + fname + ".zip", file.Name)); Response.AddHeader("Content-Length", file.Length.ToString()); Response.ContentType = "application/zip"; this.EnableViewState = false; Response.TransmitFile(file.FullName); Response.Flush(); File.Delete(@"C:\Development\v6_Mphasis\BulkDownload\" + fname + ".zip"); Response.End(); } catch { } } } }
protected void Page_Load(object sender, EventArgs e) { CtlLib.SetUser(Session["APP_DBUSER"].ToString()); string TemplateFile = "rpt_60280120_payment_report.xls"; string TempFile = "../../../../system/temp/rpt_60280120_payment_report_" + Session["User_ID"].ToString() + ".xls"; TemplateFile = Server.MapPath(TemplateFile); TempFile = Server.MapPath(TempFile); //Create a new workbook IWorkbook exBook = NativeExcel.Factory.OpenWorkbook(TemplateFile); //Add worksheet IWorksheet exSheet = exBook.Worksheets[1]; IRange range; //bind data to excel file string p_date = Request["p_date"]; string p_date_to = Request["p_date_to"]; string p_room = Request["p_room"]; string p_payment_method = Request["p_payment_method"]; string p_partner_PK = Request["p_partner_PK"]; string p_time_frm = Request["p_time_frm"]; string p_time_to = Request["p_time_to"]; string p_cashier = Request["p_cashier"]; string para = "'" + p_date + "','" + p_date_to + "','" + p_room + "','" + p_payment_method + "','" + p_partner_PK + "','" + p_time_frm + "','" + p_time_to + "','" + p_cashier + "'"; DataTable dt = CtlLib.TableReadOpenCursor("ht_sel_60280120", para); // MASTER // INSERT ROWS for (int l_addrow = 1; l_addrow < dt.Rows.Count; l_addrow++) { exSheet.Range["A9"].Rows.EntireRow.Insert();//insert row new of sheet } // SET DATA int pos = 8; int i = 0; for (i = 0; i < dt.Rows.Count; i++) { exSheet.Cells[pos + i, 1].Value = i + 1; exSheet.Cells[pos + i, 2].Value = dt.Rows[i]["room_no"]; exSheet.Cells[pos + i, 3].Value = dt.Rows[i]["invoice_no"]; exSheet.Cells[pos + i, 4].Value = dt.Rows[i]["pay_date"]; exSheet.Cells[pos + i, 5].Value = dt.Rows[i]["guest_name"]; exSheet.Cells[pos + i, 6].Value = dt.Rows[i]["checkin_date"]; exSheet.Cells[pos + i, 7].Value = dt.Rows[i]["checkout_date"]; exSheet.Cells[pos + i, 8].Value = dt.Rows[i]["partner_name"]; // exSheet.Cells[pos + i, 9 ].Value = dt.Rows[i]["description"]; } //--------- //exSheet.Cells[pos + i, 6 ].Value = "=sum(F10:F"+(pos+i-1)+")"; //exSheet.Cells[pos + i, 7].Value = "=sum(G10:G"+(pos+i-1)+")"; //--------- if (File.Exists(TempFile)) { File.Delete(TempFile); } // hide row firts range = exSheet.Range["A1"]; // hide row A5 // range.Rows.Hidden = true; // font bold header /*range = exSheet.Range["A1:AC1"]; * range.Rows[4].Font.Bold = true;*/ exBook.SaveAs(TempFile); //write out to client broswer System.IO.FileInfo file = new System.IO.FileInfo(TempFile); //System.IO.FileInfo file = new System.IO.FileInfo(pdfFilePath); Response.Clear(); Response.Charset = "UTF-8"; Response.ContentEncoding = System.Text.Encoding.UTF8; //Add header, give a default file name for "File Download/Store as" Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name)); //Add header, set file size to enable browser display download progress Response.AddHeader("Content-Length", file.Length.ToString()); //Set the return string is unavailable reading for client, and must be downloaded Response.ContentType = "application/ms-exSheet"; //Response.ContentType = "application/pdf"; //Send file string to client //Response.WriteFile(pdfFilePath); Response.WriteFile(TempFile); //Stop execute Response.End(); }
private void textBoxDir_TextChanged(object sender, EventArgs e) { imagini.Clear(); imaginiCheie.Clear(); listaFisiere.Clear(); pictureBox1.Image = null; if (IO.Directory.Exists(textBoxDir.Text)) { //Asociere director cu aliniamentul using (acadDoc.LockDocument()) using (Transaction trdir = db.TransactionManager.StartTransaction()) using (ResultBuffer RB = new ResultBuffer(new TypedValue(1001, "OVIDIU"), new TypedValue(1000, "POZE->" + textBoxDir.Text))) { //Alignment Ax = (Alignment)trans.GetObject(((Alignment)comboBoxAx.SelectedItem).Id, OpenMode.ForWrite); string nume = ((Alignment)comboBoxAx.SelectedItem).Name; Alignment Ax = null; foreach (ObjectId idAx in civDoc.GetAlignmentIds()) { Ax = (Alignment)trdir.GetObject(idAx, OpenMode.ForRead); if (Ax.Name == nume) { Ax.UpgradeOpen(); Ax.XData = RB; } } //Ax.UpgradeOpen(); //Ax.XData = RB; //Capturare Senzor CapturaSenzor(); //CapturaSenzor(trans, Ax); //TypedValue[] TVs = new TypedValue[] //{ // new TypedValue(0, "SOLID"), // new TypedValue(8, "AR-MArker"), // new TypedValue(62, "3") //}; //SelectionFilter SF = new SelectionFilter(TVs); //PromptSelectionResult PSR = ed.SelectAll(SF); //if (PSR.Status != PromptStatus.OK) return; //SelectionSet SS = PSR.Value; //foreach (SelectedObject SO in SS) //{ // Solid S = (Solid)trans.GetObject(SO.ObjectId, OpenMode.ForRead); // double[] Xs = { S.GetPointAt(0).X, S.GetPointAt(1).X, S.GetPointAt(2).X }; // double[] Ys = { S.GetPointAt(0).Y, S.GetPointAt(1).Y, S.GetPointAt(2).Y }; // double km = double.NaN; // double offset = double.NaN; // try // { // Ax.StationOffset(Xs.Average(), Ys.Average(), ref km, ref offset); // } // catch { } // if (offset != double.NaN) // { // if (Senzor == null) Senzor = S; // else // { // double[] SenzorXs = { Senzor.GetPointAt(0).X, Senzor.GetPointAt(1).X, Senzor.GetPointAt(2).X }; // double[] SenzorYs = { Senzor.GetPointAt(0).Y, Senzor.GetPointAt(1).Y, Senzor.GetPointAt(2).Y }; // double SenzorKm = double.NaN; // double SenzorOffset = double.NaN; // try // { // Ax.StationOffset(SenzorXs.Average(), SenzorYs.Average(), ref SenzorKm, ref SenzorOffset); // if (offset < SenzorOffset) Senzor = S; // } // catch { } // } // } //} //if (Senzor != null) checkBoxSincr.Checked = true; // trdir.Commit(); }// //Inregistrare vedere curenta VTRcur = ed.GetCurrentView().Clone() as ViewTableRecord; //Citire imaginiCheie din fisierul CALIBRARE.TXT daca acesta exista if (IO.File.Exists(textBoxDir.Text + @"\CALIBRARE.TXT")) { using (IO.StreamReader reader = new IO.FileInfo(textBoxDir.Text + @"\CALIBRARE.TXT").OpenText()) { string linie = null; while ((linie = reader.ReadLine()) != null) { if (linie.Contains("********")) { try { string[] componente = linie.Remove(0, 4).Replace("********", "").Split(new string[] { "-> " }, StringSplitOptions.None); imaginiCheie.Add(int.Parse(componente[0]), componente[1]); } catch { } } } } //WF.MessageBox.Show("Numar chei citite: " + imaginiCheie.Count.ToString() + ": " + imaginiCheie.ToString()); } ActualizarePoze(); } else { textBoxDir.Text = @"-"; } }
public virtual string GetAppSettingsPath() { //Used to determine where to store the settings System.IO.FileInfo fi = new System.IO.FileInfo(Application.ExecutablePath); return(fi.DirectoryName); }
private void webGateway_ProcessRequest(object gwRequest) { var request = (WebServiceGatewayRequest)gwRequest; var context = request.Context; string requestedUrl = request.UrlRequest; bool wroteBytes = false; var migRequest = new MIGClientRequest() { Context = context, RequestOrigin = context.Request.RemoteEndPoint.Address.ToString(), RequestMessage = requestedUrl, SubjectName = "HTTP", SubjectValue = context.Request.HttpMethod, InputStream = context.Request.InputStream, OutputStream = context.Response.OutputStream }; // we are expecting url in the forms http://<hgserver>/<hgservicekey>/<servicedomain>/<servicegroup>/<command>/<opt1>/.../<optn> // arguments up to <command> are mandatory. string migCommand = requestedUrl.Substring(requestedUrl.IndexOf('/', 1) + 1); //string section = requestedurl.Substring (0, requestedurl.IndexOf ('/', 1) - 1); TODO: "api" section keyword, ignored for now //TODO: implement "api" keyword in MIGInterfaceCommand? var command = new MIGInterfaceCommand(migCommand); //PREPROCESS request: if domain != html, execute command if (ServiceRequestPreProcess != null) { ServiceRequestPreProcess(migRequest, command); // request was handled by preprocess listener if (!string.IsNullOrEmpty(command.Response)) { // simple automatic json response type detection if (command.Response.StartsWith("[") && command.Response.EndsWith("]") || (command.Response.StartsWith("{") && command.Response.EndsWith("}"))) { // TODO: check the reason why this cause ajax/json error on some browser context.Response.ContentType = "application/json"; context.Response.ContentEncoding = defaultWebFileEncoding; } WebServiceUtility.WriteStringToContext(context, command.Response); return; } } if (command.Domain == "MIGService.Interfaces") { // This is a MIGService namespace Web API context.Response.ContentType = "application/json"; switch (command.Command) { case "IsEnabled.Set": if (command.GetOption(0) == "1") { configuration.GetInterface(command.NodeId).IsEnabled = true; EnableInterface(command.NodeId); } else { configuration.GetInterface(command.NodeId).IsEnabled = false; DisableInterface(command.NodeId); } WebServiceUtility.WriteStringToContext(context, "[{ \"ResponseValue\" : \"OK\" }]"); // if (InterfacePropertyChanged != null) { InterfacePropertyChanged(new InterfacePropertyChangedAction() { Domain = "MIGService.Interfaces", SourceId = command.NodeId, SourceType = "MIG Interface", Path = "Status.IsEnabled", Value = command.GetOption(0) }); } break; case "IsEnabled.Get": WebServiceUtility.WriteStringToContext( context, "[{ \"ResponseValue\" : \"" + (configuration.GetInterface(command.NodeId).IsEnabled ? "1" : "0") + "\" }]" ); break; case "Options.Set": Interfaces[command.NodeId].SetOption(command.GetOption(0), command.GetOption(1)); WebServiceUtility.WriteStringToContext(context, "[{ \"ResponseValue\" : \"OK\" }]"); // if (InterfacePropertyChanged != null) { InterfacePropertyChanged(new InterfacePropertyChangedAction() { Domain = "MIGService.Interfaces", SourceId = command.NodeId, SourceType = "MIG Interface", Path = "Options." + command.GetOption(0), Value = command.GetOption(1) }); } break; case "Options.Get": string optionValue = Interfaces[command.NodeId].GetOption(command.GetOption(0)).Value; WebServiceUtility.WriteStringToContext( context, "[{ \"ResponseValue\" : \"" + Uri.EscapeDataString(optionValue) + "\" }]" ); break; default: break; } } else if (requestedUrl.StartsWith(webServiceConfig.BaseUrl)) { // If request begins /hg/html, process as standard Web request string requestedFile = GetWebFilePath(requestedUrl); if (!System.IO.File.Exists(requestedFile)) { context.Response.StatusCode = 404; //context.Response.OutputStream.WriteByte(); } else { bool isText = false; if (requestedUrl.EndsWith(".js")) // || requestedurl.EndsWith(".json")) { context.Response.ContentType = "text/javascript"; isText = true; } else if (requestedUrl.EndsWith(".css")) { context.Response.ContentType = "text/css"; isText = true; } else if (requestedUrl.EndsWith(".zip")) { context.Response.ContentType = "application/zip"; } else if (requestedUrl.EndsWith(".png")) { context.Response.ContentType = "image/png"; } else if (requestedUrl.EndsWith(".jpg")) { context.Response.ContentType = "image/jpeg"; } else if (requestedUrl.EndsWith(".gif")) { context.Response.ContentType = "image/gif"; } else if (requestedUrl.EndsWith(".mp3")) { context.Response.ContentType = "audio/mp3"; } else if (requestedUrl.EndsWith(".appcache")) { context.Response.ContentType = "text/cache-manifest"; } else { context.Response.ContentType = "text/html"; isText = true; } var file = new System.IO.FileInfo(requestedFile); context.Response.AddHeader("Last-Modified", file.LastWriteTimeUtc.ToString("r")); context.Response.Headers.Set(HttpResponseHeader.LastModified, file.LastWriteTimeUtc.ToString("r")); // PRE PROCESS text output //TODO: add callback for handling caching (eg. function that returns true or false with requestdfile as input and that will return false for widget path) if (isText) { try { WebFileCache cachedItem = GetWebFileCache(requestedFile); context.Response.ContentEncoding = cachedItem.Encoding; context.Response.ContentType += "; charset=" + cachedItem.Encoding.BodyName; string body = cachedItem.Content; // // expand preprocessor tags body = body.Replace("{hostos}", Environment.OSVersion.Platform.ToString()); // bool tagFound; do { tagFound = false; int ts = body.IndexOf("{include "); if (ts > 0) { int te = body.IndexOf("}", ts); if (te > ts) { string rs = body.Substring(ts + (te - ts) + 1); string cs = body.Substring(ts, te - ts + 1); string ls = body.Substring(0, ts); // try { if (cs.StartsWith("{include ")) { string fileName = cs.Substring(9).TrimEnd('}').Trim(); fileName = GetWebFilePath(fileName); // Encoding fileEncoding = DetectWebFileEncoding(fileName); if (fileEncoding == null) { fileEncoding = defaultWebFileEncoding; } body = ls + System.IO.File.ReadAllText(fileName, fileEncoding) + rs; } } catch { body = ls + "<h5 style=\"color:red\">Error processing '" + cs.Replace( "{", "[" ).Replace( "}", "]" ) + "'</h5>" + rs; } tagFound = true; } } } while (tagFound); // pre processor tag found // if (webServiceConfig.CacheEnable) { PutWebFileCache(requestedFile, body, context.Response.ContentEncoding); } // WebServiceUtility.WriteStringToContext(context, body); } catch (Exception ex) { // TODO: report internal mig interface error context.Response.StatusCode = 500; WebServiceUtility.WriteStringToContext(context, ex.Message + "\n" + ex.StackTrace); Console.WriteLine("\nMIGService ERROR: " + ex.Message + "\n" + ex.StackTrace + "\n"); } } else { WebServiceUtility.WriteBytesToContext(context, System.IO.File.ReadAllBytes(requestedFile)); } } } else { // Try processing as MigInterface Api or Web Service Dynamic Api object responseObject = null; //domain == HomeAutomation._Interface_ call InterfaceControl var result = (from miginterface in Interfaces.Values let ns = miginterface.GetType().Namespace let domain = ns.Substring(ns.LastIndexOf(".") + 1) + "." + miginterface.GetType().Name where (command.Domain != null && command.Domain.StartsWith(domain)) select miginterface).FirstOrDefault(); if (result != null) { try { responseObject = result.InterfaceControl(command); } catch (Exception ex) { // TODO: report internal mig interface error context.Response.StatusCode = 500; responseObject = ex.Message + "\n" + ex.StackTrace; } } // if (responseObject == null || responseObject.Equals(String.Empty)) { var postData = new StreamReader(context.Request.InputStream).ReadToEnd(); if (!String.IsNullOrEmpty(postData)) { command.OriginalRequest += "/" + postData; } responseObject = WebServiceDynamicApiCall(command); } // if (responseObject != null && responseObject.GetType().Equals(typeof(string))) { command.Response = (string)responseObject; // // simple automatic json response type detection if (command.Response.StartsWith("[") && command.Response.EndsWith("]") || (command.Response.StartsWith("{") && command.Response.EndsWith("}"))) { context.Response.ContentType = "application/json"; context.Response.ContentEncoding = defaultWebFileEncoding; } } else { WebServiceUtility.WriteBytesToContext(context, (Byte[])responseObject); wroteBytes = true; } } // //POSTPROCESS if (ServiceRequestPostProcess != null) { ServiceRequestPostProcess(migRequest, command); if (!string.IsNullOrEmpty(command.Response) && !wroteBytes) { // request was handled by postprocess listener WebServiceUtility.WriteStringToContext(context, command.Response); return; } } }
static void Main(string[] args) { Console.WriteLine("***** Write the location *****\n"); string path = Console.ReadLine(); string[] files = Directory.GetFiles(path); for (int i = 0; i < files.Length; i++) { files[i] = Path.GetFileName(files[i]); } Console.WriteLine(path); foreach (var x in files) { Console.WriteLine(x); } Episode_det temp = new Episode_det(); for (int i = 0; i < files.Length; i++) { if (files[i].Substring(files[i].Length - 3) == "srt") { string[] ssize = files[i].Split(null); temp.series_name = ssize[0]; temp.series_no = Int32.Parse(ssize[2].Substring(0, 1)); temp.episode_no = Int32.Parse(ssize[2].Substring(2, 2)); temp.episode_name = ssize[4].Substring(0, ssize[4].IndexOf(".")); string sourceFile = Path.Combine(path, @"\", files[i]); System.IO.FileInfo fi = new System.IO.FileInfo(sourceFile); Console.WriteLine(sourceFile); if (fi.Exists) { string finalpath = Path.Combine(path, @"\", temp.series_name, " - ", "S0", temp.series_no.ToString(), "E", temp.episode_no.ToString(), " - ", temp.episode_name, ".srt"); fi.MoveTo(finalpath); } else { Console.WriteLine("foff3"); } string sourceFile2 = Path.Combine(path, @"\", temp.series_name, " ", "S0", temp.series_no.ToString(), "E", temp.episode_no.ToString(), ".mp4"); System.IO.FileInfo fi2 = new System.IO.FileInfo(sourceFile2); Console.WriteLine(sourceFile2); if (fi2.Exists) { string finalpath2 = Path.Combine(path, @"\", temp.series_name, " - ", "S0", temp.series_no.ToString(), "E", temp.episode_no.ToString(), " - ", temp.episode_name, ".mp4"); fi2.MoveTo(finalpath2); } else { Console.WriteLine("foff4"); } } } }
protected void Page_Load(object sender, EventArgs e) { CtlLib.SetUser(Session["APP_DBUSER"].ToString()); string p_dept_pk, p_work_mon, p_from_dt, p_to_dt, p_nation, p_group_pk, p_meal_emp_type; p_dept_pk = Request["l_tco_dept_pk"].ToString(); p_group_pk = Request["l_thr_group_pk"].ToString(); p_work_mon = Request["l_work_mon"].ToString(); p_to_dt = Request["l_to_dt"].ToString(); p_from_dt = Request["l_from_dt"].ToString(); p_meal_emp_type = Request["l_meal_emp_type"].ToString(); string TemplateFile = "rpt_chrm00020_2.xls"; string TempFile = "../../../../system/temp/rpt_chrm00020_2_" + Session["User_ID"].ToString() + ".xls"; TemplateFile = Server.MapPath(TemplateFile); TempFile = Server.MapPath(TempFile); //Create a new workbook IWorkbook exBook = NativeExcel.Factory.OpenWorkbook(TemplateFile); //Add worksheet IWorksheet exSheet = exBook.Worksheets[1]; string SQL_CODE = "SELECT MAX(CASE WHEN NUM_1 = 1 THEN NVL(NUM_2,0) ELSE 0 END) " + " ,MAX(CASE WHEN NUM_1 = 2 THEN NVL(NUM_2,0) ELSE 0 END) " + " FROM vhr_hr_code c " + " WHERE id = 'HR0191' "; DataTable dt_hr_code = CtlLib.TableReadOpen(SQL_CODE); double meal_main_amt = double.Parse(dt_hr_code.Rows[0][0].ToString()); double snack_time_amt = double.Parse(dt_hr_code.Rows[0][1].ToString()); int ncal = int.Parse(p_to_dt.Substring(6, 2).ToString()) - int.Parse(p_from_dt.Substring(6, 2).ToString()) + 1; int i; //====================================================================================================================== string SQL_1 = " SELECT 1 seq,'',MAX(( SELECT g.ORG_NM " + " FROM TCO_ORG g " + " WHERE g.del_if = 0 AND G.ORG_TYPE = '06' " + " START WITH g.pk = b.pk " + " CONNECT BY PRIOR g.p_pk = g.pk)) div_nm " + " ,B.ORG_NM org_nm " + " ,C.WORKGROUP_NM group_nm " + " ,D.EMP_ID EMP_ID " + " ,D.FULL_NAME " + " ,TO_CHAR (TO_DATE (D.JOIN_DT, 'yyyymmdd'), 'dd/mm/yyyy') join_dt " + " ,SUM (CASE WHEN F.WORK_DT_OF_SHIFT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + 0,'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 1 THEN 1 ELSE 0 END ELSE 0 END) MEAL_MAIN_QTY " + " ,SUM (CASE WHEN F.WORK_DT_OF_SHIFT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + 0,'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 1 THEN 1 ELSE 0 END * " + meal_main_amt + " ELSE 0 END) MEAL_MAIN_AMT " + " ,SUM (CASE WHEN F.WORK_DT_OF_SHIFT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + 0,'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 2 THEN 1 ELSE 0 END ELSE 0 END) SNACK_TIME_QTY " + " ,SUM (CASE WHEN F.WORK_DT_OF_SHIFT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + 0,'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 2 THEN 1 ELSE 0 END * " + snack_time_amt + " ELSE 0 END) SNACK_TIME_AMT "; for (i = 1; i < ncal; i++) { SQL_1 = SQL_1 + " ,SUM (CASE WHEN F.WORK_DT_OF_SHIFT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + " + i + ",'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 1 THEN 1 ELSE 0 END ELSE 0 END) MEAL_MAIN_QTY " + " ,SUM (CASE WHEN F.WORK_DT_OF_SHIFT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + " + i + ",'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 1 THEN 1 ELSE 0 END * " + meal_main_amt + " ELSE 0 END) MEAL_MAIN_AMT " + " ,SUM (CASE WHEN F.WORK_DT_OF_SHIFT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + " + i + ",'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 2 THEN 1 ELSE 0 END ELSE 0 END) SNACK_TIME_QTY " + " ,SUM (CASE WHEN F.WORK_DT_OF_SHIFT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + " + i + ",'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 2 THEN 1 ELSE 0 END * " + snack_time_amt + " ELSE 0 END) SNACK_TIME_AMT "; } SQL_1 = SQL_1 + " FROM THR_MEAL_CHECKING F, TCO_ORG B, THR_WORK_GROUP C, THR_EMPLOYEE D " + " WHERE F.DEL_IF = 0 AND B.DEL_IF = 0 AND C.DEL_IF =0 AND D.DEL_IF =0 " + " AND F.THR_EMP_PK = d.pk " + " AND F.TCO_ORG_PK = b.pk " + " and D.THR_WG_PK = c.pk " + " AND F.WORK_DT_OF_SHIFT BETWEEN '" + p_from_dt + "' AND '" + p_to_dt + "' " + " AND F.MEAL_TIMES IS NOT NULL " + " AND F.MEAL_EMP_TYPE = 'IN' " + " AND DECODE ('" + p_group_pk + "', 'ALL', 'ALL', D.THR_WG_PK) = '" + p_group_pk + "' " + " AND D.TCO_ORG_PK IN " + " ( SELECT g.pk " + " FROM TCO_ORG g " + " WHERE g.del_if = 0 " + " START WITH g.pk = " + " CASE " + " WHEN '" + p_dept_pk + "' = 'ALL' THEN g.pk " + " ELSE TO_NUMBER ('" + p_dept_pk + "') " + " END " + " CONNECT BY PRIOR g.pk = g.p_pk) " + " GROUP BY D.EMP_ID,B.ORG_NM,C.WORKGROUP_NM,D.FULL_NAME,D.JOIN_DT " + " ORDER BY seq,div_nm,org_nm,EMP_ID "; //====================================================================================================================== string SQL_2 = " SELECT 2 seq,'','' div_nm " + " ,'' org_nm " + " ,'' group_nm " + " ,F.EMP_ID EMP_ID " + " ,F.FULL_NAME " + " ,'' join_dt " + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + 0,'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 1 THEN 1 ELSE 0 END ELSE 0 END) MEAL_MAIN_QTY " + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + 0,'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 1 THEN 1 ELSE 0 END * " + meal_main_amt + " ELSE 0 END) MEAL_MAIN_AMT " + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + 0,'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 2 THEN 1 ELSE 0 END ELSE 0 END) SNACK_TIME_QTY " + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + 0,'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 2 THEN 1 ELSE 0 END * " + snack_time_amt + " ELSE 0 END) SNACK_TIME_AMT "; for (i = 1; i < ncal; i++) { SQL_2 = SQL_2 + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + " + i + ",'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 1 THEN 1 ELSE 0 END ELSE 0 END) MEAL_MAIN_QTY " + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + " + i + ",'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 1 THEN 1 ELSE 0 END * " + meal_main_amt + " ELSE 0 END) MEAL_MAIN_AMT " + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + " + i + ",'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 2 THEN 1 ELSE 0 END ELSE 0 END) SNACK_TIME_QTY " + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + " + i + ",'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 2 THEN 1 ELSE 0 END * " + snack_time_amt + " ELSE 0 END) SNACK_TIME_AMT "; } SQL_2 = SQL_2 + " FROM THR_MEAL_CHECKING F " + " WHERE F.DEL_IF = 0 " + " AND F.WORK_DT BETWEEN '" + p_from_dt + "' AND '" + p_to_dt + "' " + " AND F.MEAL_TIMES IS NOT NULL " + " AND F.MEAL_EMP_TYPE = 'OUT' " + " GROUP BY F.EMP_ID,F.FULL_NAME " + " ORDER BY seq,div_nm,org_nm,EMP_ID "; //====================================================================================================================== string SQL_3 = " SELECT 3 seq,'','' div_nm " + " ,'' org_nm " + " ,'' group_nm " + " ,'' EMP_ID " + " ,F.VISITOR_NM " + " ,'' join_dt " + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + 0,'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 1 THEN NVL(F.MEAL_QTY,0) ELSE 0 END ELSE 0 END) MEAL_MAIN_QTY " + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + 0,'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 1 THEN NVL(F.MEAL_QTY,0) ELSE 0 END * " + meal_main_amt + " ELSE 0 END) MEAL_MAIN_AMT " + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + 0,'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 2 THEN NVL(F.MEAL_QTY,0) ELSE 0 END ELSE 0 END) SNACK_TIME_QTY " + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + 0,'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 2 THEN NVL(F.MEAL_QTY,0) ELSE 0 END * " + snack_time_amt + " ELSE 0 END) SNACK_TIME_AMT "; for (i = 1; i < ncal; i++) { SQL_3 = SQL_3 + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + " + i + ",'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 1 THEN NVL(F.MEAL_QTY,0) ELSE 0 END ELSE 0 END) MEAL_MAIN_QTY " + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + " + i + ",'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 1 THEN NVL(F.MEAL_QTY,0) ELSE 0 END * " + meal_main_amt + " ELSE 0 END) MEAL_MAIN_AMT " + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + " + i + ",'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 2 THEN NVL(F.MEAL_QTY,0) ELSE 0 END ELSE 0 END) SNACK_TIME_QTY " + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + " + i + ",'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 2 THEN NVL(F.MEAL_QTY,0) ELSE 0 END * " + snack_time_amt + " ELSE 0 END) SNACK_TIME_AMT "; } SQL_3 = SQL_3 + " FROM THR_MEAL_VISITOR F " + " WHERE F.DEL_IF = 0 " + " AND F.WORK_DT BETWEEN '" + p_from_dt + "' AND '" + p_to_dt + "' " + " AND F.MEAL_TIMES IS NOT NULL " + " GROUP BY F.VISITOR_NM " + " ORDER BY seq,div_nm,org_nm,EMP_ID "; //====================================================================================================================== string SQL_ALL = " SELECT 1 seq,'',MAX(( SELECT g.ORG_NM " + " FROM TCO_ORG g " + " WHERE g.del_if = 0 AND G.ORG_TYPE = '06' " + " START WITH g.pk = b.pk " + " CONNECT BY PRIOR g.p_pk = g.pk)) div_nm " + " ,B.ORG_NM org_nm " + " ,C.WORKGROUP_NM group_nm " + " ,D.EMP_ID EMP_ID " + " ,D.FULL_NAME " + " ,TO_CHAR (TO_DATE (D.JOIN_DT, 'yyyymmdd'), 'dd/mm/yyyy') join_dt " + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + 0,'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 1 THEN 1 ELSE 0 END ELSE 0 END) MEAL_MAIN_QTY " + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + 0,'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 1 THEN 1 ELSE 0 END * " + meal_main_amt + " ELSE 0 END) MEAL_MAIN_AMT " + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + 0,'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 2 THEN 1 ELSE 0 END ELSE 0 END) SNACK_TIME_QTY " + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + 0,'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 2 THEN 1 ELSE 0 END * " + snack_time_amt + " ELSE 0 END) SNACK_TIME_AMT "; for (i = 1; i < ncal; i++) { SQL_ALL = SQL_ALL + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + " + i + ",'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 1 THEN 1 ELSE 0 END ELSE 0 END) MEAL_MAIN_QTY " + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + " + i + ",'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 1 THEN 1 ELSE 0 END * " + meal_main_amt + " ELSE 0 END) MEAL_MAIN_AMT " + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + " + i + ",'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 2 THEN 1 ELSE 0 END ELSE 0 END) SNACK_TIME_QTY " + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + " + i + ",'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 2 THEN 1 ELSE 0 END * " + snack_time_amt + " ELSE 0 END) SNACK_TIME_AMT "; } SQL_ALL = SQL_ALL + " FROM THR_MEAL_CHECKING F, TCO_ORG B, THR_WORK_GROUP C, THR_EMPLOYEE D " + " WHERE F.DEL_IF = 0 AND B.DEL_IF = 0 AND C.DEL_IF =0 AND D.DEL_IF =0 " + " AND F.THR_EMP_PK = d.pk " + " AND F.TCO_ORG_PK = b.pk " + " and D.THR_WG_PK = c.pk " + " AND F.WORK_DT BETWEEN '" + p_from_dt + "' AND '" + p_to_dt + "' " + " AND F.MEAL_TIMES IS NOT NULL " + " AND F.MEAL_EMP_TYPE = 'IN' " + " AND DECODE ('" + p_group_pk + "', 'ALL', 'ALL', D.THR_WG_PK) = '" + p_group_pk + "' " + " AND D.TCO_ORG_PK IN " + " ( SELECT g.pk " + " FROM TCO_ORG g " + " WHERE g.del_if = 0 " + " START WITH g.pk = " + " CASE " + " WHEN '" + p_dept_pk + "' = 'ALL' THEN g.pk " + " ELSE TO_NUMBER ('" + p_dept_pk + "') " + " END " + " CONNECT BY PRIOR g.pk = g.p_pk) " + " GROUP BY D.EMP_ID,B.ORG_NM,C.WORKGROUP_NM,D.FULL_NAME,D.JOIN_DT " + " UNION ALL " + " SELECT 2 seq,'','' div_nm " + " ,'' org_nm " + " ,'' group_nm " + " ,F.EMP_ID EMP_ID " + " ,F.FULL_NAME " + " ,'' join_dt " + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + 0,'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 1 THEN 1 ELSE 0 END ELSE 0 END) MEAL_MAIN_QTY " + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + 0,'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 1 THEN 1 ELSE 0 END * " + meal_main_amt + " ELSE 0 END) MEAL_MAIN_AMT " + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + 0,'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 2 THEN 1 ELSE 0 END ELSE 0 END) SNACK_TIME_QTY " + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + 0,'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 2 THEN 1 ELSE 0 END * " + snack_time_amt + " ELSE 0 END) SNACK_TIME_AMT "; for (i = 1; i < ncal; i++) { SQL_ALL = SQL_ALL + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + " + i + ",'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 1 THEN 1 ELSE 0 END ELSE 0 END) MEAL_MAIN_QTY " + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + " + i + ",'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 1 THEN 1 ELSE 0 END * " + meal_main_amt + " ELSE 0 END) MEAL_MAIN_AMT " + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + " + i + ",'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 2 THEN 1 ELSE 0 END ELSE 0 END) SNACK_TIME_QTY " + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + " + i + ",'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 2 THEN 1 ELSE 0 END * " + snack_time_amt + " ELSE 0 END) SNACK_TIME_AMT "; } SQL_ALL = SQL_ALL + " FROM THR_MEAL_CHECKING F " + " WHERE F.DEL_IF = 0 " + " AND F.WORK_DT BETWEEN '" + p_from_dt + "' AND '" + p_to_dt + "' " + " AND F.MEAL_TIMES IS NOT NULL " + " AND F.MEAL_EMP_TYPE = 'OUT' " + " GROUP BY F.EMP_ID,F.FULL_NAME " + " UNION ALL " + " SELECT 3 seq,'','' div_nm " + " ,'' org_nm " + " ,'' group_nm " + " ,'' EMP_ID " + " ,F.VISITOR_NM " + " ,'' join_dt " + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + 0,'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 1 THEN NVL(F.MEAL_QTY,0) ELSE 0 END ELSE 0 END) MEAL_MAIN_QTY " + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + 0,'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 1 THEN NVL(F.MEAL_QTY,0) ELSE 0 END * " + meal_main_amt + " ELSE 0 END) MEAL_MAIN_AMT " + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + 0,'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 2 THEN NVL(F.MEAL_QTY,0) ELSE 0 END ELSE 0 END) SNACK_TIME_QTY " + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + 0,'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 2 THEN NVL(F.MEAL_QTY,0) ELSE 0 END * " + snack_time_amt + " ELSE 0 END) SNACK_TIME_AMT "; for (i = 1; i < ncal; i++) { SQL_ALL = SQL_ALL + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + " + i + ",'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 1 THEN NVL(F.MEAL_QTY,0) ELSE 0 END ELSE 0 END) MEAL_MAIN_QTY " + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + " + i + ",'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 1 THEN NVL(F.MEAL_QTY,0) ELSE 0 END * " + meal_main_amt + " ELSE 0 END) MEAL_MAIN_AMT " + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + " + i + ",'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 2 THEN NVL(F.MEAL_QTY,0) ELSE 0 END ELSE 0 END) SNACK_TIME_QTY " + " ,SUM (CASE WHEN F.WORK_DT = TO_CHAR(TO_DATE('" + p_from_dt + "','yyyymmdd') + " + i + ",'yyyymmdd') THEN CASE WHEN F.MEAL_TYPE = 2 THEN NVL(F.MEAL_QTY,0) ELSE 0 END * " + snack_time_amt + " ELSE 0 END) SNACK_TIME_AMT "; } SQL_ALL = SQL_ALL + " FROM THR_MEAL_VISITOR F " + " WHERE F.DEL_IF = 0 " + " AND F.WORK_DT BETWEEN '" + p_from_dt + "' AND '" + p_to_dt + "' " + " AND F.MEAL_TIMES IS NOT NULL " + " GROUP BY F.VISITOR_NM " + " ORDER BY seq,div_nm,org_nm,EMP_ID "; string SQL; if (p_meal_emp_type == "IN") { SQL = SQL_1; } else if (p_meal_emp_type == "OUT") { SQL = SQL_2; } else if (p_meal_emp_type == "VIS") { SQL = SQL_3; } else { SQL = SQL_ALL; } //Response.Write(SQL); //Response.End(); DataTable dt_emp = CtlLib.TableReadOpen(SQL); int irow = dt_emp.Rows.Count; int icol = dt_emp.Columns.Count; if (irow == 0) { Response.Write("There is no data."); Response.End(); } //Khai bao bien int j, k, pos = 6; int ntotal = icol - 8, nseq = 0; //8 cot khong sum double[] s_total = new double[ntotal]; double[] g_total = new double[ntotal]; int ncount = 0; for (j = 0; j < ntotal; j++) { s_total[j] = 0; g_total[j] = 0; } //Dem so luong thay doi meal type for (i = 0; i < irow - 1; i++) { if (dt_emp.Rows[i]["seq"].ToString() != dt_emp.Rows[i + 1]["seq"].ToString()) { nseq++; } } //Insert new row for (i = 0; i < irow - 1 + nseq; i++) { exSheet.Range[pos + 1, 1].Rows.EntireRow.Insert(); } //Title value exSheet.Cells["BL2"].Value = "Month: " + p_work_mon.Substring(4, 2).ToString() + "/" + p_work_mon.Substring(0, 4).ToString(); //Show data for (i = 0; i < irow; i++) { for (k = 0; k < ntotal; k++) { s_total[k] = s_total[k] + double.Parse(dt_emp.Rows[i][k + 8].ToString()); g_total[k] = g_total[k] + double.Parse(dt_emp.Rows[i][k + 8].ToString()); } ncount++; exSheet.Cells[pos + i, 1].Value = ncount; for (j = 2; j < icol; j++) { if (j <= 7) { exSheet.Cells[pos + i, j].Value = dt_emp.Rows[i][j].ToString(); } else { exSheet.Cells[pos + i, j].Value = double.Parse(dt_emp.Rows[i][j].ToString()); } } //Dong sub total if (i == irow - 1) { exSheet.Cells[pos + i + 1, 1].Value = "Total " + ncount + " employees"; for (k = 0; k < ntotal; k++) { exSheet.Cells[pos + i + 1, k + 8].Value = s_total[k]; exSheet.Cells[pos + i + 2, k + 8].Value = g_total[k]; } } else if (dt_emp.Rows[i]["seq"].ToString() != dt_emp.Rows[i + 1]["seq"].ToString()) { exSheet.Cells[pos + i + 1, 1, pos + i + 1, 7].Merge(); exSheet.Cells[pos + i + 1, 1, pos + i + 1, icol].Font.Bold = true; exSheet.Cells[pos + i + 1, 1].HorizontalAlignment = XlHAlign.xlHAlignCenter; exSheet.Cells[pos + i + 1, 1].Value = "Total " + ncount + " employees"; for (k = 0; k < ntotal; k++) { exSheet.Cells[pos + i + 1, k + 8].Value = s_total[k]; s_total[k] = 0; } ncount = 0; pos++; } } //Xóa cột dư ở những tháng không đủ 31 ngày int ndel = 0; //so luong ngày can xoa int cdel = 0; //vi tri cot can xoa ndel = 31 - ncal; cdel = ncal * 4 + 7; for (i = 0; i < ndel * 4; i++) { exSheet.Range[1, cdel + 1].Columns.EntireColumn.Delete(); exSheet.Range[1, cdel + 1].Columns.EntireColumn.Delete(); } // end loop detail percent if (File.Exists(TempFile)) { File.Delete(TempFile); } // hide row firts //range = exSheet.Range["A1"]; // hide row A5 //range.Rows.Hidden = true; exBook.SaveAs(TempFile); //CtlLib.ExcelToPdf(TempFile); //string pdfFilePath = TempFile.Replace(".xls", ".pdf"); //write out to client broswer System.IO.FileInfo file = new System.IO.FileInfo(TempFile); //System.IO.FileInfo file = new System.IO.FileInfo(pdfFilePath); Response.Clear(); Response.Charset = "UTF-8"; Response.ContentEncoding = System.Text.Encoding.UTF8; //Add header, give a default file name for "File Download/Store as" Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name)); //Add header, set file size to enable browser display download progress Response.AddHeader("Content-Length", file.Length.ToString()); //Set the return string is unavailable reading for client, and must be downloaded Response.ContentType = "application/ms-exSheet"; //Response.ContentType = "application/pdf"; //Send file string to client Response.WriteFile(TempFile); //Response.WriteFile(pdfFilePath); //Stop execute Response.End(); }
/// <summary> /// Adds the console, debugger, file, or host listener if requested. /// </summary> internal void AddTraceListenersToSources(Collection <PSTraceSource> matchingSources) { if (DebuggerListener) { if (_defaultListener == null) { _defaultListener = new DefaultTraceListener(); // Note, this is not meant to be localized. _defaultListener.Name = "Debug"; } AddListenerToSources(matchingSources, _defaultListener); } if (PSHostListener) { if (_hostListener == null) { ((MshCommandRuntime)this.CommandRuntime).DebugPreference = ActionPreference.Continue; _hostListener = new PSHostTraceListener(this); // Note, this is not meant to be localized. _hostListener.Name = "Host"; } AddListenerToSources(matchingSources, _hostListener); } if (FileListener != null) { if (_fileListeners == null) { _fileListeners = new Collection <TextWriterTraceListener>(); FileStreams = new Collection <FileStream>(); Exception error = null; try { Collection <string> resolvedPaths = new Collection <string>(); try { // Resolve the file path ProviderInfo provider = null; resolvedPaths = this.SessionState.Path.GetResolvedProviderPathFromPSPath(FileListener, out provider); // We can only export aliases to the file system if (!provider.NameEquals(this.Context.ProviderNames.FileSystem)) { throw new PSNotSupportedException( StringUtil.Format(TraceCommandStrings.TraceFileOnly, FileListener, provider.FullName)); } } catch (ItemNotFoundException) { // Since the file wasn't found, just make a provider-qualified path out if it // and use that. PSDriveInfo driveInfo = null; ProviderInfo provider = null; string path = this.SessionState.Path.GetUnresolvedProviderPathFromPSPath( FileListener, new CmdletProviderContext(this.Context), out provider, out driveInfo); // We can only export aliases to the file system if (!provider.NameEquals(this.Context.ProviderNames.FileSystem)) { throw new PSNotSupportedException( StringUtil.Format(TraceCommandStrings.TraceFileOnly, FileListener, provider.FullName)); } resolvedPaths.Add(path); } if (resolvedPaths.Count > 1) { throw new PSNotSupportedException(StringUtil.Format(TraceCommandStrings.TraceSingleFileOnly, FileListener)); } string resolvedPath = resolvedPaths[0]; Exception fileOpenError = null; try { if (ForceWrite && System.IO.File.Exists(resolvedPath)) { // remove readonly attributes on the file System.IO.FileInfo fInfo = new System.IO.FileInfo(resolvedPath); if (fInfo != null) { // Save some disk write time by checking whether file is readonly.. if ((fInfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { // Make sure the file is not read only fInfo.Attributes &= ~(FileAttributes.ReadOnly); } } } // Trace commands always append..So there is no need to set overwrite with force.. FileStream fileStream = new FileStream(resolvedPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite); FileStreams.Add(fileStream); // Open the file stream TextWriterTraceListener fileListener = new TextWriterTraceListener(fileStream, resolvedPath); fileListener.Name = FileListener; _fileListeners.Add(fileListener); } catch (IOException ioException) { fileOpenError = ioException; } catch (SecurityException securityException) { fileOpenError = securityException; } catch (UnauthorizedAccessException unauthorized) { fileOpenError = unauthorized; } if (fileOpenError != null) { ErrorRecord errorRecord = new ErrorRecord( fileOpenError, "FileListenerPathResolutionFailed", ErrorCategory.OpenError, resolvedPath); WriteError(errorRecord); } } catch (ProviderNotFoundException providerNotFound) { error = providerNotFound; } catch (System.Management.Automation.DriveNotFoundException driveNotFound) { error = driveNotFound; } catch (NotSupportedException notSupported) { error = notSupported; } if (error != null) { ErrorRecord errorRecord = new ErrorRecord( error, "FileListenerPathResolutionFailed", ErrorCategory.InvalidArgument, FileListener); WriteError(errorRecord); } } foreach (TraceListener listener in _fileListeners) { AddListenerToSources(matchingSources, listener); } } }
// function to add files and folders recursively private bool AddFileOrFolderRecursive(FolderTreeNode parentNode, String path) { // if path is a file if (File.Exists(path)) { VirtFsNode virtFsFileNode; FileData fileOverwrite = null; if (parentNode.childFiles != null) { foreach (FileData file in parentNode.childFiles) { if (!file.deleted && Path.GetFileName(file.virtFsNode.FileName).Equals(Path.GetFileName(path), StringComparison.CurrentCultureIgnoreCase)) { if (MessageBox.Show(String.Format("File \"{0}\" already exists, overwrite?", file.virtFsNode.FileName), "Overwrite?", MessageBoxButtons.YesNo) == DialogResult.No) { return(false); } else { if ((file.addedFrom != "")) { fileOverwrite = file; } else { file.deleted = true; } break; } } } } virtFsFileNode = new VirtFsNode(); #pragma warning disable 1690 virtFsFileNode.FileName = TreeHelper.FullPath(parentNode.virtFsNode.FileName, Path.GetFileName(path)); #pragma warning restore 1690 virtFsFileNode.FileFlags = VIRT_FILE_FLAGS.ISFILE; //it's a file if (Path.GetExtension(virtFsFileNode.FileName).Equals(".dll")) { virtFsFileNode.FileFlags |= VIRT_FILE_FLAGS.DEPLOY_UPON_PRELOAD; } System.IO.FileInfo fi = new System.IO.FileInfo(path); virtFsFileNode.EndOfFile = (ulong)fi.Length; if (fileOverwrite != null) { fileOverwrite.virtFsNode = virtFsFileNode; } else { AddFileOrFolder(virtFsFileNode, path); // Also sets dirty = true } if (parentNode == fsFolderTree.SelectedNode) { RefreshFolderNodeRecursively(parentNode, 0); TreeViewEventArgs ev = new TreeViewEventArgs(parentNode); OnFolderTreeSelect(null, ev); } return(true); } if (!Directory.Exists(path)) { return(false); } FolderTreeNode folderOverwrite = null; //foreach (String subdir in subdirs) { foreach (FolderTreeNode childNode in parentNode.Nodes) { if (childNode.Text.Equals(Path.GetFileName(path), StringComparison.CurrentCultureIgnoreCase)) { #pragma warning disable 1690 if (!childNode.deleted && MessageBox.Show(String.Format("Folder \"{0}\" already exists, overwrite?", childNode.virtFsNode.FileName), "Overwrite?", MessageBoxButtons.YesNo) == DialogResult.No) #pragma warning restore 1690 { return(false); } else { folderOverwrite = childNode; childNode.deleted = false; if (childNode.childFiles != null) { foreach (FileData file in childNode.childFiles) { file.deleted = true;// make sure files from a previously deleted folder dont come back.. } } break; } } } } String[] lsFiles = Directory.GetFiles(path); String[] lsDirs = Directory.GetDirectories(path); FolderTreeNode subdirNode; if (folderOverwrite == null) { // if path is a folder VirtFsNode virtFsDirNode = new VirtFsNode(); #pragma warning disable 1690 virtFsDirNode.FileName = TreeHelper.FullPath(parentNode.virtFsNode.FileName, Path.GetFileName(path)); #pragma warning restore 1690 virtFsDirNode.FileFlags = 0; //it's a dir subdirNode = AddFileOrFolder(virtFsDirNode, path); // Also sets dirty = true } else { subdirNode = folderOverwrite; } foreach (String file in lsFiles) { if (!AddFileOrFolderRecursive(subdirNode, file)) { return(false); } } foreach (String dir in lsDirs) { if (!AddFileOrFolderRecursive(subdirNode, dir)) { return(false); } } if (parentNode == fsFolderTree.SelectedNode) { RefreshFolderNodeRecursively(parentNode, 0); TreeViewEventArgs ev = new TreeViewEventArgs(parentNode); OnFolderTreeSelect(null, ev); } return(true); }
private void GenerateContent() { try { sb = new StringBuilder(); sb.AppendLine("--Generated Upgrade For Version " + _model.Version + "." + _model.GeneratedVersion); sb.AppendLine("--Generated on " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); sb.AppendLine(); //*********************************************************** //ATTEMPT TO GENERATE AN UPGRADE SCRIPT FROM PREVIOUS VERSION //*********************************************************** #region Generate Upgrade Script //Find the previous model file if one exists var fileName = this._model.GeneratorProject.FileName; var prevFileName = fileName + ".sql.lastgen"; var fiPrev = new System.IO.FileInfo(prevFileName); var fi = new System.IO.FileInfo(fileName); if (fiPrev.Exists) { var newFileName = string.Format(fileName, "sql."); //Rename old style to new style if (File.Exists(prevFileName) && !File.Exists(fileName)) { File.Move(fileName, newFileName); } fileName = newFileName; fi = new System.IO.FileInfo(fileName); if (fi.Exists) { var newFile = fileName + ".converting"; if (File.Exists(newFile)) { File.Delete(newFile); System.Threading.Thread.Sleep(250); } File.Copy(fileName, newFile); var fileText = File.ReadAllText(newFile); fileText = fileText.Replace("Widgetsphere.Generator.", "nHydrate.Generator."); fileText = fileText.Replace("WidgetsphereGeneratorProject", "nHydrateGeneratorProject"); File.WriteAllText(newFile, fileText); System.Threading.Thread.Sleep(500); //Load the previous model var generator = nHydrate.Generator.Common.GeneratorFramework.GeneratorHelper.OpenModel(prevFileName); var oldRoot = generator.Model as ModelRoot; sb.Append(SqlHelper.GetModelDifferenceSql(oldRoot, _model)); if (File.Exists(newFile)) { File.Delete(newFile); } //Copy the current LASTGEN file to BACKUP //fi.CopyTo(fileName + ".bak", true); } } //Just in case it was there, but there is already a new file name, just remove it if (File.Exists(prevFileName)) { File.Delete(prevFileName); } //Save this version on top of the old version var currentFile = new System.IO.FileInfo(this._model.GeneratorProject.FileName); currentFile.CopyTo(prevFileName, true); #endregion } catch (Exception ex) { throw; } }
//[TestMethod] public void RunPerformanceComparison() { //string testfilesDirectory = @"C:\Users\margus\Desktop\IJCAR12\proceedings"; string testfilesDirectory = "../../../GeneratedCodeSamples/SampleTexts"; var someTestFiles = System.IO.Directory.GetFiles(testfilesDirectory); int decodeTimeSystem_tot = 0; int decodeTimeSystemWeb_tot = 0; int decodeTimeA_tot = 0; int decodeTimeS_tot = 0; long totsize = 0; int someTestFileNr = 0; while (totsize < 100000000) { string file = someTestFiles[someTestFileNr]; someTestFileNr = (someTestFileNr + 1) % someTestFiles.Length; int LIMIT = 1000000; var fi = new System.IO.FileInfo(file); var size = fi.Length; string content = "<" + System.IO.File.ReadAllText(file, Encoding.UTF8) + ">"; string encoded = HtmlEncodeStrict.Apply(content); string decoded_System = ""; string decoded_SystemWeb = ""; string decoded_A = ""; string decoded_S = ""; //--- decode with system int decodeTimeSystemNet = System.Environment.TickCount; for (long K = 0; K < LIMIT; K += size) { decoded_System = System.Net.WebUtility.HtmlDecode(encoded); totsize += size; } decodeTimeSystemNet = System.Environment.TickCount - decodeTimeSystemNet; int decodeTimeSystemWeb = System.Environment.TickCount; for (long K = 0; K < LIMIT; K += size) { decoded_SystemWeb = System.Web.HttpUtility.HtmlDecode(encoded); } decodeTimeSystemWeb = System.Environment.TickCount - decodeTimeSystemWeb; //--- decode with methB (using StringBuilder) int decodeTimeS = System.Environment.TickCount; for (long K = 0; K < LIMIT; K += size) { decoded_S = HtmlDecodeS.Apply(encoded); } decodeTimeS = System.Environment.TickCount - decodeTimeS; //--- decode with methA (using Array) int decodeTimeA = System.Environment.TickCount; for (long K = 0; K < LIMIT; K += size) { decoded_A = HtmlDecodeA.Apply(encoded); } decodeTimeA = System.Environment.TickCount - decodeTimeA; //--- summary of times //string summary = string.Format("{0}: System:{1}ms, methA:{2}ms, methS:{3}ms", fi.Name, decodeTimeSystem, decodeTimeA, decodeTimeS); //Console.WriteLine(summary); //--- validate outputs Assert.AreEqual <string>(decoded_System, decoded_SystemWeb); if (!decoded_System.Equals(decoded_A)) { for (int i = 0; i < decoded_System.Length; i++) { if (decoded_System[i] != decoded_A[i]) { Assert.Fail(); } } } Assert.AreEqual <string>(decoded_System, decoded_S); decodeTimeSystem_tot += decodeTimeSystemNet; decodeTimeSystemWeb_tot += decodeTimeSystemWeb; decodeTimeA_tot += decodeTimeA; decodeTimeS_tot += decodeTimeS; } string summary_tot = string.Format("{0}MB: System.Net.WebUtility.HtmlDecode:{1}ms, System.Web.HttpUtility.HtmlDecode:{4}, methA:{2}ms, methS:{3}ms", totsize / 1000000, decodeTimeSystem_tot, decodeTimeA_tot, decodeTimeS_tot, decodeTimeSystemWeb_tot); Console.WriteLine(summary_tot); }
public static void TraverseTree(string root) { // Data structure to hold names of subfolders to be // examined for files. Stack <string> dirs = new Stack <string>(20); if (!System.IO.Directory.Exists(root)) { throw new ArgumentException(); } dirs.Push(root); while (dirs.Count > 0) { string currentDir = dirs.Pop(); string[] subDirs; try { subDirs = System.IO.Directory.GetDirectories(currentDir); } // An UnauthorizedAccessException exception will be thrown if we do not have // discovery permission on a folder or file. It may or may not be acceptable // to ignore the exception and continue enumerating the remaining files and // folders. It is also possible (but unlikely) that a DirectoryNotFound exception // will be raised. This will happen if currentDir has been deleted by // another application or thread after our call to Directory.Exists. The // choice of which exceptions to catch depends entirely on the specific task // you are intending to perform and also on how much you know with certainty // about the systems on which this code will run. catch (UnauthorizedAccessException e) { Console.WriteLine(e.Message); continue; } catch (System.IO.DirectoryNotFoundException e) { Console.WriteLine(e.Message); continue; } string[] files = null; try { files = System.IO.Directory.GetFiles(currentDir); } catch (UnauthorizedAccessException e) { Console.WriteLine(e.Message); continue; } catch (System.IO.DirectoryNotFoundException e) { Console.WriteLine(e.Message); continue; } // Perform the required action on each file here. // Modify this block to perform your required task. int counter = 0; foreach (string file in files) { counter++; try { // Perform whatever action is required in your scenario. System.IO.FileInfo fi = new System.IO.FileInfo(file); string contents = File.ReadAllText(file); contents = StripComments(contents); string pattern = @"namespace (.*);"; var NameSpace = PCRE.PcreRegex.Match(contents, pattern).ToArray(); //System.Data.DataTable results = DBStorage.SQLite.Query("namespaces", "SELECT id from namespaces where name='" + NameSpace[1] + "'"); //if (results != null && results.Rows.Count == 0) //{ // //DBStorage.SQLite.Query("namespaces", @"INSERT INTO namespaces VALUES(" + counter + ",'" + NameSpace[1] + "','" + fi.Name + "')"); //} pattern = @"use (.*);"; PcreMatch[] Dependencies = PCRE.PcreRegex.Matches(contents, pattern).ToArray(); var depList = String.Join(", ", Dependencies.AsEnumerable()); pattern = @"\s+(?<functionView>\w+)\s*function\s+(?<functionName>\w+)\s?(?<functionArguments>\(.*(?R)*\))\s*(?<functionBody>{(?:[^{}]+|(?-1))*+})?"; var PageFunctions = PCRE.PcreRegex.Matches(contents, pattern).ToArray(); string queries = ""; foreach (var function in PageFunctions) { string privacy = function[1]; string functionName = function[2]; string functionArguments = function[3]; string FunctionBody = function[4]; pattern = @"\s+(?<functionNameSpace>(?=[^\s\(\>])(\$this-\>)?([\w\d]*[\:|\\]{0,2}){0,4})(?=\s*\()"; var InternalFunctions = PCRE.PcreRegex.Matches(FunctionBody, pattern).ToArray(); int InternalFunctionsCount = 0; List <string> InternalFunctionsList = new List <string>(); if (InternalFunctions.Length > 0) { foreach (var func in InternalFunctions) { bool builtin = false; foreach (var builtInPHP in PHPFNames.php_functions) { if (builtInPHP == func[1]) { builtin = true; break; } } if (builtin == false) { InternalFunctionsList.Add(func[1]); } } InternalFunctionsList = InternalFunctionsList.Distinct().ToList(); InternalFunctionsCount = InternalFunctionsList.Count; } var InternalFunctionsListString = String.Join(", ", InternalFunctionsList.AsEnumerable()); //(?<functionName>(?=[^\(])([\w\d]*[:|\\]*)*[\w\d]*)\s?\((?<Arguments>.*)?\) queries += @"INSERT INTO code_objects (namespace,scope,name,args,body,total_using,using_list,internal_function_list,internal_function_count,filename) VALUES('" + NameSpace[1] + "','" + privacy.Replace("'", "''") + "','" + functionName.Replace("'", "''") + "','" + functionArguments.Replace("'", "''") + "','" + FunctionBody.Replace("'", "''") + "','" + Dependencies.Length + "','" + depList.Replace("'", "''") + "','" + InternalFunctionsListString + "','" + InternalFunctionsCount + "','" + file + "');"; } DBStorage.SQLite.Query("namespaces", queries); //System.Data.DataTable results2 = DBStorage.SQLite.Query("namespaces", "SELECT id,body from code_objects"); //if (results2 != null && results2.Rows.Count == 0) //{ // DBStorage.SQLite.Query("namespaces", @"INSERT INTO namespaces VALUES(" + counter + ",'" + NameSpace[1] + "','" + fi.Name + "')"); //} } catch (System.IO.FileNotFoundException e) { // If file was deleted by a separate application // or thread since the call to TraverseTree() // then just continue. Console.WriteLine(e.Message); continue; } } // Push the subdirectories onto the stack for traversal. // This could also be done before handing the files. foreach (string str in subDirs) { dirs.Push(str); } } }
/// <summary> /// Handle trace requests - typically during development, but may be turned on to track code flow in production. /// </summary> /// <param name="level"></param> /// <param name="message"></param> /// <param name="showingDatetime">If true, precede message with current date-time, otherwise just the message> The latter is useful for data dumps</param> public static void DoTrace(int level, string message, bool showingDatetime = true, string logPrefix = "") { //TODO: Future provide finer control at the control level string msg = ""; int appTraceLevel = UtilityManager.GetAppKeyValue("appTraceLevel", 6); //bool useBriefFormat = true; const int NumberOfRetries = 4; const int DelayOnRetry = 1000; if (showingDatetime) { msg = "\n " + System.DateTime.Now.ToString() + " - " + message; } else { msg = "\n " + message; } string datePrefix1 = System.DateTime.Today.ToString("u").Substring(0, 10); string datePrefix = System.DateTime.Today.ToString("yyyy-dd"); string logFile = UtilityManager.GetAppKeyValue("path.trace.log", ""); if (!string.IsNullOrWhiteSpace(logPrefix)) { datePrefix += "_" + logPrefix; } //Allow if the requested level is <= the application thresh hold if (string.IsNullOrWhiteSpace(logFile) || level > appTraceLevel) { return; } string outputFile = ""; if (message.IndexOf("UPPER CASE URI") > -1 || message.IndexOf("GRAPH URI") > -1) { logFile = logFile.Replace("[date]", "[date]_URI_ISSUES"); } //added retries where log file is in use for (int i = 1; i <= NumberOfRetries; ++i) { try { outputFile = logFile.Replace("[date]", datePrefix + (i < 3 ? "" : "_" + i.ToString())); if (File.Exists(outputFile)) { if (File.GetLastWriteTime(outputFile).Month != DateTime.Now.Month) { File.Delete(outputFile); } } else { System.IO.FileInfo f = new System.IO.FileInfo(outputFile); f.Directory.Create(); // If the directory already exists, this method does nothing. } StreamWriter file = File.AppendText(outputFile); file.WriteLine(msg); file.Close(); if (level > 0) { Console.WriteLine(msg); } break; } catch (IOException e) when(i <= NumberOfRetries) { // You may check error code to filter some exceptions, not every error // can be recovered. Thread.Sleep(DelayOnRetry); } catch (Exception ex) { //ignore errors } } }
/// <summary> /// Get file write time /// </summary> /// <param name="filename">file name</param> /// <returns></returns> public static System.DateTime GetWriteTime(string filename) { System.IO.FileInfo fi = new System.IO.FileInfo(filename); return(fi.LastWriteTime); }