// private static string logDirectory = ""; /// <summary> /// 记录异常 /// </summary> /// <param name="addr">引起异常的地址,比如网址</param> /// <param name="except"></param> public static void RecordException(string addr,Exception except) { if (PluginConfig.PLUGIN_LOG_OPENED) { Exception exc = except; DateTime dt = DateTime.Now; string dtStr = String.Format("{0:yyyyMMdd}", dt); string logDir = AppDomain.CurrentDomain.BaseDirectory + PluginConfig.PLUGIN_TMP_DIRECTORY + "logs"; //创建日志目录 if (!Directory.Exists(logDir)) { Directory.CreateDirectory(logDir).Create(); } LogFile logFile = new LogFile(logDir + "/" + dtStr + ".log"); if (exc.InnerException != null) { exc = except.InnerException; } Hashtable hash = new Hashtable(); hash.Add("addr", addr ?? "application"); hash.Add("message", exc.Message); hash.Add("stack", exc.StackTrace); hash.Add("time", String.Format("{0:yyyy-MM-dd HH:mm:ss}", dt)); hash.Add("source", exc.Source); //附加记录 logFile.Append(PluginConfig.PLUGIN_LOG_EXCEPT_FORMAT.Template(hash)); } throw except; //继续抛出异常 }
/// <summary> /// 日志记录 /// </summary> /// <param name="message">要写入消息</param> /// <param name="path">文件路径:C:\\Log.txt</param> public static void WriteLog(string message, LogFile logFile) { string pathFile = null; switch (logFile) { case LogFile.GetProxyIP: pathFile = "C:\\GreamGugGetProxyIP.txt"; break; case LogFile.SetIE: pathFile = "C:\\GreamGugProxies.txt"; break; case LogFile.ValidateProxy: pathFile = "C:\\GreamGugValidateProxy.txt"; break; default: pathFile = "C:\\GreamGugLog.txt"; break; } try { StreamWriter sw = new StreamWriter(pathFile, true, Encoding.UTF8); sw.WriteLine("{0} ---{1}", DateTime.Now.ToLongDateString(), message); sw.Close(); sw.Dispose(); } catch (IOException ex) { return; } }
//private void CreateLineIndexes(string fileName) //{ // var list = new List<int>(); // using (var reader = new StreamReader(fileName)) // { // string line; // while ((line = reader.ReadLine()) != null) // { // list.Add(line.Length); // } // } // MessageBox.Show(list.Count.ToString()); //} private void OpenFile(string fileName) { if (logFile != null) { logFile.Dispose(); } logFile = new LogFile(fileName); logControl.LogFile = logFile; ShowTail(); }
public MainWindow() { InitializeComponent(); lf = new LogFile(); ofd = new Microsoft.Win32.OpenFileDialog(); sfd = new Microsoft.Win32.SaveFileDialog(); EntriesView.ItemsSource = lf.m_entryList; PriorityFilterDD.ItemsSource = lf.m_listOfPriorities; }
public void Open(string logFilePath) { logFile = LogFile.LoadFrom(logFilePath); int pageSize = GetVisibleLines(); if (pageSize <= 1) { pageSize = 20; } lineList = new VirtualizingCollection<string>(new LogItemsProvider(logFile), pageSize); listBox.DataSource = lineList; }
public static FileStream GetFileStream(FileInfo file, LogFile logFile) { try { return file.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite); } catch (IOException ex) { logFile.WriteLog(ex.Message); logFile.Close(); System.Environment.Exit(404); return (FileStream)null; } }
public TerminalBox(TelnetSession session,bool LogFileEnable) { Session = session; autoreconnecttime = 500; InitializeComponent(); RichTextBox.SetTelnetSession(session); RichTextBox.WriteInStream += Write; RichTextBox.WriteStream += WriteAsync; //RichTextBox.UpdateCaret += UpdateCaret; SetupTextBox(); this.LogFileEnable = LogFileEnable; if(LogFileEnable) logfile = new LogFile(session); ShowNoConnectionBanner(); }
public LogFileDownloader(String IP, String Port, NetworkCredential credentials, String rootFolder, LogFile logfile) : base("ftp://" + IP + ":" + Port + "/", credentials) { this.logFile = logfile; String logFileName = ""; switch (this.logFile) { case 0: logFileName = "blisshive.log"; break; default: throw new Exception("Invalid Logfile."); } this.StartDownload(rootFolder + "/" + logFileName); }
//public TerminalRichTextEditor TerminalRichTextEditorObj { get; set; } public Terminal(TelnetSession Session) : base() { // it should not be less than 10000 this.Session = Session; InitializeComponent(); ConsoleTextBox.Caret = this.Caret; consolebuffer = new BufferString(); logfile = new LogFile(this); ConsoleTextBox.TextInput += ConsoleTextBox_TextInput; //ConsoleTextBox.KeyDownEvent += ConsoleTextBox_KeyDown; ConsoleTextBox.AddHandler(KeyDownEvent, new RoutedEventHandler(ConsoleTextBox_KeyDown), true); ConsoleTextBox.AddHandler(KeyUpEvent, new RoutedEventHandler(ConsoleTextBox_KeyUp), true); }
private void SetupExceptionHandler() { // initialize exception handler ExceptionHandler.AppName = "BugTrapNetTest"; ExceptionHandler.Flags = FlagsType.DetailedMode | FlagsType.ScreenCapture | FlagsType.AttachReport | FlagsType.EditMail; ExceptionHandler.ReportFormat = ReportFormatType.Xml; ExceptionHandler.DumpType = MinidumpType.NoDump; ExceptionHandler.SupportEMail = "*****@*****.**"; ExceptionHandler.SupportURL = "http://www.intellesoft.net"; ExceptionHandler.SupportHost = "localhost"; ExceptionHandler.SupportPort = 9999; // register custom log file this.log = new LogFile("test.log", LogFormatType.Xml); LogFiles.Add(new LogFileEntry(this.log.FileName)); this.log.LogSizeInEntries = 3; }
protected override void EndProcessing() { LogFile logFile; if (this.ParameterSetName == "New") { logFile = new LogFile(this.path, this.streams, this.errorCallback); this.WriteObject(logFile); } else { logFile = this.inputObject; } HostIoInterceptor.GetInterceptor().AddSubscriber(logFile); }
protected override void EndProcessing() { LogFile logFile; if (ParameterSetName == "New") { logFile = new LogFile(path, streams, errorCallback); WriteObject(logFile); } else { logFile = inputObject; } HostIOInterceptor.Instance.AttachToHost(Host); HostIOInterceptor.Instance.AddSubscriber(logFile); }
static PluginAppBase() { plugins = new Dictionary<IPlugin, PluginPackAttribute>(); var pluginFilePattern = "*.dll"; string appDirectory = AppDomain.CurrentDomain.BaseDirectory; pluginDirectory = String.Concat( appDirectory, PluginConfig.PLUGIN_DIRECTORY); if (Directory.Exists(pluginDirectory)) { var loadResult = true; var files = Directory.GetFiles(pluginDirectory, pluginFilePattern ?? "*.dll"); log = new LogFile(appDirectory + PluginConfig.PLUGIN_TMP_DIRECTORY + "plugin.log"); log.Truncate(); if (log != null) { log.Append(String.Format("\r\n\r\n{0:yyyy-MM-dd HH:mm:ss} [+]Plugin Loading" + "\r\n========================================\r\n" + "Directory:{1} \t Total DLL:{2}", DateTime.Now, pluginDirectory.Replace("\\", "/"), files.Length.ToString())); } foreach (string file in files) { if (!LoadPlugin(file)) { loadResult = false; } } if (log != null) { log.Append(String.Format("\r\nload complete!result:{0}", loadResult ? "Ok" : "Error")); } } else { Directory.CreateDirectory(pluginDirectory).Create(); } }
public static void DeleteObjects() { string tablename = "PROBJECT_DELETED"; var lf = new LogFile(tablename+".log"); string sql = "select cpaso_id from "+tablename; string cpaso_id, oradr_adress_id; DbCommand ibcmd = ibconn.CreateCommand(); DbCommand scecmd = sceconn.CreateCommand(); ibcmd.CommandText = sql; ibconn.Open(); sceconn.Open(); DbDataReader rdr = ibcmd.ExecuteReader(); //scecmd.CommandText = sql; while (rdr.Read ()) { cpaso_id = rdr.GetValue(0).ToString(); sql = "SELECT cpaso_id, oradr_adress_id FROM PRobject WHERE cpaso_id="+cpaso_id; lf.WriteLine(sql); scecmd.CommandText = sql; DbDataReader scepr = scecmd.ExecuteReader(); if(scepr.Read()){ cpaso_id = scepr.GetValue(0).ToString(); oradr_adress_id = scepr.GetValue(1).ToString(); if(cpaso_id.Length>0){ sql = "DELETE FROM PRobject WHERE cpaso_id='"+cpaso_id+"'"; lf.WriteLine(sql); scecmd.CommandText = sql; scecmd.ExecuteNonQuery(); sql = "DELETE FROM OR_ADRESS WHERE oradr_adress_id='"+oradr_adress_id+"'"; lf.WriteLine(sql); scecmd.CommandText = sql; scecmd.ExecuteNonQuery(); } } } Console.WriteLine(tablename+" TAMAM"); rdr.Close(); ibconn.Close(); sceconn.Close(); }
/// <summary> /// Stores a snapshot of a project build. /// </summary> /// <param name="result">The result that the snapshot is for.</param> /// <param name="snapshot">The project snapshot.</param> public void StoreProjectSnapshot(IIntegrationResult result, ItemStatus snapshot) { var dirPath = this.RootFolder(result.ArtifactDirectory, this.SnapshotsFolder); Log.Info("Writing snapshot (XML) to [" + dirPath + "]"); var logFile = new LogFile(result); var filePath = Path.ChangeExtension( Path.Combine(dirPath, logFile.Filename), "snapshot"); this.FileSystem.EnsureFolderExists(filePath); Log.Debug("Creating new snapshot (XML) [" + filePath + "]"); using (var stream = this.FileSystem.OpenOutputStream(filePath)) { using (var writer = new StreamWriter(stream)) { Log.Debug("Writing snapshot (XML)"); writer.Write(snapshot.ToString()); Log.Debug("Snapshot (XML) written"); } } }
/// <summary> /// Executes the specified result. /// </summary> /// <param name="result">The result.</param> /// <returns></returns> /// <remarks></remarks> protected override bool Execute(IIntegrationResult result) { result.BuildProgressInformation.SignalStartRunTask(!string.IsNullOrEmpty(Description) ? Description : "Merging Files"); var actualFileSystem = FileSystem ?? new SystemIoFileSystem(); var actualLogger = Logger ?? new DefaultLogger(); var targetSubFolder = result.Label; if (!result.Succeeded) targetSubFolder = new LogFile(result).FilenameFormattedDateString; // Make sure the target folder is rooted var targetFolder = TargetFolder; if (!string.IsNullOrEmpty(targetFolder)) { if (!Path.IsPathRooted(targetFolder)) { targetFolder = Path.Combine( Path.Combine(result.ArtifactDirectory, targetSubFolder), targetFolder); } } else { targetFolder = Path.Combine(result.ArtifactDirectory, targetSubFolder); } foreach (var mergeFile in MergeFiles) { // Get the name of the file string fullMergeFile = mergeFile.FileName; if (!Path.IsPathRooted(fullMergeFile)) { fullMergeFile = Path.Combine(result.WorkingDirectory, fullMergeFile); } // Merge each file WildCardPath path = new WildCardPath(fullMergeFile); foreach (var fileInfo in path.GetFiles()) { if (actualFileSystem.FileExists(fileInfo.FullName)) { switch (mergeFile.MergeAction) { case MergeFileInfo.MergeActionType.Merge: case MergeFileInfo.MergeActionType.CData: // Add the file to the merge list actualLogger.Info("Merging file '{0}'", fileInfo); result.BuildProgressInformation.AddTaskInformation(string.Format(CultureInfo.CurrentCulture,"Merging file '{0}'", fileInfo)); result.AddTaskResult( new FileTaskResult(fileInfo, mergeFile.DeleteAfterMerge, actualFileSystem) { WrapInCData = (mergeFile.MergeAction == MergeFileInfo.MergeActionType.CData) }); break; case MergeFileInfo.MergeActionType.Copy: // Copy the file to the target folder actualFileSystem.EnsureFolderExists(targetFolder); actualLogger.Info("Copying file '{0}' to '{1}'", fileInfo.Name, targetFolder); result.BuildProgressInformation.AddTaskInformation(string.Format(CultureInfo.CurrentCulture,"Copying file '{0}' to '{1}'", fileInfo.Name, targetFolder)); actualFileSystem.Copy(fileInfo.FullName, Path.Combine(targetFolder, fileInfo.Name)); break; case MergeFileInfo.MergeActionType.IndexCopy: // Copy the file to the target folder actualFileSystem.EnsureFolderExists(targetFolder); actualLogger.Info("Reading index file '{0}' for copy", fileInfo.Name); this.CopyFromIndex(fileInfo.Name, targetFolder, actualFileSystem, actualLogger, result); break; default: throw new CruiseControlException( string.Format(CultureInfo.CurrentCulture,"Unknown file merge action '{0}'", mergeFile.MergeAction)); } } else { actualLogger.Warning("File not found '{0}", fileInfo); } } } return true; }
private BSAArchive(string archivepath, LogFile theLog, bool verbose) { if (!File.Exists(archivepath)) { theLog.WriteLog("Archive not found " + archivepath); return; } if (verbose) { theLog.WriteLog("Using " + archivepath); } BSAHeader header; name = archivepath.ToLower(); FileInfo file = new FileInfo(archivepath); BinaryReader binary = new BinaryReader(file.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite), System.Text.Encoding.Default); header = new BSAHeader(binary); //theLog.WriteLog(archivepath + " version " + header.bsaVersion); if (header.bsaVersion != 0x67 && header.bsaVersion != 0x68) { theLog.WriteLog("Unknown BSA version " + archivepath); binary.Close(); return; } if ((header.archiveFlags & 0x4) > 0) { defaultCompressed = true; } else { defaultCompressed = false; } if ((header.archiveFlags & 0x100) > 0) { defaultFlag9 = true; } else { defaultFlag9 = false; } //theLog.WriteLog(name + " is compressed? " + defaultCompressed + " flags " + header.archiveFlags); BSAFolderInfo[] folderInfo = new BSAFolderInfo[header.folderCount]; BSAFileInfo[] fileInfo = new BSAFileInfo[header.fileCount]; for (int index = 0; index < header.folderCount; index++) { folderInfo[index] = new BSAFolderInfo(binary); } int count = 0; for (uint index = 0; index < header.folderCount; index++) { byte b = binary.ReadByte(); if (b > 0) { folderInfo[index].path = new string(binary.ReadChars(b - 1)); } else { folderInfo[index].path = ""; } binary.BaseStream.Position++; folderInfo[index].offset = count; for (int index2 = 0; index2 < folderInfo[index].count; index2++) { fileInfo[count + index2] = new BSAFileInfo(binary, defaultCompressed); } count += folderInfo[index].count; } for (uint index = 0; index < header.fileCount; index++) { fileInfo[index].path = ""; char c; while ((c = binary.ReadChar()) != '\0') fileInfo[index].path += c; } binary.Close(); for (int index = 0; index < header.folderCount; index++) { for (int index2 = 0; index2 < folderInfo[index].count; index2++) { BSAFileInfo bsaFileInfo = fileInfo[folderInfo[index].offset + index2]; BSAArchiveFileInfo bsaArchiveFileInfo = new BSAArchiveFileInfo(this, (int)bsaFileInfo.offset, bsaFileInfo.size); string filepath = Path.Combine(folderInfo[index].path, bsaFileInfo.path); //theLog.WriteLog(archivepath + " file = " + filepath + " off = " + bsaFileInfo.offset + " size = " + bsaFileInfo.size + " compressed = " + bsaArchiveFileInfo.compressed); FileList[filepath.ToLower()] = bsaArchiveFileInfo; } } LoadedArchives.Add(this); }
/// <summary> /// Create a new database based on user input. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void CreateButton_Click(object sender, System.EventArgs e) { // Create the database Cursor csr = null; String sDatabaseName; Database db; FileGroup fg; DataFile df; LogFile lf; ListViewItem DatabaseListViewItem; try { csr = this.Cursor; // Save the old cursor this.Cursor = Cursors.WaitCursor; // Display the waiting cursor // Get the name of the new database sDatabaseName = NewDatabaseTextBox.Text; // Check for new non-zero length name if (sDatabaseName.Length == 0) { ExceptionMessageBox emb = new ExceptionMessageBox(); emb.Text = Properties.Resources.NoDatabaseName; emb.Show(this); return; } // Ensure we have the current list of databases to check. SqlServerSelection.Databases.Refresh(); // Refresh database list ShowDatabases(false); // Is database name new and unique? if (SqlServerSelection.Databases.Contains(sDatabaseName)) { ExceptionMessageBox emb = new ExceptionMessageBox(); emb.Text = Properties.Resources.DuplicateDatabaseName; emb.Show(this); return; } // Instantiate a new database object db = new Database(SqlServerSelection, sDatabaseName); // This may also be accomplished like so: // db = new Database(); // db.Parent = SqlServerSelection; // db.Name = sDatabaseName; // Create a new file group named PRIMARY fg = new FileGroup(db, @"PRIMARY"); // Create a new data file and add it to the file group's Files collection // Give the data file a physical filename using the master database path of the server df = new DataFile(fg, sDatabaseName + @"_Data0", SqlServerSelection.Information.MasterDBPath + @"\" + sDatabaseName + @"_Data0" + @".mdf"); // Set the growth type to KB df.GrowthType = FileGrowthType.KB; // Set the growth size in KB df.Growth = 1024; // Set initial size in KB (optional) df.Size = 10240; // Set the maximum size in KB df.MaxSize = 20480; // Add file to file group fg.Files.Add(df); // Create a new data file and add it to the file group's Files collection // Give the data file a physical filename using the master database path of the server df = new DataFile(fg, sDatabaseName + @"_Data1", SqlServerSelection.Information.MasterDBPath + @"\" + sDatabaseName + @"_Data1" + @".ndf"); // Set the growth type to KB df.GrowthType = FileGrowthType.KB; // Set the growth size in KB df.Growth = 1024; // Set initial size in KB (optional) df.Size = 2048; // Set the maximum size in KB df.MaxSize = 8192; // Add file to file group fg.Files.Add(df); // Add the new file group to the database's FileGroups collection db.FileGroups.Add(fg); // Create a new file group named SECONDARY fg = new FileGroup(db, @"SECONDARY"); // Create a new data file and add it to the file group's Files collection // Give the data file a physical filename using the master database path of the server df = new DataFile(fg, sDatabaseName + @"_Data2", SqlServerSelection.Information.MasterDBPath + @"\" + sDatabaseName + @"_Data2" + @".ndf"); // Set the growth type to KB df.GrowthType = FileGrowthType.KB; // Set the growth size in KB df.Growth = 512; // Set initial size in KB (optional) df.Size = 1024; // Set the maximum size in KB df.MaxSize = 4096; // Add file to file group fg.Files.Add(df); // Create a new data file and add it to the file group's Files collection // Give the data file a physical filename using the master database path df = new DataFile(fg, sDatabaseName + @"_Data3", SqlServerSelection.Information.MasterDBPath + @"\" + sDatabaseName + @"_Data3" + @".ndf"); // Set the growth type to KB df.GrowthType = FileGrowthType.KB; // Set the growth size in KB df.Growth = 512; // In KB // Set initial size in KB (optional) df.Size = 1024; // Set initial size in KB (optional) // Set the maximum size in KB df.MaxSize = 4096; // Add file to file group fg.Files.Add(df); // Add the new file group to the database's FileGroups collection db.FileGroups.Add(fg); // Define the database transaction log. lf = new LogFile(db, sDatabaseName + @"_Log", SqlServerSelection.Information.MasterDBPath + @"\" + sDatabaseName + @"_Log" + @".ldf"); // Set the growth type to KB lf.GrowthType = FileGrowthType.KB; // Set the growth size in KB lf.Growth = 1024; // In KB // Set initial size in KB (optional) lf.Size = 2048; // Set initial size in KB (optional) // Set the maximum size in KB lf.MaxSize = 8192; // In KB // Add file to file group db.LogFiles.Add(lf); // Create the database as defined. db.Create(); // Refresh database list ShowDatabases(false); // Find and select the database just created DatabaseListViewItem = DatabasesListView.FindItemWithText(sDatabaseName); DatabaseListViewItem.Selected = true; DatabaseListViewItem.EnsureVisible(); } catch (SmoException ex) { ExceptionMessageBox emb = new ExceptionMessageBox(ex); emb.Show(this); } finally { // Clean up. db = null; fg = null; df = null; lf = null; UpdateControls(); this.Cursor = csr; // Restore the original cursor } }
//Sends an updated position to the decison system and needs the nearest object to be brightened that can be brightened public bool Brighten(JObject model) { #if DEBUG try { string time = model["time"].ToString(); double lat = (double)model["lat"]; double lon = (double)model["long"]; double alt = (double)model["alt"]; string userID = model["userID"].ToString(); string command = model["brightenNearMe"].ToString(); } catch (Exception e) { // catches the exception if any of the keys are missing Console.WriteLine(e.Source); return(false); } return(true); #else try { string time = model["time"].ToString(); double lat = (double)model["lat"]; double lon = (double)model["lon"]; double alt = (double)model["alt"]; string userID = model["userID"].ToString(); string command = model["command-string"].ToString(); WebRequest request = WebRequest.Create(dm_url + "CommandsFromApp"); request.ContentType = "application/json"; request.Method = "POST"; using (var streamWriter = new StreamWriter(request.GetRequestStream())) { streamWriter.Write(model.ToString()); streamWriter.Flush(); streamWriter.Close(); } try { using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { if (response.StatusCode != HttpStatusCode.OK) { throw new Exception(String.Format( "Server error (HTTP {0}: {1}).", response.StatusCode, response.StatusDescription)); } } } catch (Exception we) { LogFile.AddLog("Brighten -- Could not post information to Decision System: " + we.Message + "\n"); return(false); } } catch (SystemException ex) { LogFile.AddLog("Brigthen -- Could not create the URL with the data provided: " + ex.Message + "\n"); return(false); } return(true); #endif }
public string SaveUser(JObject model) { #if DEBUG try { //string userID = (string)model["userID"]; // houseID is the correct key and is type UInt64 //string passWord = (string)model["Password"]; // roomID is the correct key and is type UInt64 //int[] houseIDs = (int[])model["houseIDs"]; // Type is the correct key and is type string return("1"); } catch (Exception e) { // catches the exception if any of the keys are missing Console.WriteLine(e.Source); return("false"); } #else try { string username = (string)model["username"]; // houseID is the correct key and is type UInt64 string password = (string)model["password"]; // roomID is the correct key and is type UInt64 WebRequest request = WebRequest.Create(pss_url + "U/" + username + "/" + password); request.ContentType = "application/json"; request.Method = "POST"; using (var streamWriter = new StreamWriter(request.GetRequestStream())) { streamWriter.Write(model.ToString()); streamWriter.Close(); } try { using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { if (response.StatusCode != HttpStatusCode.OK) { throw new Exception(String.Format( "Server error (HTTP {0}: {1}).", response.StatusCode, response.StatusDescription)); } var stream = response.GetResponseStream(); var reader = new StreamReader(stream); return(reader.ReadToEnd()); } } catch (Exception we) { LogFile.AddLog("Could not post user information to the Storage: " + we.Message + "\n"); return("false"); } } catch (SystemException ex) { LogFile.AddLog("UpdateLocation -- Could not create the URL with the data provided: " + ex.Message + "\n"); return("false"); } return("true"); #endif }
private void runExtraction() { steps = (((enddate - startdate).TotalSeconds) / count); if (steps < maxLinhas) { steps = 1; partSeconds = ((enddate - startdate).TotalSeconds); } else { steps = Math.Ceiling((((enddate - startdate).TotalSeconds) / count) / maxLinhas); partSeconds = Math.Ceiling(((enddate - startdate).TotalSeconds) / steps); } count = Math.Ceiling(partSeconds / count); startdate = startdate.AddSeconds(-partSeconds); progressBar_extr.Value = 1; for (double cstep = 1; cstep <= steps; cstep++) { startdate = startdate.AddSeconds(partSeconds); enddate = startdate.AddSeconds(partSeconds); starttime = PItime(startdate); endtime = PItime(enddate); //MessageBox.Show("Step:" + cstep + "/" + steps + " starttime:" + starttime + " endtime:" + endtime + " (partial=" + partSeconds + ")" + " (count=" + count + ")"); System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo.FileName = Support.InstalPath + "resources\\piconfig.exe"; process.StartInfo.WindowStyle = ProcessWindowStyle.Minimized; process.StartInfo.RedirectStandardInput = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.Start(); this.BringToFront(); string input = ""; string mode = (ConfigFile.read_attribute(configName, ConfigFile.AttribPIConfig_Inte) == "1") ? "even" : "comp"; input = input + "@logi " + ConfigFile.read_attribute(configName, ConfigFile.AttribPIConfig_Host) + "," + ConfigFile.read_attribute(configName, ConfigFile.AttribPIConfig_User) + "," + ConfigFile.read_attribute(configName, ConfigFile.AttribPIConfig_Pass) + "," + ConfigFile.read_attribute(configName, ConfigFile.AttribPIConfig_Port) + "\r\n"; input = input + "@maxerr 65535" + "\r\n"; input = input + "@table piarc" + "\r\n"; input = input + "@mode list" + "\r\n"; input = input + "@modify count=" + (count + 1) + "\r\n"; input = input + "@modify starttime = " + starttime + "\r\n"; input = input + "@modify endtime = " + endtime + "\r\n"; input = input + "@modify mode = " + mode + "\r\n"; input = input + "@timf 1,F" + "\r\n"; input = input + "@ostr tag,time,value" + "\r\n"; input = input + "@ostr ..." + "\r\n"; //input = input +" @ostructure tag" + "\r\n"; //input = input + "@ostructure time" + "\r\n"; //input = input + "@ostructure value" + "\r\n"; //input = input + "@ostructure *" + "\r\n"; input = input + "@istr tag,starttime,endtime" + "\r\n"; Support.CreateFile(Support.SelectedTagFilePrefix + configName + ".txt"); input = input + "@input " + Support.InstalPath + "\\" + Support.SelectedTagFilePrefix + configName + ".txt" + "\r\n"; input = input + "@endsection" + "\r\n"; input = input + "@bye"; process.StandardInput.Write(input); this.BringToFront(); process.StandardInput.Flush(); this.BringToFront(); process.StandardInput.Close(); this.BringToFront(); string result = (process.StandardOutput.ReadToEnd()); //MessageBox.Show(result); string[] results = result.Split(new string[] { "\r\n" }, StringSplitOptions.None); string finalresult = ""; string datalines = "Timestamp"; //no matrix format if (ConfigFile.read_attribute(configName, ConfigFile.AttribPIConfig_Mtrx) == "0") { for (int i = 0; i < results.Length; i++) { //Selects only usefull info (removes alerts, erros and other messages) if (results[i].Contains(",") == true) { string[] thisline = results[i].Split(','); if (thisline.Length == 3) { DateTime timestamp; if (DateTime.TryParse(thisline[1], out timestamp)) { if (thisline[2] == "Digital State") { thisline[2] = ""; } thisline[1] = timestamp.ToString("yyyyMMdd_HHmmss"); finalresult = finalresult + thisline[0] + ";" + thisline[1] + ";" + thisline[2] + "\r\n"; } } } } } //matrix format else { List <string> tags = new List <string>(); List <string> times = new List <string>(); //for each line from response for (int i = 0; i < results.Length; i++) { //if line is data (non data line wont contain the "," char) if (results[i].Contains(",") == true) { string[] thisline = results[i].Split(','); if (thisline.Length == 3) { //add tag to tag array if (!tags.Contains(thisline[0])) { tags.Add(thisline[0]); } //add times to time array if (!times.Contains(thisline[1])) { times.Add(thisline[1]); } } } } //creates data table (matrix format) string[,] table = new string[tags.Count(), times.Count()]; for (int i = 0; i < results.Length; i++) { if (results[i].Contains(",") == true) { string[] thisline = results[i].Split(','); if (thisline.Length == 3) { if (thisline[2] == "Digital State") { thisline[2] = ""; } //add value to the spot on the table with corresponding tag and time table[tags.IndexOf(thisline[0]), times.IndexOf(thisline[1])] = thisline[2]; } } } foreach (var tag in tags) { datalines += ";" + tag; } datalines += "\r\n"; foreach (var time in times) { DateTime timestamp; if (DateTime.TryParse(time, out timestamp)) { datalines += timestamp.ToString("yyyyMMdd_HHmmss"); foreach (var tag in tags) { string value = (table[tags.IndexOf(tag), times.IndexOf(time)] != null) ? table[tags.IndexOf(tag), times.IndexOf(time)] : ""; datalines += ";" + value.Replace(";", ""); } datalines += "\r\n"; } } finalresult = datalines; } process.WaitForExit(); string Outputpath = Regex.Split(ConfigFile.read_attribute(configName, ConfigFile.AttribPIConfig_OutP), @"(.*[\\|\/])([^\\|\/]*)")[1]; try { string Pref = ConfigFile.read_attribute(configName, ConfigFile.AttribPIConfig_Pref); string filename = (Pref == "") ? configName : Pref; //Support.WriteOneLine(filename + "_Historic_" + startdate.ToString("yyyyMMdd_HHmmss") + "_to_" + enddate.ToString("yyyyMMdd_HHmmss") + ".csv", finalresult, false); File.WriteAllText(Outputpath + filename + "_Historic_" + startdate.ToString("yyyyMMdd_HHmmss") + "_to_" + enddate.ToString("yyyyMMdd_HHmmss") + ".csv", finalresult); } catch (Exception exx) { LogFile.write_LogFile("Error saving output for config " + configName + " with message: " + exx.Message); } progressBar_extr.Value = ((int)Math.Ceiling((cstep / steps) * 100) > 1)? (int)Math.Ceiling((cstep / steps) * 100) :1; this.Update(); } MessageBox.Show(this, "Historical Extraction Complete!", "Success", MessageBoxButtons.OK); this.Close(); }
public static void Main(string[] args) { ConsoleColor defaultColor = Console.ForegroundColor; Console.WriteLine(Assembly.GetExecutingAssembly().GetName().Name + " " + Assembly.GetExecutingAssembly().GetName().Version); Console.WriteLine("Copyright (c) 2020 GISNET\n"); MyLicense license = LicenseHandler.ReadLicense(out LicenseStatus licStatus, out string validationMsg); switch (licStatus) { case LicenseStatus.Undefined: Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Brak pliku z licencją!!!\n"); Console.ForegroundColor = defaultColor; Console.WriteLine("Identyfikator komputera: " + LicenseHandler.GenerateUid("ReadOpXML") + '\n'); LogFile.SaveMessage("Brak pliku z licencją: " + LicenseHandler.GenerateUid("ReadOpXML")); Console.ReadKey(false); Environment.Exit(0); break; case LicenseStatus.Valid: Console.WriteLine("Właściciel licencji:"); Console.WriteLine(license.LicenseOwner + "\n"); Console.WriteLine("Licencja dla powiatu: " + license.Atr1 + '\n'); Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine($"Licencja typu: '{license.Type}', ważna do: {license.LicenseEnd}\n"); Console.ForegroundColor = defaultColor; System.Threading.Thread.Sleep(1000); break; case LicenseStatus.Invalid: case LicenseStatus.Cracked: Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(validationMsg); Console.ForegroundColor = defaultColor; Console.ReadKey(false); Environment.Exit(0); break; case LicenseStatus.Expired: Console.WriteLine("Właściciel licencji:"); Console.WriteLine(license.LicenseOwner + "\n"); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(validationMsg); Console.ForegroundColor = defaultColor; Console.ReadKey(false); Environment.Exit(0); break; default: throw new ArgumentOutOfRangeException(); } string startupPath = string.Empty; bool poprawa = false; bool walidacja = false; Parser.Default.ParseArguments <Options>(args).WithParsed(RunOptions).WithNotParsed(HandleParseError); void RunOptions(Options opts) { startupPath = opts.StarupPath; poprawa = opts.Poprawa; walidacja = opts.Walidacja; } void HandleParseError(IEnumerable <Error> errs) { Console.ReadKey(false); Environment.Exit(0); } Console.WriteLine("Wyszukiwanie plików XML w katalogu {0}...", startupPath); List <string> xmlFiles = Directory.EnumerateFiles(startupPath ?? throw new InvalidOperationException(), "*.xml", SearchOption.AllDirectories).ToList(); Console.WriteLine("Znaleziono {0} plików XML.\n", xmlFiles.Count); bool isError = false; foreach (string xmlFile in xmlFiles) { if (license.Atr1 != "0000") { // ReSharper disable once PossibleNullReferenceException if (!Path.GetFileNameWithoutExtension(xmlFile).StartsWith($"P.{license.Atr1}")) { Console.WriteLine(xmlFile + " => " + "błędne oznaczenie powiatu."); ErrorLogFile.SaveMessage(Path.Combine(startupPath, "syntaktyka.log"), xmlFile + " => " + "błędne oznaczenie powiatu."); isError = true; } } } if (isError) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("\nWe wskazanym katalogu znajdują się pliki XML, które nie pasują do schematu XSD (zły powiat)!"); Console.ForegroundColor = defaultColor; Console.ReadKey(true); Environment.Exit(0); } Console.WriteLine("Walidacja syntaktyczna plików XML...\n"); foreach (string xmlFile in xmlFiles) { try { XmlDocument doc = new XmlDocument { PreserveWhitespace = true }; doc.Load(xmlFile); } catch (XmlException e) { Console.WriteLine($@"{xmlFile}: {e.Message}"); ErrorLogFile.SaveMessage(Path.Combine(startupPath, "syntaktyka.log"), xmlFile + " => " + e.Message); isError = true; } } if (isError) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("\nMusisz ręcznie poprawić wskazane błedy by zaczytać pliki XML!"); Console.ForegroundColor = defaultColor; Console.ReadKey(true); Environment.Exit(0); } if (poprawa) { Console.WriteLine("Automatyczna poprawa plików XML...\n"); foreach (string xmlFile in xmlFiles) { XmlDocument doc = new XmlDocument { PreserveWhitespace = true }; doc.Load(xmlFile); doc.FixErrors(); doc.Save(xmlFile); } } Console.WriteLine(walidacja ? "Wczytywanie i walidacja plików XML...\n" : "Wczytywanie plików XML...\n"); Dictionary <int, PzgMaterialZasobu> pzgMaterialZasobuDict = new Dictionary <int, PzgMaterialZasobu>(); List <PzgCel> pzgMaterialZasobuCelList = new List <PzgCel>(); List <CelArchiwalny> pzgMaterialZasobuCelArchList = new List <CelArchiwalny>(); List <DzialkaPrzed> pzgMaterialZasobuDzialkaPrzedList = new List <DzialkaPrzed>(); List <DzialkaPo> pzgMaterialZasobuDzialkaPoList = new List <DzialkaPo>(); Dictionary <int, PzgZgloszenie> pzgZgloszenieDict = new Dictionary <int, PzgZgloszenie>(); List <PzgCel> pzgZgloszenieCelList = new List <PzgCel>(); List <CelArchiwalny> pzgZgloszenieCelArchList = new List <CelArchiwalny>(); List <OsobaUprawniona> pzgZgloszenieOsobaUprawnionaList = new List <OsobaUprawniona>(); XmlReaderSettings settings = new XmlReaderSettings(); if (walidacja) { settings.Schemas.Add("http://www.w3.org/2001/XMLSchema", ".\\xsd\\schemat.xsd"); settings.ValidationType = ValidationType.Schema; settings.ValidationFlags = XmlSchemaValidationFlags.AllowXmlAttributes | XmlSchemaValidationFlags.ProcessIdentityConstraints | XmlSchemaValidationFlags.ProcessInlineSchema | XmlSchemaValidationFlags.ReportValidationWarnings; settings.ValidationEventHandler += ValidationEventHandler; } int idFile = 0; foreach (string xmlFile in xmlFiles) { idFile++; XmlReader reader = XmlReader.Create(xmlFile, settings); XmlDocument doc = new XmlDocument { PreserveWhitespace = true }; doc.Load(reader); XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); nsmgr.AddNamespace("xmls", "http://www.w3.org/2001/XMLSchema"); PzgMaterialZasobu pzgMaterialZasobu = new PzgMaterialZasobu { IdFile = idFile, XmlPath = xmlFile, IdMaterialu = Path.GetFileNameWithoutExtension(xmlFile) }; pzgMaterialZasobu.IdMaterialuPierwszyCzlon = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_IdMaterialu", "pierwszyCzlon"); pzgMaterialZasobu.IdMaterialuDrugiCzlon = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_IdMaterialu", "drugiCzlon"); pzgMaterialZasobu.IdMaterialuTrzeciCzlon = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_IdMaterialu", "trzeciCzlon"); pzgMaterialZasobu.IdMaterialuCzwartyCzlon = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_IdMaterialu", "czwartyCzlon"); pzgMaterialZasobu.PzgDataPrzyjecia = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_dataPrzyjecia"); pzgMaterialZasobu.DataWplywu = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "dataWplywu"); pzgMaterialZasobu.PzgNazwa = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_nazwa"); pzgMaterialZasobu.PzgPolozenieObszaru = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_polozenieObszaru"); pzgMaterialZasobu.Obreb = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "obreb"); pzgMaterialZasobu.PzgTworcaOsobaId = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_tworca", "osoba_id"); pzgMaterialZasobu.PzgTworcaNazwa = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_tworca", "nazwa"); pzgMaterialZasobu.PzgTworcaRegon = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_tworca", "REGON"); pzgMaterialZasobu.PzgTworcaPesel = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_tworca", "PESEL"); pzgMaterialZasobu.PzgSposobPozyskania = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_sposobPozyskania"); pzgMaterialZasobu.PzgPostacMaterialu = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_postacMaterialu"); pzgMaterialZasobu.PzgRodzNosnika = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_rodzNosnika"); pzgMaterialZasobu.PzgDostep = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_dostep"); pzgMaterialZasobu.PzgPrzyczynyOgraniczen = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_przyczynyOgraniczen"); pzgMaterialZasobu.PzgTypMaterialu = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_typMaterialu"); pzgMaterialZasobu.PzgKatArchiwalna = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_katArchiwalna"); pzgMaterialZasobu.PzgJezyk = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_jezyk"); pzgMaterialZasobu.PzgOpis = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_opis"); pzgMaterialZasobu.PzgOznMaterialuZasobu = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_oznMaterialuZasobu"); pzgMaterialZasobu.OznMaterialuZasobuTyp = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "oznMaterialuZasobuTyp"); pzgMaterialZasobu.OznMaterialuZasobuJedn = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "oznMaterialuZasobuJedn"); pzgMaterialZasobu.OznMaterialuZasobuNr = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "oznMaterialuZasobuNr"); pzgMaterialZasobu.OznMaterialuZasobuRok = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "oznMaterialuZasobuRok"); pzgMaterialZasobu.OznMaterialuZasobuTom = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "oznMaterialuZasobuTom"); pzgMaterialZasobu.OznMaterialuZasobuSepJednNr = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "oznMaterialuZasobuSepJednNr"); pzgMaterialZasobu.OznMaterialuZasobuSepNrRok = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "oznMaterialuZasobuSepNrRok"); pzgMaterialZasobu.PzgDokumentWyl = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_dokumentWyl"); pzgMaterialZasobu.PzgDataWyl = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_dataWyl"); pzgMaterialZasobu.PzgDataArchLubBrak = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_dataArchLubBrak"); pzgMaterialZasobu.PzgCelList = doc.GetXmlValueList(nsmgr, "PZG_MaterialZasobu", "pzg_cel"); pzgMaterialZasobu.CelArchiwalnyList = doc.GetXmlValueList(nsmgr, "PZG_MaterialZasobu", "celArchiwalny"); pzgMaterialZasobu.DzialkaPrzedList = doc.GetXmlValueList(nsmgr, "PZG_MaterialZasobu", "dzialkaPrzed"); pzgMaterialZasobu.DzialkaPoList = doc.GetXmlValueList(nsmgr, "PZG_MaterialZasobu", "dzialkaPo"); pzgMaterialZasobu.Opis2 = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "opis2"); pzgMaterialZasobuDict.Add(pzgMaterialZasobu.IdFile, pzgMaterialZasobu); XmlNodeList nodeList = doc.DocumentElement?.SelectNodes("/xmls:schema/xmls:PZG_MaterialZasobu/xmls:pzg_cel", nsmgr); if (nodeList != null) { pzgMaterialZasobuCelList.AddRange(from XmlNode node in nodeList select new PzgCel { IdFile = idFile, XmlPath = xmlFile, IdMaterialu = Path.GetFileNameWithoutExtension(xmlFile), Value = string.IsNullOrEmpty(node.InnerText) ? "--brak wartosci--" : node.InnerText }); } nodeList = doc.DocumentElement?.SelectNodes("/xmls:schema/xmls:PZG_MaterialZasobu/xmls:celArchiwalny", nsmgr); if (nodeList != null) { pzgMaterialZasobuCelArchList.AddRange(from XmlNode node in nodeList select new CelArchiwalny { IdFile = idFile, XmlPath = xmlFile, IdMaterialu = Path.GetFileNameWithoutExtension(xmlFile), Value = string.IsNullOrEmpty(node.InnerText) ? "--brak wartosci--" : node.InnerText }); } nodeList = doc.DocumentElement?.SelectNodes("/xmls:schema/xmls:PZG_MaterialZasobu/xmls:dzialkaPrzed", nsmgr); if (nodeList != null) { pzgMaterialZasobuDzialkaPrzedList.AddRange(from XmlNode node in nodeList select new DzialkaPrzed { IdFile = idFile, XmlPath = xmlFile, IdMaterialu = Path.GetFileNameWithoutExtension(xmlFile), Value = string.IsNullOrEmpty(node.InnerText) ? "--brak wartosci--" : node.InnerText }); } nodeList = doc.DocumentElement?.SelectNodes("/xmls:schema/xmls:PZG_MaterialZasobu/xmls:dzialkaPo", nsmgr); if (nodeList != null) { pzgMaterialZasobuDzialkaPoList.AddRange(from XmlNode node in nodeList select new DzialkaPo { IdFile = idFile, XmlPath = xmlFile, IdMaterialu = Path.GetFileNameWithoutExtension(xmlFile), Value = string.IsNullOrEmpty(node.InnerText) ? "--brak wartosci--" : node.InnerText }); } PzgZgloszenie pzgZgloszenie = new PzgZgloszenie { IdFile = idFile, XmlPath = xmlFile, IdMaterialu = Path.GetFileNameWithoutExtension(xmlFile) }; pzgZgloszenie.PzgOznMaterialuZasobu = pzgMaterialZasobu.PzgOznMaterialuZasobu; pzgZgloszenie.PzgIdZgloszenia = doc.GetXmlValue(nsmgr, "PZG_Zgloszenie", "pzg_idZgloszenia"); pzgZgloszenie.IdZgloszeniaJedn = doc.GetXmlValue(nsmgr, "PZG_Zgloszenie", "idZgloszeniaJedn"); pzgZgloszenie.IdZgloszeniaNr = doc.GetXmlValue(nsmgr, "PZG_Zgloszenie", "idZgloszeniaNr"); pzgZgloszenie.IdZgloszeniaRok = doc.GetXmlValue(nsmgr, "PZG_Zgloszenie", "idZgloszeniaRok"); pzgZgloszenie.IdZgloszeniaEtap = doc.GetXmlValue(nsmgr, "PZG_Zgloszenie", "idZgloszeniaEtap"); pzgZgloszenie.IdZgloszeniaSepJednNr = doc.GetXmlValue(nsmgr, "PZG_Zgloszenie", "idZgloszeniaSepJednNr"); pzgZgloszenie.IdZgloszeniaSepNrRok = doc.GetXmlValue(nsmgr, "PZG_Zgloszenie", "idZgloszeniaSepNrRok"); pzgZgloszenie.PzgDataZgloszenia = doc.GetXmlValue(nsmgr, "PZG_Zgloszenie", "pzg_dataZgloszenia"); pzgZgloszenie.PzgPolozenieObszaru = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_polozenieObszaru"); pzgZgloszenie.Obreb = doc.GetXmlValue(nsmgr, "PZG_Zgloszenie", "obreb"); pzgZgloszenie.PzgPodmiotZglaszajacyOsobaId = doc.GetXmlValue(nsmgr, "PZG_Zgloszenie", "pzg_podmiotZglaszajacy", "osoba_id"); pzgZgloszenie.PzgPodmiotZglaszajacyNazwa = doc.GetXmlValue(nsmgr, "PZG_Zgloszenie", "pzg_podmiotZglaszajacy", "nazwa"); pzgZgloszenie.PzgPodmiotZglaszajacyRegon = doc.GetXmlValue(nsmgr, "PZG_Zgloszenie", "pzg_podmiotZglaszajacy", "REGON"); pzgZgloszenie.PzgPodmiotZglaszajacyPesel = doc.GetXmlValue(nsmgr, "PZG_Zgloszenie", "pzg_podmiotZglaszajacy", "PESEL"); pzgZgloszenie.OsobaUprawnionaList = doc.GetXmlValueList(nsmgr, "PZG_Zgloszenie", "osobaUprawniona"); pzgZgloszenie.PzgCelList = doc.GetXmlValueList(nsmgr, "PZG_Zgloszenie", "pzg_cel"); pzgZgloszenie.CelArchiwalnyList = doc.GetXmlValueList(nsmgr, "PZG_Zgloszenie", "celArchiwalny"); pzgZgloszenie.PzgRodzaj = doc.GetXmlValue(nsmgr, "PZG_Zgloszenie", "pzg_rodzaj"); pzgZgloszenieDict.Add(pzgZgloszenie.IdFile, pzgZgloszenie); nodeList = doc.DocumentElement?.SelectNodes("/xmls:schema/xmls:PZG_Zgloszenie/xmls:pzg_cel", nsmgr); if (nodeList != null) { pzgZgloszenieCelList.AddRange(from XmlNode node in nodeList select new PzgCel { IdFile = idFile, XmlPath = xmlFile, IdMaterialu = Path.GetFileNameWithoutExtension(xmlFile), Value = string.IsNullOrEmpty(node.InnerText) ? "--brak wartosci--" : node.InnerText }); } nodeList = doc.DocumentElement?.SelectNodes("/xmls:schema/xmls:PZG_Zgloszenie/xmls:celArchiwalny", nsmgr); if (nodeList != null) { pzgZgloszenieCelArchList.AddRange(from XmlNode node in nodeList select new CelArchiwalny { IdFile = idFile, XmlPath = xmlFile, IdMaterialu = Path.GetFileNameWithoutExtension(xmlFile), Value = string.IsNullOrEmpty(node.InnerText) ? "--brak wartosci--" : node.InnerText }); } nodeList = doc.DocumentElement?.SelectNodes("/xmls:schema/xmls:PZG_Zgloszenie/xmls:osobaUprawniona", nsmgr); if (nodeList != null) { foreach (XmlNode node in nodeList) { XmlDocument docosoba = new XmlDocument(); docosoba.LoadXml(node.OuterXml); string imie = docosoba.SelectSingleNode("/xmls:osobaUprawniona/xmls:imie", nsmgr)?.InnerText; string nazwisko = docosoba.SelectSingleNode("/xmls:osobaUprawniona/xmls:nazwisko", nsmgr)?.InnerText; string numerUprawnien = docosoba.SelectSingleNode("/xmls:osobaUprawniona/xmls:numer_uprawnien", nsmgr)?.InnerText; if (string.IsNullOrEmpty(imie)) { imie = "--brak wartosci--"; } if (string.IsNullOrEmpty(nazwisko)) { nazwisko = "--brak wartosci--"; } if (string.IsNullOrEmpty(numerUprawnien)) { numerUprawnien = "--brak wartosci--"; } OsobaUprawniona osobaUprawniona = new OsobaUprawniona { IdFile = idFile, XmlPath = xmlFile, IdMaterialu = Path.GetFileNameWithoutExtension(xmlFile), Imie = imie, Nazwisko = nazwisko, NumerUprawnien = numerUprawnien }; pzgZgloszenieOsobaUprawnionaList.Add(osobaUprawniona); } } } // ------------------------------------------------------------------------------------------- // Badanie zgodności operatów i zgłoszeń z modelem danych if (walidacja) { if (WalidationLogList.Count > 0) { Console.WriteLine(""); } Console.WriteLine("Weryfikacja poprawności operatów z modelem danych..."); foreach (PzgMaterialZasobu operat in pzgMaterialZasobuDict.Values) { string oznMaterialuZasobu = GetPzgOznMaterialuZasobu(operat); if (operat.PzgOznMaterialuZasobu != oznMaterialuZasobu) { Console.WriteLine($"Błąd: {operat.XmlPath} - Nazwa operatu nie pasuje do jego składowych."); ModelErrorLogList.Add(new ModelErrorLog(operat.IdFile, operat.XmlPath, "Błąd", "pzg_oznMaterialuZasobu", operat.PzgOznMaterialuZasobu, "Nazwa operatu nie pasuje do jego składowych.")); } int operatCount = pzgMaterialZasobuDict.Values.Count(o => o.PzgOznMaterialuZasobu == operat.PzgOznMaterialuZasobu && o.Obreb == operat.Obreb); if (operatCount > 1) { Console.WriteLine($"Błąd: {operat.XmlPath} - Duplikat pzg_oznMaterialuZasobu."); ModelErrorLogList.Add(new ModelErrorLog(operat.IdFile, operat.XmlPath, "Błąd", "pzg_oznMaterialuZasobu", operat.PzgOznMaterialuZasobu, "Duplikat pzg_oznMaterialuZasobu.")); } string idMaterialu = $"{operat.IdMaterialuPierwszyCzlon}.{operat.IdMaterialuDrugiCzlon}.{operat.IdMaterialuTrzeciCzlon}.{operat.IdMaterialuCzwartyCzlon}"; if (operat.IdMaterialu != idMaterialu) { Console.WriteLine($"Błąd: {operat.XmlPath} - ID operatu nie pasuje do jego składowych."); ModelErrorLogList.Add(new ModelErrorLog(operat.IdFile, operat.XmlPath, "Błąd", "pzg_IdMaterialu", operat.IdMaterialu, "ID operatu nie pasuje do jego składowych.")); } operatCount = pzgMaterialZasobuDict.Values.Count(o => o.IdMaterialu == operat.IdMaterialu); if (operatCount > 1) { Console.WriteLine($"Błąd: {operat.XmlPath} - Duplikat pzg_IdMaterialu."); ModelErrorLogList.Add(new ModelErrorLog(operat.IdFile, operat.XmlPath, "Błąd", "pzg_IdMaterialu", operat.IdMaterialu, "Duplikat pzg_IdMaterialu.")); } } Console.WriteLine(""); // ------------------------------------------------------------------------------------------- Console.WriteLine("Weryfikacja poprawności zgłoszeń z modelem danych..."); foreach (PzgZgloszenie zgloszenie in pzgZgloszenieDict.Values) { string pzgIdZgloszenia = GetPzgIdZgloszenia(zgloszenie); if (zgloszenie.PzgIdZgloszenia == "--brak znacznika--") { Console.WriteLine($"Błąd: {zgloszenie.XmlPath}: Brak zgłoszenia dla operatu."); ModelErrorLogList.Add(new ModelErrorLog(zgloszenie.IdFile, zgloszenie.XmlPath, "Ostrzeżenie", "pzg_IdZgloszenia", zgloszenie.PzgIdZgloszenia, "Brak zgłoszenia dla operatu.")); } else { if (zgloszenie.PzgIdZgloszenia != pzgIdZgloszenia) { Console.WriteLine($"Błąd: {zgloszenie.XmlPath}: Nazwa zgłoszenia nie pasuje do jego składowych."); ModelErrorLogList.Add(new ModelErrorLog(zgloszenie.IdFile, zgloszenie.XmlPath, "Błąd", "pzg_IdZgloszenia", zgloszenie.PzgIdZgloszenia, "Nazwa zgłoszenia nie pasuje do jego składowych.")); } int zgloszenieCount = pzgZgloszenieDict.Values.Count(o => o.PzgIdZgloszenia == zgloszenie.PzgIdZgloszenia); if (zgloszenieCount > 1) { int zgloszenieMultiAttributesCount = pzgZgloszenieDict.Values.Count(z => z.PzgIdZgloszenia == zgloszenie.PzgIdZgloszenia && z.PzgDataZgloszenia == zgloszenie.PzgDataZgloszenia && z.Obreb == zgloszenie.Obreb && z.PzgPodmiotZglaszajacyOsobaId == zgloszenie.PzgPodmiotZglaszajacyOsobaId && z.PzgPodmiotZglaszajacyNazwa == zgloszenie.PzgPodmiotZglaszajacyNazwa && z.PzgPodmiotZglaszajacyRegon == zgloszenie.PzgPodmiotZglaszajacyRegon && z.PzgPodmiotZglaszajacyPesel == zgloszenie.PzgPodmiotZglaszajacyPesel && z.OsobaUprawnionaList == zgloszenie.OsobaUprawnionaList && z.PzgCelList == zgloszenie.PzgCelList && z.CelArchiwalnyList == zgloszenie.CelArchiwalnyList && z.PzgRodzaj == zgloszenie.PzgRodzaj); if (zgloszenieMultiAttributesCount == zgloszenieCount) { Console.WriteLine($"Ostrzeżenie: {zgloszenie.XmlPath}: Powielony numer zgłoszenia dla operatu."); ModelErrorLogList.Add(new ModelErrorLog(zgloszenie.IdFile, zgloszenie.XmlPath, "Ostrzeżenie", "pzg_IdZgloszenia", zgloszenie.PzgIdZgloszenia, "Powielony numer zgłoszenia dla operatu.")); } else { Console.WriteLine($"Błąd: {zgloszenie.XmlPath}: Duplikat nazwy zgłoszenia."); ModelErrorLogList.Add(new ModelErrorLog(zgloszenie.IdFile, zgloszenie.XmlPath, "Błąd", "pzg_IdZgloszenia", zgloszenie.PzgIdZgloszenia, "Duplikat nazwy zgłoszenia.")); } } } } Console.WriteLine(""); } Console.WriteLine("Zapis plików WKT z XML..."); foreach (PzgMaterialZasobu pzgMaterialZasobu in pzgMaterialZasobuDict.Values) { string wktName = pzgMaterialZasobu.XmlPath.Replace(".xml", ".wkt"); File.WriteAllText(wktName, pzgMaterialZasobu.PzgPolozenieObszaru, Encoding.UTF8); } foreach (PzgZgloszenie pzgZgloszenie in pzgZgloszenieDict.Values) { string wktName = pzgZgloszenie.XmlPath.Replace(".xml", "_zgl.wkt"); File.WriteAllText(wktName, pzgZgloszenie.PzgPolozenieObszaru, Encoding.UTF8); } // ------------------------------------------------------------------------------------------- using (ExcelPackage excelPackage = new ExcelPackage()) { excelPackage.Workbook.Properties.Author = "GISNET Grzegorz Gogolewski i Wspólnicy Spółka Jawna"; excelPackage.Workbook.Properties.Company = "GISNET Grzegorz Gogolewski i Wspólnicy Spółka Jawna"; excelPackage.Workbook.Properties.Manager = "Grzegorz Gogolewski"; excelPackage.Workbook.Properties.Title = "Raport z danymi wczytanymi z plików XML dla operatów i zgłoszeń"; excelPackage.Workbook.Properties.Keywords = "xml, xsd, operat, zgłoszenie"; string[] arkusze = { "operaty", "operaty_cel", "operaty_cel_arch", "operaty_dzialka_przed", "operaty_dzialka_po", "zgłoszenia", "zgłoszenia_cel", "zgłoszenia_cel_arch", "zgłoszenia_osoba_uprawniona", "walidacja", "model" }; if (ModelErrorLogList.Count > 0 || WalidationLogList.Count > 0) { Console.WriteLine(""); } foreach (string arkusz in arkusze) { Console.WriteLine($"Eksport danych do XLS [{arkusz}]..."); ExcelWorksheet sheet = excelPackage.Workbook.Worksheets.Add(arkusz); switch (arkusz) { case "operaty": sheet.Cells[1, 1].LoadFromCollection(pzgMaterialZasobuDict, true); Console.WriteLine("\nWeryfikacja pzg_polozenieObszaru..."); for (int i = 2; i < sheet.Dimension.End.Row; i++) { if (sheet.Cells[$"K{i}"].Text.Length > 32767) { sheet.Cells[$"K{i}"].Value = sheet.Cells[$"K{i}"].Text.Substring(0, 32766); Console.WriteLine(sheet.Cells[$"B{i}"].Text + ": pzg_polozenieObszaru przekracza rozmiar komórki Excel!"); } } Console.WriteLine("\nWeryfikacja dzialkaPrzed..."); for (int i = 2; i < sheet.Dimension.End.Row; i++) { if (sheet.Cells[$"AM{i}"].Text.Length > 32767) { sheet.Cells[$"AM{i}"].Value = sheet.Cells[$"AM{i}"].Text.Substring(0, 32766); Console.WriteLine(sheet.Cells[$"B{i}"].Text + ": dzialkaPrzed przekracza rozmiar komórki Excel!"); } } Console.WriteLine("\nWeryfikacja dzialkaPo..."); for (int i = 2; i < sheet.Dimension.End.Row; i++) { if (sheet.Cells[$"AN{i}"].Text.Length > 32767) { sheet.Cells[$"AN{i}"].Value = sheet.Cells[$"AN{i}"].Text.Substring(0, 32766); Console.WriteLine(sheet.Cells[$"B{i}"].Text + ": dzialkaPo przekracza rozmiar komórki Excel!"); } } Console.WriteLine(""); break; case "operaty_cel": sheet.Cells[1, 1].LoadFromCollection(pzgMaterialZasobuCelList, true); break; case "operaty_cel_arch": sheet.Cells[1, 1].LoadFromCollection(pzgMaterialZasobuCelArchList, true); break; case "operaty_dzialka_przed": sheet.Cells[1, 1].LoadFromCollection(pzgMaterialZasobuDzialkaPrzedList, true); break; case "operaty_dzialka_po": sheet.Cells[1, 1].LoadFromCollection(pzgMaterialZasobuDzialkaPoList, true); break; case "zgłoszenia": sheet.Cells[1, 1].LoadFromCollection(pzgZgloszenieDict.Values, true); Console.WriteLine("\nWeryfikacja pzg_polozenieObszaru..."); for (int i = 2; i < sheet.Dimension.End.Row; i++) { if (sheet.Cells[$"F{i}"].Text.Length > 32767) { sheet.Cells[$"F{i}"].Value = sheet.Cells[$"F{i}"].Text.Substring(0, 32766); string xmlPath = sheet.Cells[$"B{i}"].Text; Console.WriteLine(xmlPath + ": pzg_polozenieObszaru przekracza rozmiar komórki Excel!"); } } Console.WriteLine(""); break; case "zgłoszenia_cel": sheet.Cells[1, 1].LoadFromCollection(pzgZgloszenieCelList, true); break; case "zgłoszenia_cel_arch": sheet.Cells[1, 1].LoadFromCollection(pzgZgloszenieCelArchList, true); break; case "zgłoszenia_osoba_uprawniona": sheet.Cells[1, 1].LoadFromCollection(pzgZgloszenieOsobaUprawnionaList, true); break; case "walidacja": sheet.Cells[1, 1].LoadFromCollection(WalidationLogList, true); break; case "model": sheet.Cells[1, 1].LoadFromCollection(ModelErrorLogList, true); break; } int rowsCount = sheet.Dimension.Rows; int columnsCount = sheet.Dimension.Columns; sheet.View.FreezePanes(2, 1); sheet.Cells[1, 1, rowsCount, columnsCount].Style.Numberformat.Format = "@"; ExcelRange range = sheet.Cells[1, 1, sheet.Dimension.End.Row, sheet.Dimension.End.Column]; sheet.Tables.Add(range, arkusz); sheet.Cells.AutoFitColumns(10, 50); } // ------------------------------------------------------------------------------- try { FileStream fileStream = new FileStream(Path.Combine(startupPath, "xml.xlsx"), FileMode.Create); Console.WriteLine("\nZapis pliku XLS..."); excelPackage.SaveAs(fileStream); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("\nPlik zapisano pomyślnie."); Console.ForegroundColor = defaultColor; } catch (Exception e) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine('\n' + e.Message); Console.ForegroundColor = defaultColor; } } Console.ReadKey(true); }
public HelpAbout() { LogFile.WriteLine("instantiating HelpAbout"); //MenuController.GetInstance().RegisterMainMenu(new string[]{ "&Help","&About..." }, new MainMenuCallback( About ) ); ContextMenuController.GetInstance().RegisterPersistentContextMenu(new string[] { "&Help", "&About..." }, new ContextMenuHandler(About)); }
public bool UpdateData(string sql, string[] paraNames, object[] paraValues, SqlDbType[] paraTypes) { if (!multiStatement) { if (!OpenConnection()) { return(false); } } try { SqlCommand sqlcm = new SqlCommand(); sqlcm.CommandText = sql; sqlcm.CommandType = CommandType.Text; sqlcm.CommandTimeout = _timeOut; sqlcm.Connection = connection; sqlcm.Transaction = strMain; if (paraNames != null) { for (int i = 0; i < paraNames.Length; i++) { SqlParameter sqlpara; sqlpara = new SqlParameter(paraNames[i], paraValues[i]); sqlpara.SqlDbType = paraTypes[i]; sqlcm.Parameters.Add(sqlpara); } } sqlcm.ExecuteNonQuery(); if (sql.ToLower().Contains("insert into systable")) { DesignLog.SqlError(sql + paraValues[0].ToString()); } if (sql.ToLower().Contains("insert into sysfield")) { DesignLog.SqlError(sql + paraValues[0].ToString()); } if (sql.ToLower().Contains("update systable")) { DesignLog.SqlError(sql + paraValues[0].ToString()); } if (sql.ToLower().Contains("update sysfield")) { DesignLog.SqlError(sql + paraValues[0].ToString()); } if (!multiStatement) { strMain.Commit(); } LogFile.LogTruyXuatDL(sql + "/n" + paraNames.ToString() + "/n" + paraValues.ToString()); return(true); } catch (SqlException se) { if (!multiStatement) { strMain.Rollback(); } hasErrors = true; string sql1 = sql; foreach (object o in paraValues) { sql1 += "-" + o.ToString(); } LogFile.SqlError(sql1, se); return(false); } finally { if (!multiStatement) { CloseConnection(); } } }
public bool UpdateDatabyPara(string sql, string[] paraNames, object[] paraValues) { SqlCommand sqlcm = new SqlCommand(); sqlcm.CommandText = sql; sqlcm.CommandType = CommandType.Text; sqlcm.CommandTimeout = _timeOut; sqlcm.Connection = connection; if (multiStatement) { sqlcm.Transaction = this.strMain; } if (!multiStatement) { if (!OpenConnection()) { return(false); } } if (paraNames != null) { for (int i = 0; i < paraNames.Length; i++) { SqlParameter sqlpara; sqlpara = new SqlParameter(paraNames[i], paraValues[i]); sqlcm.Parameters.Add(sqlpara); } } try { LogFile.LogTruyXuatDL(sql + "/n" + paraNames.ToString() + "/n" + paraValues.ToString()); int r = sqlcm.ExecuteNonQuery(); return(true); } catch (SqlException se) { if (!multiStatement) { strMain.Rollback(); } hasErrors = true; string sql1 = sql; foreach (object o in paraValues) { string value; if (o == null) { value = ""; } else { value = o.ToString(); } sql1 += "-" + value; } LogFile.SqlError(sql1, se); return(false); } finally { if (!multiStatement) { CloseConnection(); } } }
/// <summary> /// Update Learning Story details /// </summary> /// <returns></returns> public ResponseStatus Update(string userID) { // Check record version. Do not allow update if version is different if (!IsTheSameRecordVersion(this.UID, this.RecordVersion)) { return(new ResponseStatus() { ReturnCode = -0010, ReasonCode = 0001, Message = "Record updated previously by another user." }); } string commandString = ( "UPDATE LearningStory " + " SET " + FieldName.UID + "= @" + FieldName.UID + ", " + FieldName.FKChildUID + "= @" + FieldName.FKChildUID + ", " + FieldName.FKEducatorUID + "= @" + FieldName.FKEducatorUID + ", " + FieldName.FKRoomCode + "= @" + FieldName.FKRoomCode + ", " + FieldName.Date + "= @" + FieldName.Date + ", " + FieldName.Story + "= @" + FieldName.Story + ", " + FieldName.AnalysisOfLearning + "= @" + FieldName.AnalysisOfLearning + ", " + FieldName.ExtensionOfLearning + "= @" + FieldName.ExtensionOfLearning + ", " + FieldName.ParentsComments + "= @" + FieldName.ParentsComments + ", " + FieldName.UpdateDateTime + "= @" + FieldName.UpdateDateTime + ", " + FieldName.UserIdUpdatedBy + "= @" + FieldName.UserIdUpdatedBy + ", " + FieldName.RecordVersion + "= @" + FieldName.RecordVersion + ", " + FieldName.IsVoid + "= @" + FieldName.IsVoid + " WHERE UID = @UID " ); using (var connection = new MySqlConnection(ConnectionString.GetConnectionString())) { using (var command = new MySqlCommand(cmdText: commandString, connection: connection)) { RecordVersion++; IsVoid = "N"; AddSqlParameters(command); try { connection.Open(); command.ExecuteNonQuery(); } catch (Exception ex) { LogFile.WriteToTodaysLogFile(ex.ToString(), _headerInfo.UserID); return(new ResponseStatus() { ReturnCode = -0020, ReasonCode = 0001, Message = "Error saving client. " + ex }); } } } // Delete Items // new LearningStoryItem().DeleteItems(this.UID, _headerInfo); // Add items // if (LearningOutcomes != null) { foreach (var learningOutcome in LearningOutcomes) { var lit = new LearningStoryItem().AddItem(this, learningOutcome, _headerInfo); } } if (Practices != null) { foreach (var practice in Practices) { var lit = new LearningStoryItem().AddItem(this, practice, _headerInfo); } } if (Principles != null) { foreach (var principle in Principles) { var lit = new LearningStoryItem().AddItem(this, principle, _headerInfo); } } return(new ResponseStatus()); }
/// <summary> /// Add Learning Story /// </summary> public LearningStoryAddResponse Add(LearningStoryAddRequest learningStoryAddRequest) { var response = new LearningStoryAddResponse(); response.responseStatus = new ResponseStatus(); this.UserIdCreatedBy = learningStoryAddRequest.headerInfo.UserID; this.UserIdUpdatedBy = learningStoryAddRequest.headerInfo.UserID; using (var connection = new MySqlConnection(ConnectionString.GetConnectionString())) { UID = CommonDB.GetLastUID("LearningStory") + 1; RecordVersion = 1; var commandString = ( "INSERT INTO LearningStory (" + FieldString() + ")" + " VALUES " + "( " + " @" + FieldName.UID + " ,@" + FieldName.FKChildUID + " ,@" + FieldName.FKEducatorUID + " ,@" + FieldName.FKRoomCode + " ,@" + FieldName.Date + " ,@" + FieldName.Story + " ,@" + FieldName.AnalysisOfLearning + " ,@" + FieldName.ExtensionOfLearning + " ,@" + FieldName.ParentsComments + ", @" + FieldName.UpdateDateTime + ", @" + FieldName.UserIdUpdatedBy + ", @" + FieldName.CreationDateTime + ", @" + FieldName.UserIdCreatedBy + ", @" + FieldName.RecordVersion + ", @" + FieldName.IsVoid + " )" ); using (var command = new MySqlCommand( commandString, connection)) { IsVoid = "N"; AddSqlParameters(command); command.Parameters.Add("@" + FieldName.CreationDateTime, MySqlDbType.DateTime).Value = DateTime.Now; command.Parameters.Add("@" + FieldName.UserIdCreatedBy, MySqlDbType.VarChar).Value = this.UserIdCreatedBy; //command.Parameters.Add("@" + FieldName.IsVoid, MySqlDbType.VarChar).Value = "N"; try { connection.Open(); command.ExecuteNonQuery(); } catch (Exception ex) { LogFile.WriteToTodaysLogFile(ex.ToString(), _headerInfo.UserID); var respError = new LearningStoryAddResponse(); respError.responseStatus = new ResponseStatus(); respError.responseStatus.ReturnCode = -0025; respError.responseStatus.ReasonCode = 0001; respError.responseStatus.Message = "Error adding Learning Story. " + ex; } } } // Add items if (LearningOutcomes != null) { foreach (var learningOutcome in LearningOutcomes) { if (learningOutcome.Action == "TBD") { continue; } var lit = new LearningStoryItem().AddItem(this, learningOutcome, _headerInfo); } } if (Practices != null) { foreach (var practice in Practices) { if (practice.Action == "TBD") { continue; } var lit = new LearningStoryItem().AddItem(this, practice, _headerInfo); } } if (Principles != null) { foreach (var principle in Principles) { if (principle.Action == "TBD") { continue; } var lit = new LearningStoryItem().AddItem(this, principle, _headerInfo); } } return(response); }
internal byte[] GetResponse(byte[] ResponsePattern) { byte[] ResponseBuffer = new byte[0x2000]; int Length = 0; bool IsIncomplete = false; do { IsIncomplete = false; try { int BytesRead = 0; if (Port != null) { BytesRead = Port.Read(ResponseBuffer, Length, ResponseBuffer.Length - Length); } if (USBDevice != null) { BytesRead = USBDevice.InputPipe.Read(ResponseBuffer); } if (BytesRead == 0) { LogFile.Log("Emergency mode of phone is ignoring us", LogType.FileAndConsole); throw new BadMessageException(); } Length += BytesRead; byte[] DecodedResponse; if (DecodeResponses) { DecodedResponse = DecodeResponse(ResponseBuffer, (UInt32)Length); } else { DecodedResponse = new byte[Length]; Buffer.BlockCopy(ResponseBuffer, 0, DecodedResponse, 0, Length); } if (ResponsePattern != null) { for (int i = 0; i < ResponsePattern.Length; i++) { if (DecodedResponse[i] != ResponsePattern[i]) { byte[] LogResponse = new byte[DecodedResponse.Length < 0x10 ? DecodedResponse.Length: 0x10]; LogFile.Log("Qualcomm serial response: " + Converter.ConvertHexToString(LogResponse, ""), LogType.FileOnly); LogFile.Log("Expected: " + Converter.ConvertHexToString(ResponsePattern, ""), LogType.FileOnly); throw new BadMessageException(); } } } return(DecodedResponse); } catch (IncompleteMessageException) { IsIncomplete = true; } catch { } // Will be rethrown as BadConnectionException }while (IsIncomplete); if (Port != null) { Port.DiscardInBuffer(); } if (USBDevice != null) { USBDevice.InputPipe.Flush(); } throw new BadConnectionException(); }
/// <summary> /// 写日志 /// </summary> public static void WriteLog(LogFile logFile, string msg) { WriteLog(logFile.ToString(), msg); }
public virtual void ProcessCurrentDelayed(List <Task <DeviceDetails> > taskQueue, EnvironmentReference environmentContext, LogFile file) { taskQueue.Add(ProcessBatch(new LogFile(environmentContext, file.Queue))); }
protected void btnCreateUser_Click(object sender, EventArgs e) { ActivityTracker.Track("Created a New User", (int)UserActionEnum.Created); try { // Create instance of role manager and store RoleStore <IdentityRole> roleStore = new RoleStore <IdentityRole>(); RoleManager <IdentityRole> roleMgr = new RoleManager <IdentityRole>(roleStore); if (!roleMgr.RoleExists(ddlRole.Text)) { IdentityResult roleResult = roleMgr.Create(new IdentityRole(ddlRole.Text)); } // Declare UserStore and UserManager UserStore <IdentityUser> userStore = new UserStore <IdentityUser>(); UserManager <IdentityUser> manager = new UserManager <IdentityUser>(userStore); // Declare/create new user and store in manager object in the userstore IdentityUser user = new IdentityUser(txtUsername.Text); user.Email = txtEmail.Text; // Store result of user creation IdentityResult idResult = manager.Create(user, txtPassword.Text); // Check if user was created and added to role if (idResult.Succeeded) { // Add user to role IdentityResult userResult = manager.AddToRole(user.Id, ddlRole.SelectedValue); lblMessage.Text = "User " + user.UserName + " was created successfully!"; lblMessage.CssClass = "text-success"; // Add other user information to separate table HPSUser hpsUser = new HPSUser(); hpsUser.FirstName = txtUserFirstName.Text; hpsUser.LastName = txtUserLastName.Text; hpsUser.CreatedOn = DateTime.Now; hpsUser.UserId = user.Id; hpsUser.RoleName = ddlRole.SelectedValue; db.HPSUsers.Add(hpsUser); // Add empty row to db for fitbit to help with update if sign up date is on the same day as a synchronization db.Steps.AddOrUpdate(new Step { StepCount = 0, StepDate = DateTime.Now.AddDays(-28), UserId = user.Id }); db.Distances.AddOrUpdate(new Distance { DistanceCount = 0, DistanceDate = DateTime.Now.AddDays(-28), UserId = user.Id }); db.Minutes.AddOrUpdate(new Minute { MinuteCount = 0, MinuteDate = DateTime.Now.AddDays(-28), UserId = user.Id }); // create notification for admin users string[] role = { "Administrator" }; NotificationCreator.CreateNotification(role, "User Created", Page.User.Identity.Name + " created the user named '" + user.UserName + "'.", DateTime.Now, "Info", null, null); // Save changes tgo db db.SaveChanges(); } else { lblMessage.Text = idResult.Errors.FirstOrDefault(); } } catch (DataException dx) { lblMessage.Text = "A data error occured. Please try again later or contact your Administrator if this continues to happen."; LogFile.WriteToFile("UserManager.aspx.cs", "btnCreateUser_Click", dx, "Data error when creating user", "HPSErrorLog.txt"); } catch (Exception ex) { lblMessage.Text = "An error occured. Please try again later or contact your Administrator if this continues to happen."; LogFile.WriteToFile("UserManager.aspx.cs", "btnCreateUser_Click", ex, "Error when creating user", "HPSErrorLog.txt"); } }
public virtual Task <DeviceDetails> ProcessBatch(LogFile measures) { throw new NotImplementedException(); }
public EDI315MsgParsing() { logFile = new LogFile(); context = new DBContext(); }
protected override void Execute(CodeActivityContext executionContext) { Boolean Logging = EnableLogging.Get(executionContext); string LogFilePath = LogFile.Get(executionContext); EntityReference Letter = LetterId.Get(executionContext); EntityReference Attachment = AttachmentId.Get(executionContext); try { if (Logging) { Log("Workflow Execution Start", LogFilePath); } // Create a CRM Service in Workflow. IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>(); IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>(); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); if (Logging) { Log("Retrieving Attachment", LogFilePath); } Entity TempAttachment = service.Retrieve("annotation", Attachment.Id, new ColumnSet(true)); if (TempAttachment != null) { if (Logging) { Log("Creating New Attachment", LogFilePath); } // Create an attachment. Entity NewAttachment = new Entity("annotation"); if (TempAttachment.Contains("subject")) { NewAttachment.Attributes.Add("subject", TempAttachment["subject"]); } if (TempAttachment.Contains("filename")) { NewAttachment.Attributes.Add("filename", TempAttachment["filename"]); } if (TempAttachment.Contains("notetext")) { NewAttachment.Attributes.Add("notetext", TempAttachment["notetext"]); } if (TempAttachment.Contains("mimetype")) { NewAttachment.Attributes.Add("mimetype", TempAttachment["mimetype"]); } if (TempAttachment.Contains("documentbody")) { NewAttachment.Attributes.Add("documentbody", TempAttachment["documentbody"]); } NewAttachment.Attributes.Add("objectid", new EntityReference(Letter.LogicalName, Letter.Id)); service.Create(NewAttachment); if (Logging) { Log("New Attachment Added To Letter", LogFilePath); } } else { if (Logging) { Log("Temp Attachment does not exist", LogFilePath); } } if (Logging) { Log("Workflow Executed Successfully", LogFilePath); } } catch (Exception ex) { Log(ex.Message, LogFilePath); } }
private BSAArchive(string archivepath, LogFile theLog, bool verbose) { if (!File.Exists(archivepath)) { theLog.WriteLog("Archive not found " + archivepath); return; } if (verbose) { theLog.WriteLog("Using " + archivepath); } BSAHeader header; name = archivepath.ToLower(); FileInfo file = new FileInfo(archivepath); BinaryReader binary = new BinaryReader(file.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite), System.Text.Encoding.Default); header = new BSAHeader(binary); //theLog.WriteLog(archivepath + " version " + header.bsaVersion); if (header.bsaVersion != 0x67 && header.bsaVersion != 0x68) { theLog.WriteLog("Unknown BSA version " + archivepath); binary.Close(); return; } if ((header.archiveFlags & 0x4) > 0) { defaultCompressed = true; } else { defaultCompressed = false; } if ((header.archiveFlags & 0x100) > 0) { defaultFlag9 = true; } else { defaultFlag9 = false; } //theLog.WriteLog(name + " is compressed? " + defaultCompressed + " flags " + header.archiveFlags); BSAFolderInfo[] folderInfo = new BSAFolderInfo[header.folderCount]; BSAFileInfo[] fileInfo = new BSAFileInfo[header.fileCount]; for (int index = 0; index < header.folderCount; index++) { folderInfo[index] = new BSAFolderInfo(binary); } int count = 0; for (uint index = 0; index < header.folderCount; index++) { byte b = binary.ReadByte(); if (b > 0) { folderInfo[index].path = new string(binary.ReadChars(b - 1)); } else { folderInfo[index].path = ""; } binary.BaseStream.Position++; folderInfo[index].offset = count; for (int index2 = 0; index2 < folderInfo[index].count; index2++) { fileInfo[count + index2] = new BSAFileInfo(binary, defaultCompressed); } count += folderInfo[index].count; } for (uint index = 0; index < header.fileCount; index++) { fileInfo[index].path = ""; char c; while ((c = binary.ReadChar()) != '\0') { fileInfo[index].path += c; } } binary.Close(); for (int index = 0; index < header.folderCount; index++) { for (int index2 = 0; index2 < folderInfo[index].count; index2++) { BSAFileInfo bsaFileInfo = fileInfo[folderInfo[index].offset + index2]; BSAArchiveFileInfo bsaArchiveFileInfo = new BSAArchiveFileInfo(this, (int)bsaFileInfo.offset, bsaFileInfo.size); string filepath = Path.Combine(folderInfo[index].path, bsaFileInfo.path); //theLog.WriteLog(archivepath + " file = " + filepath + " off = " + bsaFileInfo.offset + " size = " + bsaFileInfo.size + " compressed = " + bsaArchiveFileInfo.compressed); FileList[filepath.ToLower()] = bsaArchiveFileInfo; } } LoadedArchives.Add(this); }
public CodeValue Read(bool checkOnly) { CodeValue ret = null; // // EA SQL database // da using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = string.Format( " SELECT FKCodeType " + " ,ID " + " ,Description " + " ,Abbreviation " + " ,ValueExtended " + " FROM rdCodeValue" + " WHERE FKCodeType = '{0}' " + " AND ID = '{1}' ", FKCodeType, this.ID); using (var command = new MySqlCommand( commandString, connection)) { try { connection.Open(); if (connection.State != System.Data.ConnectionState.Open) { LogFile.WriteToTodaysLogFile(connection.ServerThread.ToString()); return(null); } MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { if (!checkOnly) { FKCodeType = reader["FKCodeType"] as string; ID = reader["ID"] as string; Description = reader["Description"] as string; Abbreviation = reader["Abbreviation"] as string; ValueExtended = reader["ValueExtended"] as string; } FoundinDB = true; } else { FoundinDB = false; } } catch (Exception ex) { Description = ex.ToString(); LogFile.WriteToTodaysLogFile(this.Description, Helper.Utils.UserID, null, "ProcessRequestCodeValues.cs"); throw new Exception(ex.ToString()); } } } return(ret); }
public static void WriteLog(LogFile logFile, string msg) { logManager.WriteLog(logFile, msg); }
static void Main(string[] args) { double batchDataSize = 100000; //kB bool showHelp = false; string sourceServerName = null, sourceUsername = null, sourcePassword = null, sourceDatabaseName = null, destinationServerName = null, destinationUsername = null, destinationPassword = null, destinationDatabaseName = null; bool clearDestinationDatabase = false, checkIdentityExists = false; bool periodicBackup = false; string backupFilePath = null; IEnumerable<string> ignoredTables = Enumerable.Empty<string>(); var optionSet = new OptionSet() { { "h|help", "show this message and exit", x => showHelp = x != null}, { "srcserver=", "source server (eg. db000.appharbor.net)", x => sourceServerName = x }, { "srcusername="******"username on source server", x => sourceUsername = x }, { "srcpassword="******"password on source server", x => sourcePassword = x }, { "srcdatabasename=", "source database name", x => sourceDatabaseName = x }, { "dstserver=", "destination server", x => destinationServerName = x }, { "dstusername="******"username on destination server", x => destinationUsername = x }, { "dstpassword="******"password on destination server", x => destinationPassword = x }, { "dstdatabasename=", "destination database name", x => destinationDatabaseName = x }, { "ignoretables=", "names of tables not to copy", x => ignoredTables = x.Split(',') }, { "cleardstdatabase", "clears the destination database before copying the data", x => clearDestinationDatabase = x != null }, { "checkidentityexists", "only reseed identity if table has identity column", x => checkIdentityExists = x != null }, { "periodicBackup", "create full backup version of the source database", x => periodicBackup = x != null }, { "backupFilePath", "backup file path if you want to store on an external backup disc, leave blank for default. If set ensure filepath exists and is writable", x => backupFilePath = x } }; try { optionSet.Parse(args); if (showHelp) { ShowHelp(optionSet); return; } //Use settings from App.config if specified so can be more conveniently configured as a scheduled task sourceServerName = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["sourceServerName"]) ? sourceServerName : ConfigurationSettings.AppSettings["sourceServerName"]; sourceUsername = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["sourceUsername"]) ? sourceUsername : ConfigurationSettings.AppSettings["sourceUsername"]; sourcePassword = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["sourcePassword"]) ? sourcePassword : ConfigurationSettings.AppSettings["sourcePassword"]; sourceDatabaseName = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["sourceDatabaseName"]) ? sourceDatabaseName : ConfigurationSettings.AppSettings["sourceDatabaseName"]; destinationServerName = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["destinationServerName"]) ? destinationServerName : ConfigurationSettings.AppSettings["destinationServerName"]; destinationUsername = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["destinationUsername"]) ? destinationUsername : ConfigurationSettings.AppSettings["destinationUsername"]; destinationPassword = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["destinationPassword"]) ? destinationPassword : ConfigurationSettings.AppSettings["destinationPassword"]; destinationDatabaseName = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["destinationDatabaseName"]) ? destinationDatabaseName : ConfigurationSettings.AppSettings["destinationDatabaseName"]; ignoredTables = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["ignoredTables"]) ? ignoredTables : ConfigurationSettings.AppSettings["ignoredTables"].Split(','); clearDestinationDatabase = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["clearDestinationDatabase"]) ? clearDestinationDatabase : ConfigurationSettings.AppSettings["clearDestinationDatabase"] == "true"; checkIdentityExists = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["checkIdentityExists"]) ? checkIdentityExists : ConfigurationSettings.AppSettings["checkIdentityExists"] == "true"; periodicBackup = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["periodicBackup"]) ? periodicBackup : ConfigurationSettings.AppSettings["periodicBackup"] == "true"; backupFilePath = String.IsNullOrEmpty(ConfigurationSettings.AppSettings["backupFilePath"]) ? backupFilePath : ConfigurationSettings.AppSettings["backupFilePath"]; if (sourceServerName == null) { throw new OptionException("source server not specified", "srcserver"); } if (sourceUsername == null && sourcePassword != null) { throw new OptionException("source username not specified", "srcusername"); } if (sourcePassword == null && sourceUsername != null) { throw new OptionException("source password not specified", "srcpassword"); } if (sourceDatabaseName == null) { throw new OptionException("source database name not specified", "srcdatabasename"); } if (destinationServerName == null) { throw new OptionException("destination server not specified", "dstserver"); } if (destinationUsername == null && destinationPassword != null) { throw new OptionException("destination username not specified", "dstusername"); } if (destinationPassword == null && destinationUsername != null) { throw new OptionException("destination password not specified", "dstpassword"); } if (!periodicBackup && destinationDatabaseName == null) //for periodic backup we create databases daily so not required { throw new OptionException("destination database name not specified", "dstdatabasename"); } } catch (OptionException exception) { Console.Write(string.Format("{0}: ", AppDomain.CurrentDomain.FriendlyName)); Console.WriteLine(exception.Message); Console.WriteLine("Try {0} --help for more information", AppDomain.CurrentDomain.FriendlyName); return; } Console.WriteLine("Retrieving source database table information..."); var usingTrustedConnection = string.IsNullOrEmpty(sourceUsername) && string.IsNullOrEmpty(sourcePassword); var sourceConnection = usingTrustedConnection ? new ServerConnection(sourceServerName) { LoginSecure = true } : new ServerConnection(sourceServerName, sourceUsername, sourcePassword); var sourceServer = new Server(sourceConnection); var sourceDatabase = sourceServer.Databases[sourceDatabaseName]; var tables = sourceDatabase.Tables .OfType<Table>() .Where(x => !x.IsSystemObject) .Select(x => '[' + x.Schema + ']' + ".[" + x.Name + ']') .ToList(); var actualExcludedTables = tables.Intersect(ignoredTables); if (actualExcludedTables.Any()) { Console.WriteLine(string.Format("Ignoring: {0}", string.Join(",", actualExcludedTables))); } tables = tables.Except(ignoredTables).ToList(); Console.WriteLine(string.Format("Copying {0} tables: {1}", tables.Count(), string.Join(",", tables))); var destinationConnectionString = GetConnectionString(destinationServerName, destinationDatabaseName, destinationUsername, destinationPassword); var sourceConnectionString = GetConnectionString(sourceServerName, sourceDatabaseName, sourceUsername, sourcePassword); var watch = Stopwatch.StartNew(); // clear the data before copying if (!periodicBackup && clearDestinationDatabase) //no need to clear if doing backups { using (var connection = new SqlConnection(destinationConnectionString)) { using (SqlCommand command = connection.CreateCommand()) { // http://stackoverflow.com/questions/155246/how-do-you-truncate-all-tables-in-a-database-using-tsql/156813#156813 StringBuilder commandBuilder = new StringBuilder(); commandBuilder.Append( @" -- disable all constraints EXEC sp_msforeachtable ""ALTER TABLE ? NOCHECK CONSTRAINT all"" -- delete data in all tables EXEC sp_msforeachtable ""DELETE FROM ?"" -- enable all constraints exec sp_msforeachtable ""ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"" "); if (checkIdentityExists) { // http://stackoverflow.com/questions/6542061/reseed-sql-server-identity-columns commandBuilder.Append( @"-- reseed (auto increment to 0) on user tables with identity column DECLARE @reseedSql NVARCHAR(MAX); SET @reseedSql = N''; SELECT @reseedSql = @reseedSql + N'DBCC CHECKIDENT(''' + QUOTENAME(OBJECT_SCHEMA_NAME(col.[object_id])) + '.' + QUOTENAME(OBJECT_NAME(col.[object_id])) + ''', RESEED, 0);' + CHAR(13) + CHAR(10) FROM sys.columns as col JOIN sys.tables as tbl ON col.[object_id] = tbl.[object_id] WHERE tbl.[type] = 'U' AND col.[is_identity] = 1; EXEC sp_executesql @reseedSql;"); } else { commandBuilder.Append(@" -- reseed (auto increment to 0) EXEC sp_msforeachtable ""DBCC CHECKIDENT ( '?', RESEED, 0)"" "); } command.CommandText = commandBuilder.ToString(); Console.WriteLine("Clearing the destination database"); connection.Open(); command.ExecuteNonQuery(); } } } /// If we are running to create a periodic backup if(periodicBackup) { Console.WriteLine("Creating backup database with filename format databasename_dd-MMM-HH-mm-ss"); //create a database name based on the date var dateFilename = DateTime.UtcNow.ToString("dd-MMM-HH-mm-ss"); var newDatabaseName = String.Format("{0}_{1}", sourceDatabaseName, dateFilename); var newDatabaseData = String.Format("{0}_{1}_Data", sourceDatabaseName, dateFilename); var mdfPath = String.Format("{0}{1}_{2}.mdf", backupFilePath, sourceDatabaseName, dateFilename); var newDatabaseLog = String.Format("{0}_{1}_log", sourceDatabaseName, dateFilename); var ldfPath = String.Format("{0}{1}_{2}_log.ldf", backupFilePath, sourceDatabaseName, dateFilename); try { using (SqlConnection sourceCon = new SqlConnection(sourceConnectionString)) { ServerConnection sourceServerConnection = new ServerConnection(sourceCon); Server sourceServ = new Server(sourceServerConnection); Database db; db = sourceServ.Databases[sourceDatabaseName]; //Create a new database that is to be destination database. using (SqlConnection destCon = new SqlConnection(destinationConnectionString)) { ServerConnection destinationServerConnection = new ServerConnection(destCon); Server destinationServer = new Server(destinationServerConnection); Database dbCopy; dbCopy = new Database(destinationServer, newDatabaseName); //if being backed up to non default location if (!String.IsNullOrEmpty(backupFilePath)) { //Adding Primary FileGroup dbCopy.FileGroups.Add(new FileGroup(dbCopy, "PRIMARY")); DataFile dtPrimary = new DataFile(dbCopy.FileGroups["PRIMARY"], newDatabaseData, mdfPath); dtPrimary.GrowthType = FileGrowthType.Percent; dtPrimary.Growth = 7; dbCopy.FileGroups["PRIMARY"].Files.Add(dtPrimary); //Adding LogFile LogFile logFile = new LogFile(dbCopy, newDatabaseLog, ldfPath); logFile.GrowthType = FileGrowthType.Percent; logFile.Growth = 7; dbCopy.LogFiles.Add(logFile); } //Create database. dbCopy.Create(); //Define a Transfer object and set the required options and properties. Transfer xfr; xfr = new Transfer(db); // additional options can be set here if required xfr.Options.WithDependencies = true; xfr.Options.ContinueScriptingOnError = true; xfr.DestinationDatabase = newDatabaseName; //if being backed up to non default location if (!String.IsNullOrEmpty(backupFilePath)) { xfr.TargetLogFilePath = ldfPath; xfr.TargetDatabaseFilePath = mdfPath; } xfr.CopyData = false; // not used as we are doing this below and was causing memory issues for me doing it this way with App Harbor db server - but would be simpler xfr.DestinationServer = destinationServer.Name; xfr.DestinationLoginSecure = true; xfr.CopySchema = true; xfr.CopyAllDefaults = true; xfr.CopyAllSchemas = true; xfr.CopyAllStoredProcedures = true; xfr.CopyAllTables = true; xfr.CopyAllUserDefinedAggregates = true; xfr.CopyAllUserDefinedDataTypes = true; xfr.CopyAllUserDefinedFunctions = true; xfr.CopyAllUserDefinedTableTypes = true; xfr.CopyAllUserDefinedTypes = true; xfr.CopyAllViews = true; xfr.Options.Default = true; xfr.Options.Indexes = true; xfr.Options.DriDefaults = true; xfr.Options.DriAllKeys = true; xfr.Options.DriForeignKeys = true; xfr.Options.DriIndexes = true; xfr.Options.DriPrimaryKey = true; xfr.Options.DriUniqueKeys = true; xfr.TransferData(); } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } //reset this to the new database now it's been created destinationConnectionString = GetConnectionString(destinationServerName, newDatabaseName, destinationUsername, destinationPassword); } foreach (var table in tables) { using (var connection = new SqlConnection(sourceConnectionString)) { double rowBatchSize = 10000; double rows = 0; double dataSize; connection.Open(); using (var command = connection.CreateCommand()) { command.CommandText = string.Format("exec sp_spaceused '{0}'", table); using (var reader = command.ExecuteReader()) { reader.Read(); var rowString = (string)reader["rows"]; rows = double.Parse(rowString); var dataSizeString = (string)reader["data"]; dataSize = double.Parse(dataSizeString.Split(' ').First()); //kB if (rows > 0 && dataSize > 0) { double rowSize = dataSize / rows; rowBatchSize = (int)(batchDataSize / rowSize); } } } if (rows > 0) { var columns = GetColumnNames(connection, table); Console.Write(string.Format("Copying {0} - {1} rows, {2:0.00} MB: ", table, rows, dataSize/1024)); using (var command = connection.CreateCommand()) { command.CommandText = string.Format("select * from {0}", table); using (var reader = command.ExecuteReader()) { using (var bulkCopy = new SqlBulkCopy( destinationConnectionString, SqlBulkCopyOptions.KeepIdentity | SqlBulkCopyOptions.TableLock)) { bulkCopy.NotifyAfter = Math.Max((int)rows / 10, 1); bulkCopy.SqlRowsCopied += new SqlRowsCopiedEventHandler(SqlRowsCopied); bulkCopy.DestinationTableName = table; bulkCopy.BatchSize = (int)rowBatchSize; bulkCopy.BulkCopyTimeout = int.MaxValue; foreach (var columnName in columns) { bulkCopy.ColumnMappings.Add(columnName, columnName); } bulkCopy.WriteToServer(reader); } } } Console.WriteLine(); } else { Console.WriteLine(string.Format("{0} had no rows", table)); } } } watch.Stop(); Console.WriteLine("Copy complete, total time {0} s", watch.ElapsedMilliseconds/1000); }
public static void Load(StringList files, LogFile theLog, bool verbose) { foreach (string s in files) { new BSAArchive(s, theLog, verbose); } }
private void CheckDateString(string expected, string filename) { string actual = new LogFile(filename).FilenameFormattedDateString; Assert.AreEqual(expected, actual); }
//Sends an updated position to the decison system public bool OnUpdatePosition(JObject model) { #if DEBUG try { string time = model["time"].ToString(); string lat = model["lat"].ToString(); string lon = model["long"].ToString(); string alt = model["alt"].ToString(); string userID = model["userID"].ToString(); } catch (Exception e) { // catches the exception if any of the keys are missing Console.WriteLine(e.Source); return(false); } return(true); #else //string time = model["time"].ToString(); //string userID = model["userID"].ToString(); try { double lat = (double)model["lat"]; double lon = (double)model["lon"]; double alt = (double)model["alt"]; model["lat"] = lat; model["lon"] = lon; model["alt"] = alt; WebRequest request = WebRequest.Create(dm_url + "LocationChange"); request.ContentType = "application/json"; request.Method = "POST"; using (var streamWriter = new StreamWriter(request.GetRequestStream())) { streamWriter.Write(model.ToString()); streamWriter.Flush(); streamWriter.Close(); } try { using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { if (response.StatusCode != HttpStatusCode.OK) { throw new Exception(String.Format( "Server error (HTTP {0}: {1}).", response.StatusCode, response.StatusDescription)); } } } catch (WebException we) { LogFile.AddLog("UpdateLocation -- Could not create the URL with the data provided: " + we.Message + "\n"); return(false); } } catch (SystemException ex) { LogFile.AddLog("UpdateLocation -- Could not create the URL with the data provided: " + ex.Message + "\n"); return(false); } return(true); #endif }
public void WriteLog(LogFile logFile, string msg) { this.WriteLog(logFile.ToString(), msg); }
/// <summary> /// Starts the service. /// </summary> public bool StartService() { #if DEBUG System.Diagnostics.Debugger.Launch(); #endif // load instance configuration AppDirs.Init(Assembly.GetExecutingAssembly()); InstanceConfig instanceConfig = new InstanceConfig(); Locale.SetCultureToEnglish(); if (instanceConfig.Load(InstanceConfig.GetConfigFileName(AppDirs.InstanceDir), out string errMsg)) { Locale.SetCulture(instanceConfig.Culture); AppDirs.UpdateLogDir(instanceConfig.LogDir); } else { Console.WriteLine(errMsg); Locale.SetCultureToDefault(); } // initialize log LogFile logFile = new LogFile(LogFormat.Full, Path.Combine(AppDirs.LogDir, CommUtils.LogFileName)) { Capacity = int.MaxValue }; log = logFile; log.WriteBreak(); // prepare to start service log.WriteAction(Locale.IsRussian ? "Коммуникатор {0} запущен" : "Communicator {0} started", EngineUtils.AppVersion); storageWrapper = new StorageWrapper(new StorageContext { App = ServiceApp.Comm, AppDirs = AppDirs, Log = log }, instanceConfig); CommConfig appConfig = new CommConfig(); if (AppDirs.CheckExistence(out errMsg) && LocalizeApp() && storageWrapper.InitStorage() && appConfig.Load(storageWrapper.Storage, CommConfig.DefaultFileName, out errMsg)) { // start service logFile.CapacityMB = appConfig.GeneralOptions.MaxLogSize; coreLogic = new CoreLogic(appConfig, AppDirs, storageWrapper.Storage, log); if (coreLogic.StartProcessing()) { return(true); } } else if (!string.IsNullOrEmpty(errMsg)) { log.WriteError(errMsg); } log.WriteError(CommonPhrases.ExecutionImpossible); return(false); }
/// <summary> /// Add Learning Story /// </summary> public ChildRoomAddResponse Add(ChildRoomAddRequest childRoomAddRequest) { this.UserIdCreatedBy = childRoomAddRequest.headerInfo.UserID; this.UserIdUpdatedBy = childRoomAddRequest.headerInfo.UserID; using (var connection = new MySqlConnection(ConnectionString.GetConnectionString())) { UID = CommonDB.GetLastUID("ChildRoom") + 1; RecordVersion = 1; var commandString = ( "INSERT INTO LearningStory (" + FieldString() + ")" + " VALUES " + "( " + " @" + FieldName.UID + " ,@" + FieldName.FKChildUID + " ,@" + FieldName.FKRoomUID + " ,@" + FieldName.StartDate + " ,@" + FieldName.EndDate + ", @" + CommonDB.FieldName.UpdateDateTime + ", @" + CommonDB.FieldName.UserIdUpdatedBy + ", @" + CommonDB.FieldName.CreationDateTime + ", @" + CommonDB.FieldName.UserIdCreatedBy + ", @" + CommonDB.FieldName.RecordVersion + ", @" + CommonDB.FieldName.IsVoid + " )" ); using (var command = new MySqlCommand( commandString, connection)) { AddSqlParameters(command); command.Parameters.Add("@" + LearningStory.FieldName.CreationDateTime, MySqlDbType.DateTime).Value = DateTime.Now; command.Parameters.Add("@" + LearningStory.FieldName.UserIdCreatedBy, MySqlDbType.VarChar).Value = this.UserIdCreatedBy; command.Parameters.Add("@" + LearningStory.FieldName.IsVoid, MySqlDbType.VarChar).Value = "N"; try { connection.Open(); command.ExecuteNonQuery(); } catch (Exception ex) { LogFile.WriteToTodaysLogFile(ex.ToString(), _headerInfo.UserID); return(new ChildRoomAddResponse { responseStatus = { ReturnCode = -0025, ReasonCode = 0001, Message = "Error adding Learning Story. " + ex } }); } return(new ChildRoomAddResponse { responseStatus = { ReturnCode = 0001, ReasonCode = 0001 } }); } } }
/// <summary> /// 写日志 /// </summary> public static void WriteLog(LogFile logFile, string msg) { WriteLog(logFile.ToString(), msg); }
public bool StateUpdate(JObject model) { UInt64 houseId, roomId; string deviceType; UInt64 deviceId; #if DEBUG try { houseId = (UInt64)model["houseID"]; // houseID is the correct key and is type UInt64 roomId = (UInt64)model["roomID"]; // roomID is the correct key and is type UInt64 deviceType = (string)model["Type"]; // Type is the correct key and is type string } catch (Exception ex) { // catches the exception if any of the keys are missing LogFile.AddLog("Decision -- Invalid Keys: " + ex.Message + "\n"); return(false); } #else try { houseId = (UInt64)model["houseID"]; // houseID is the correct key and is type UInt64 roomId = (UInt64)model["roomID"]; // roomID is the correct key and is type UInt64 deviceType = (string)model["Type"]; // Type is the correct key and is type string WebRequest request = WebRequest.Create(houseApiHost + "/" + houseId + "/" + roomId + "/" + deviceType); request.Method = "POST"; using (var streamWriter = new StreamWriter(request.GetRequestStream())) { streamWriter.Write(model.ToString()); streamWriter.Close(); } try { using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { if (response.StatusCode != HttpStatusCode.OK) { throw new Exception(String.Format( "Server error (HTTP {0}: {1}).", response.StatusCode, response.StatusDescription)); } } } catch (Exception ex) { LogFile.AddLog("Decision -- Failed to send data to the House System: " + ex.Message + "\n"); return(false); } request = WebRequest.Create(DeviceRepository.storageURL + "UD/" + (UInt64)model["HouseID"] + "/" + (UInt64)model["RoomID"] + "/" + (UInt64)model["DeviceID"]); request.Method = "POST"; using (var streamWriter = new StreamWriter(request.GetRequestStream())) { streamWriter.Write(model.ToString()); streamWriter.Close(); } try { using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { if (response.StatusCode != HttpStatusCode.OK) { throw new Exception(String.Format( "Server error (HTTP {0}: {1}).", response.StatusCode, response.StatusDescription)); } } } catch (Exception ex) { LogFile.AddLog("Decision -- Failed to send data to the Storage: " + ex.Message + "\n"); return(false); } try { #if DEBUG if (!AppCache.AddDeviceBlob_DEBUG(model)) { throw new Exception("Decision -- AppCache add device failed when adding: " + model.ToString()); } #else if (!AppCache.AddDeviceBlob(model)) { throw new Exception("Decision -- AppCache add device failed when adding: " + model.ToString()); } #endif } catch (Exception ex) { LogFile.AddLog(ex.Message + "\n"); return(false); } } catch (SystemException ex) { LogFile.AddLog("Decision -- Could not create the specified url with the data provided: " + ex.Message + "\n"); return(false); } #endif return(true); }
private static Database CreateDb(Server server, string databaseName, string directory) { var db = new Database(server, databaseName); db.DatabaseOptions.AutoClose = true; db.DatabaseOptions.AutoShrink = true; db.DatabaseOptions.UserAccess = DatabaseUserAccess.Multiple; var fileGroup = new FileGroup(db, "PRIMARY"); db.FileGroups.Add(fileGroup); var dataFile = new DataFile(fileGroup, databaseName + "_Data"); fileGroup.Files.Add(dataFile); dataFile.FileName = Path.Combine(Path.GetFullPath(directory), databaseName + ".mdf"); dataFile.Size = 5.0 * 1024.0; dataFile.Growth = 10.0; dataFile.GrowthType = FileGrowthType.Percent; var logFile = new LogFile(db, databaseName + "_Log"); db.LogFiles.Add(logFile); logFile.FileName = Path.Combine(Path.GetFullPath(directory), databaseName + ".ldf"); logFile.Size = 2.5 * 1024.0; logFile.GrowthType = FileGrowthType.Percent; logFile.Growth = 10.0; db.Create(false); return db; }
public selection(LogFile xLogFile) { m_LogFile = xLogFile; }
public static void WriteLog(LogFile logFile, string msg) { logManager.WriteLog(logFile, msg); }
private static void RecordLog() { LogFile log = new LogFile("log.txt",true); log.Println("xxxx"); log.Println("记录第二条\r\n"); Console.WriteLine("完毕"); }
public void WriteLog(LogFile logFile, string msg) { this.WriteLog(logFile.ToString(), msg); }
private async Task <string> ParsDocument(string filePath, LogFile logFile) { try { await Task.Run(() => { DateTime dateStart = DateTime.MinValue; DateTime dateEnd = DateTime.MinValue; var countFileLine = File.ReadAllLines(filePath).Length; using (var read = new StreamReader(filePath, Encoding.UTF8)) { string value; int index = 0; while (!string.IsNullOrEmpty(value = read.ReadLine())) { /*-------------------getDate from log file-----------------*/ var startDate = Regex.Match(value, RegStart, RegexOptions.IgnoreCase); if (startDate.Success) { var time = Regex.Match(value, RegDate, RegexOptions.IgnoreCase); if (time.Success) { dateStart = ConverterToDateTime(time.Value); } } var endDate = Regex.Match(value, RegEnd, RegexOptions.IgnoreCase); if (endDate.Success) { var time = Regex.Match(value, RegDate, RegexOptions.IgnoreCase); if (time.Success) { dateEnd = ConverterToDateTime(time.Value); } } /*--------------------------------------------------------------*/ /*-----------------getRequestAndResponse------------------------*/ var input = Regex.Match(value, RegInput, RegexOptions.IgnoreCase); if (input.Success) { var binarydata = Regex.Match(input.Value, RegBinData, RegexOptions.IgnoreCase); var rezult = binarydata.Success ? input.Value.Replace(binarydata.Value, "\"binary_data\":\"true\"") : input.Value; var rez = rezult.Remove(0, 8); var id = rez != "" ? GetmessageId(rez) : "notFoundInput_" + index; var rezId = id != "" ? id : "idIsNull_" + index; DataProcessor.CreateLog(rezId, dateStart, rez, DateTime.MinValue, "", logFile); } var output = Regex.Match(value, RegOutput, RegexOptions.IgnoreCase); if (output.Success) { var rez = output.Value.Remove(0, 8); var error = GetError(rez); var id = rez != "" ? GetmessageId(rez) : "notFoundOutput_" + index; var rezId = id != "" ? id : "idIsNull_" + index; DataProcessor.CreateLog(rezId, DateTime.MinValue, "", dateEnd, rez, logFile); } /*--------------------------------------------------------------*/ index++; UpdateProgBarFile((int)((index * 100.0) / countFileLine)); } } }); return("\r\nDocument " + filePath + ". completed successful! \r\nCount objetcs: " + LogsList.Count); } catch (Exception ex) { MessageBox.Show(ex.Message); } return("Error!!! " + filePath); }
public void Start() { #if UNITY_EDITOR logTeam = new LogFile[2]; for (int i = 0; i < 2; ++i) logTeam[i] = new LogFile(); logTeam[0].SetName("Assets/Scripts/Game/Autres/LOG/SouthTeam"); logTeam[1].SetName("Assets/Scripts/Game/Autres/LOG/NorthTeam"); #endif this.refs.xboxInputs.CheckNone(); this.northTeam.game = this; this.southTeam.game = this; this.northTeam.south = false; this.southTeam.south = true; this.northTeam.CreateUnits(); this.southTeam.CreateUnits(); this.Referee.game = this; this.Referee.StartPlacement(); this.northTeam.opponent = southTeam; this.southTeam.opponent = northTeam; // A changer de place this.northTeam.captain.unitAnimator.AddEvent("SuperEffect", () => { this.northTeam.Super.LaunchFeedback(); return false; }, UnitAnimator.SuperState, this.northTeam.captain.unitAnimator.TIME_SUPER_FX); // A changer de place this.southTeam.captain.unitAnimator.AddEvent("SuperEffect", () => { this.southTeam.Super.LaunchFeedback(); return false; }, UnitAnimator.SuperState, this.southTeam.captain.unitAnimator.TIME_SUPER_FX); this.refs.xboxInputs.Start(); this.p1 = new Gamer(refs.south); this.p2 = new Gamer(refs.north); this.Owner = p1.Controlled.Team; this.Ball.Game = this; this.Ball.transform.parent = p1.Controlled.BallPlaceHolderRight.transform; this.Ball.transform.localPosition = Vector3.zero; this.Ball.Owner = p1.Controlled; if (alwaysScrum) { ((GameObject.FindObjectOfType(typeof(ScrumField)) as ScrumField).collider as SphereCollider).radius = 100; settings.GameStates.MainState.PlayingState.GameActionState.ScrumingState.MaximumDuration = 200; } this.refs.managers.intro.OnFinish = () => { this.refs.managers.coin.callBack = (Team t) => { this.Ball.Owner = t.Player.Controlled; this._disableIA = true; this.Referee.OnStart(); this.refs.stateMachine.event_OnStartSignal(); }; this.refs.managers.coin.timeFlipping = 0; this.refs.managers.coin.enabled = true; }; this.refs.stateMachine.SetFirstState( new MainState(this.refs.stateMachine, this.refs.managers.camera, this) ); this.refs.managers.intro.enabled = true; xNE = refs.positions.limiteTerrainNordEst.transform.position.x; xSO = refs.positions.limiteTerrainSudOuest.transform.position.x; largeurTerrain = Mathf.Abs(xNE - xSO); section = largeurTerrain / 7f; AudioSource src; src = this.refs.CameraAudio["Ambiant"]; src.volume = 0.3f; src.loop = true; src.clip = this.refs.sounds.Ambiant; src.Play(); src = this.refs.CameraAudio["Ambiant2"]; src.volume = 0.3f; src.loop = true; src.clip = this.refs.sounds.Ambiant2; src.Play(); }
/// <summary> /// Процедура обработки скриптов /// </summary> /// <param name="nodes"></param> /// <param name="connections"></param> /// <param name="resultType"></param> private async void RunThread(IEnumerable <Node> nodes, IEnumerable <Connection> connections, int resultType) { ProcessItem.Reset(); btnCancel.IsEnabled = true; btnRunSelect.IsEnabled = false; btnRunAll.IsEnabled = false; treeQBE.IsEnabled = false; if (Settings.DelayedRun) { waitRunGroup.Visibility = System.Windows.Visibility.Visible; if (!await WaitDelayedRun(Settings.DelayedTimeSpan)) { btnCancel.IsEnabled = false; btnRunSelect.IsEnabled = btnRunAll.IsEnabled = treeQBE.IsEnabled = true; waitRunGroup.Visibility = System.Windows.Visibility.Hidden; return; } waitRunGroup.Visibility = System.Windows.Visibility.Hidden; } LogFile.WriteLog("Начало процесса выполнения скриптов..."); ProcessItem.running = true; processItems.Clear(); listThread.Clear(); int i = 1; // создать объекты ProcessItem и передать их в ListView foreach (Node node in nodes) { foreach (Connection con in connections) { if (resultType > (int)Enum.GetValues(typeof(TypeResults)).Cast <TypeResults>().Max() || resultType < (int)Enum.GetValues(typeof(TypeResults)).Cast <TypeResults>().Min()) { resultType = 1; } IResult result = null; if (resultType == (int)TypeResults.CSV) { result = new ResultCSV(); } //if (resultType == (int)TypeResults.Excel) // result = new ResultCSV(); ProcessItem processItem = new ProcessItem(i.ToString(), node.FullPath, con.Description); processItem.Status = StatusType.Process; processItem.StatusText = "Запуск"; processItems.Add(processItem); Runner runner = new Runner(node.FullPath, con.ConnectionString, con.Index, result, processItem); Thread thread = new Thread(new ThreadStart(runner.Run)); thread.Start(); listThread.Add(thread); i++; } } listViewResult.ItemsSource = processItems; ICollectionView view = CollectionViewSource.GetDefaultView(processItems); view.Refresh(); await WaitRun(); btnCancel.IsEnabled = false; btnRunSelect.IsEnabled = true; btnRunAll.IsEnabled = true; treeQBE.IsEnabled = true; LogFile.WriteLog("Окончание процесса выполнения скриптов"); }
public WHERE(LogFile xLogFile) { m_LogFile = xLogFile; }
/// <summary> /// Update client details /// </summary> /// <returns></returns> public static ResponseStatus Update(HeaderInfo headerInfo, Client client, MySqlConnection conn = null) { var response = new ResponseStatus(); response.ReturnCode = 1; response.ReasonCode = 1; response.Message = "Client Updated Successfully."; if (client.Name == null) { client.Name = ""; } if (client.Address == null) { client.Address = ""; } if (client.MainContactPersonName == null) { client.MainContactPersonName = ""; } // Check record version. Do not allow update if version is different if (!IsTheSameRecordVersion(client.UID, client.RecordVersion)) { response.ReturnCode = -0010; response.ReasonCode = 0001; response.Message = "Record updated previously by another user."; return(response); } string commandString = ( "UPDATE Client " + " SET " + FCMDBFieldName.Client.ABN + " = @" + FCMDBFieldName.Client.ABN + ", " + FCMDBFieldName.Client.RecordVersion + " = @" + FCMDBFieldName.Client.RecordVersion + ", " + FCMDBFieldName.Client.Name + " = @" + FCMDBFieldName.Client.Name + ", " + FCMDBFieldName.Client.LegalName + " = @" + FCMDBFieldName.Client.LegalName + ", " + FCMDBFieldName.Client.Address + " = @" + FCMDBFieldName.Client.Address + ", " + FCMDBFieldName.Client.Phone + " = @" + FCMDBFieldName.Client.Phone + ", " + FCMDBFieldName.Client.Fax + " = @" + FCMDBFieldName.Client.Fax + ", " + FCMDBFieldName.Client.Mobile + " = @" + FCMDBFieldName.Client.Mobile + ", " + FCMDBFieldName.Client.Logo1Location + " = @" + FCMDBFieldName.Client.Logo1Location + ", " + FCMDBFieldName.Client.Logo2Location + " = @" + FCMDBFieldName.Client.Logo2Location + ", " + FCMDBFieldName.Client.Logo3Location + " = @" + FCMDBFieldName.Client.Logo3Location + ", " + FCMDBFieldName.Client.FKUserID + " = @" + FCMDBFieldName.Client.FKUserID + ", " + FCMDBFieldName.Client.FKDocumentSetUID + " = @" + FCMDBFieldName.Client.FKDocumentSetUID + ", " + FCMDBFieldName.Client.EmailAddress + " = @" + FCMDBFieldName.Client.EmailAddress + ", " + FCMDBFieldName.Client.MainContactPersonName + " = @" + FCMDBFieldName.Client.MainContactPersonName + ", " + FCMDBFieldName.Client.DisplayLogo + " = @" + FCMDBFieldName.Client.DisplayLogo + ", " + FCMDBFieldName.Client.UpdateDateTime + " = @" + FCMDBFieldName.Client.UpdateDateTime + ", " + FCMDBFieldName.Client.UserIdUpdatedBy + " = @" + FCMDBFieldName.Client.UserIdUpdatedBy + " WHERE UID = @UID " ); using (var connection = new MySqlConnection(ConnString.ConnectionString)) { using (var command = new MySqlCommand(cmdText: commandString, connection: connection)) { client.RecordVersion++; AddSqlParameters(command, MackkadoITFramework.Helper.Utils.SQLAction.UPDATE, headerInfo, client); try { connection.Open(); command.ExecuteNonQuery(); } catch (Exception ex) { LogFile.WriteToTodaysLogFile(ex.ToString(), headerInfo.UserID); response.ReturnCode = -0020; response.ReasonCode = 0001; response.Message = "Error saving client. " + ex.ToString(); return(response); } } } return(response); }
internal LogWindow(LogFile logFile) { this.LogFile = logFile; }
void Awake() { m_logger = new LogFile(); m_logger._UnityLogFile(); }
private void Create() { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Creating Database: {0}", this.DatabaseItem.ItemSpec)); if (this.CheckDatabaseExists()) { if (this.Force) { this.Delete(); } else { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Database already exists: {0}. Set Force to true to delete an existing Database.", this.DatabaseItem.ItemSpec)); return; } } SMO.Database newDatabase = new SMO.Database(this.sqlServer, this.DatabaseItem.ItemSpec); if (this.DataFilePath != null) { FileGroup fileGroup = new FileGroup(newDatabase, this.FileGroupName); DataFile dataFile = new DataFile(fileGroup, this.DatabaseItem.ItemSpec, this.DataFilePath.GetMetadata("FullPath")); fileGroup.Files.Add(dataFile); newDatabase.FileGroups.Add(fileGroup); } if (this.LogFilePath != null) { if (string.IsNullOrEmpty(this.LogName)) { this.LogName = this.DatabaseItem.ItemSpec + "_log"; } LogFile logFile = new LogFile(newDatabase, this.LogName, this.LogFilePath.GetMetadata("FullPath")); newDatabase.LogFiles.Add(logFile); } if (!string.IsNullOrEmpty(this.Collation)) { newDatabase.Collation = this.Collation; } newDatabase.Create(); }
public void Setup() { stringResult = new StringWriter(); Console.SetOut(stringResult); _uut = new LogFile("TestFile.txt"); }