public MainForm() { InitializeComponent(); System.Runtime.Remoting.Channels.ChannelServices.RegisterChannel(new System.Runtime.Remoting.Channels.Tcp.TcpChannel(1808), false); SySal.OperaDb.OperaDbConnection conn = SySal.OperaDb.OperaDbCredentials.CreateFromRecord().Connect(); conn.Open(); System.Data.DataSet ds = new System.Data.DataSet(); new SySal.OperaDb.OperaDbDataAdapter("SELECT NAME FROM TB_MACHINES WHERE ID_SITE = (SELECT TO_NUMBER(VALUE) FROM OPERA.LZ_SITEVARS WHERE NAME = 'ID_SITE') AND ISSCANNINGSERVER = 1 ORDER BY NAME", conn, null).Fill(ds); conn.Close(); m_Servers = new ServerEntry[ds.Tables[0].Rows.Count]; int i; for (i = 0; i < ds.Tables[0].Rows.Count; i++) { m_Servers[i] = new ServerEntry(ds.Tables[0].Rows[i][0].ToString()); System.Runtime.Remoting.RemotingServices.Marshal(m_Servers[i].Server, "TrackServer_" + m_Servers[i].Name + ".rem"); System.Windows.Forms.ListViewItem lvi = TrackerList.Items.Add(m_Servers[i].Name); lvi.SubItems.Add("0"); lvi.SubItems.Add("0"); lvi.SubItems.Add("0"); lvi.SubItems.Add("0"); lvi.SubItems.Add("0"); lvi.SubItems.Add("0"); lvi.SubItems.Add(""); } m_TF = new TestForm(); }
public frmConfig(long settingsId, SySal.OperaDb.OperaDbConnection connection) { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // _connection = connection; Utilities.FillComboBox(cmbWasd, "SELECT ID, DESCRIPTION FROM TB_PROGRAMSETTINGS WHERE EXECUTABLE='" + _subDriverName + "'", _connection); if (settingsId != 0) { string settings = (string)(new SySal.OperaDb.OperaDbCommand("SELECT SETTINGS FROM TB_PROGRAMSETTINGS WHERE ID = " + settingsId, _connection)).ExecuteScalar(); System.Xml.Serialization.XmlSerializer xmls = new System.Xml.Serialization.XmlSerializer(typeof(CSScanDriverSettings)); _progSettings = (CSScanDriverSettings)xmls.Deserialize(new System.IO.StringReader(settings)); _originalConfigName = _currentConfigName = configNameTextBox.Text = (string)(new SySal.OperaDb.OperaDbCommand("SELECT DESCRIPTION FROM TB_PROGRAMSETTINGS WHERE ID = " + settingsId, _connection)).ExecuteScalar(); } else { _progSettings = new CSScanDriverSettings(); } _wasdSettingsId = _progSettings.WideAreaConfigId; //_predSettingsId = _progSettings.PredScanConfigId; //_progSettings.InitialQuery; Utilities.SelectId(cmbWasd, _wasdSettingsId); }
public static long[] Get(SySal.OperaDb.OperaDbConnection conn, long[] ids) { frmReuseSettings form = new frmReuseSettings(conn, ids); form.ShowDialog(); return(form.SelectedIds); }
public frmConfig(long settingsId, SySal.OperaDb.OperaDbConnection conn) { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // _connection = conn; Utilities.FillComboBox(linkingComboBox, @"SELECT ID, DESCRIPTION FROM TB_PROGRAMSETTINGS WHERE EXECUTABLE LIKE 'BatchLink%.exe'", conn); Utilities.FillComboBox(scanningComboBox, @"SELECT ID, DESCRIPTION FROM TB_PROGRAMSETTINGS WHERE EXECUTABLE LIKE 'ScanServer%.exe'", conn); Utilities.FillComboBox(qualityComboBox, @"SELECT ID, DESCRIPTION FROM TB_PROGRAMSETTINGS WHERE EXECUTABLE LIKE '%Sel.exe'", conn); if (settingsId != 0) { string settings = (string)(new SySal.OperaDb.OperaDbCommand("SELECT SETTINGS FROM TB_PROGRAMSETTINGS WHERE ID = " + settingsId, conn)).ExecuteScalar(); System.Xml.Serialization.XmlSerializer xmls = new System.Xml.Serialization.XmlSerializer(typeof(Intercalibration3Settings)); _progSettings = (Intercalibration3Settings)xmls.Deserialize(new System.IO.StringReader(settings)); _originalConfigName = _currentConfigName = configNameTextBox.Text = (string)(new SySal.OperaDb.OperaDbCommand("SELECT DESCRIPTION FROM TB_PROGRAMSETTINGS WHERE ID = " + settingsId, conn)).ExecuteScalar(); /*linkingComboBox.SelectedValue = _linkingConfigId; * scanningComboBox.SelectedValue = _scanningConfigId; * qualityComboBox.SelectedValue = _qualityCutId;*/ } else { _progSettings = new Intercalibration3Settings(); } posTolTextBox.Text = _progSettings.PositionTolerance.ToString(); slopeTolTextBox.Text = _progSettings.SlopeTolerance.ToString(); minMatchesTextBox.Text = _progSettings.MinMatches.ToString(); maxOffsetTextBox.Text = _progSettings.MaxOffset.ToString(); xZoneDistanceTextBox.Text = _progSettings.XZoneDistance.ToString(); yZoneDistanceTextBox.Text = _progSettings.YZoneDistance.ToString(); zoneSizeTextBox.Text = _progSettings.ZoneSize.ToString(); _linkingConfigId = _progSettings.LinkConfigId; _scanningConfigId = _progSettings.ScanningConfigId; _qualityCutId = _progSettings.QualityCutId; /*for (int i=0; i<scanningComboBox.Items.Count; i++) * { * if ( ((Utilities.ConfigItem)scanningComboBox.Items[i]).Id == _scanningConfigId ) * { * scanningComboBox.SelectedIndex = i; * break; * } * }*/ Utilities.SelectId(scanningComboBox, _scanningConfigId); Utilities.SelectId(linkingComboBox, _linkingConfigId); Utilities.SelectId(qualityComboBox, _qualityCutId); btnCreate.Enabled = ConfigNameIsValid() & IsFormFilled(); }
private void OnProcOpBeforeExpand(object sender, System.Windows.Forms.TreeViewCancelEventArgs e) { ProcOpTree.BeginUpdate(); //SySal.OperaDb.OperaDbConnection Conn = null; try { foreach (TreeNode tn in e.Node.Nodes) { if (tn.Text.Length == 0) { if (Conn == null) { Conn = new SySal.OperaDb.OperaDbConnection(Credentials.DBServer, Credentials.DBUserName, Credentials.DBPassword); Conn.Open(); } System.Data.DataSet ds = new System.Data.DataSet(); new SySal.OperaDb.OperaDbDataAdapter("SELECT /*+INDEX(TB_PROC_OPERATIONS PK_PROC_OPERATIONS) */ DESCRIPTION, EXECUTABLE, STARTTIME, SUCCESS, ID_EVENTBRICK, ID_PLATE FROM TB_PROGRAMSETTINGS INNER JOIN TB_PROC_OPERATIONS ON (TB_PROC_OPERATIONS.ID_PROGRAMSETTINGS = TB_PROGRAMSETTINGS.ID) WHERE (TB_PROC_OPERATIONS.ID = " + tn.Tag.ToString() + ")", Conn, null).Fill(ds); int image = 2; System.Data.DataRow dr = ds.Tables[0].Rows[0]; if (dr[3].ToString() == "N") { image = 1; } else if (dr[3].ToString() == "Y") { image = 0; } string addinfo = " "; if (dr[4] != System.DBNull.Value) { addinfo += "B#" + dr[4].ToString() + " "; } if (dr[5] != System.DBNull.Value) { addinfo += "P#" + dr[5].ToString() + " "; } tn.Text = "#" + tn.Tag.ToString() + ": " + dr[0].ToString() + addinfo + "(" + dr[1].ToString() + ") - (" + Convert.ToDateTime(dr[2]).ToString("dd/MM/yyyy HH:mm:ss") + ")"; tn.ImageIndex = tn.SelectedImageIndex = image; } } //if (Conn != null) Conn.Close(); ProcOpTree.EndUpdate(); } catch (Exception x) { if (Conn != null) { Conn.Close(); Conn = null; } ProcOpTree.EndUpdate(); MessageBox.Show(x.ToString(), "Error refreshing process operation information"); } }
/// <summary> /// Enqueues a batch. /// </summary> /// <param name="desc">the descriptor of the batch. If the batch is rejected because another batch in the queue already has the same id, the Id member is set to 0.</param> /// <returns>true if the batch has been accepted, false otherwise.</returns> public bool Enqueue(DataProcessingBatchDesc desc) { if (m_IsWillingToProcess[0] == false) { return(false); } SySal.OperaDb.OperaDbConnection conn = null; try { conn = new SySal.OperaDb.OperaDbConnection(OperaDataProcessingServer.DBServer, OperaDataProcessingServer.DBUserName, OperaDataProcessingServer.DBPassword); conn.Open(); SySal.OperaDb.ComputingInfrastructure.UserPermission [] rights = new SySal.OperaDb.ComputingInfrastructure.UserPermission[1]; rights[0].DB_Site_Id = OperaDataProcessingServer.IdSite; rights[0].Designator = SySal.OperaDb.ComputingInfrastructure.UserPermissionDesignator.ProcessData; rights[0].Value = SySal.OperaDb.ComputingInfrastructure.UserPermissionTriState.Grant; if (desc.Token != null) { if (!SySal.OperaDb.ComputingInfrastructure.User.CheckTokenAccess(desc.Token, rights, conn, null)) { throw new Exception("The user does not own the permission to process data in this site"); } } else { SySal.OperaDb.ComputingInfrastructure.User.CheckAccess(SySal.OperaDb.ComputingInfrastructure.User.CheckLogin(desc.Username, desc.Password, conn, null), rights, true, conn, null); } conn.Close(); conn = null; } catch (System.Exception) { if (conn != null) { conn.Close(); } return(false); } lock (m_Queue) { foreach (SySal.DAQSystem.DataProcessingBatchDesc d in m_Queue) { if (d.Id == desc.Id) { desc.Id = 0; return(false); } } desc.Finished = desc.Started = desc.Enqueued = System.DateTime.Now; m_Queue.Add(desc); m_QueueNotEmpty.Set(); } return(true); }
private void btnFromDB_Click(object sender, EventArgs e) { if (ValidateLong(txtBrick, ref m_Brick, 0, 100000000) == false) { MessageBox.Show("A valid brick number is required.", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } SySal.OperaDb.OperaDbConnection conn = null; try { conn = SySal.OperaDb.OperaDbCredentials.CreateFromRecord().Connect(); conn.Open(); SySal.OperaDb.Schema.DB = conn; SySal.OperaDb.Schema.TB_PLATES plates = SySal.OperaDb.Schema.TB_PLATES.SelectWhere("ID_EVENTBRICK = " + m_Brick, "Z ASC"); Geometry.LayerStart[] ls = new Geometry.LayerStart[plates.Count * 2]; int i; for (i = 0; i < plates.Count; i++) { plates.Row = i; ls[i * 2].Brick = m_Brick; ls[i * 2].Plate = (int)plates._ID; ls[i * 2].ZMin = plates._Z - 255.0; ls[i * 2].RadiationLength = 29000.0; ls[i * 2 + 1].Brick = m_Brick; ls[i * 2 + 1].Plate = 0; ls[i * 2 + 1].ZMin = plates._Z + 45.0; ls[i * 2 + 1].RadiationLength = 5600.0; } ls[i * 2 - 1].RadiationLength = 1e9; C.Geometry.Layers = ls; SetGeometryList(); } catch (Exception x) { MessageBox.Show(x.Message, "DB Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (conn != null) { conn.Close(); conn = null; } try { SySal.OperaDb.Schema.DB = null; } catch (Exception) { } } }
private void OnLoad(object sender, System.EventArgs e) { SySal.OperaDb.OperaDbCredentials cred = SySal.OperaDb.OperaDbCredentials.CreateFromRecord(); System.Runtime.Remoting.Channels.ChannelServices.RegisterChannel(new TcpChannel(), false); Conn = new SySal.OperaDb.OperaDbConnection(cred.DBServer, cred.DBUserName, cred.DBPassword); Conn.Open(); System.Data.DataSet ds = new System.Data.DataSet(); new SySal.OperaDb.OperaDbDataAdapter("select name from tb_machines where id_site = (select to_number(value) from opera.lz_sitevars where name = 'ID_SITE') and isbatchserver = 1", Conn, null).Fill(ds); foreach (System.Data.DataRow dr in ds.Tables[0].Rows) { comboBatchManager.Items.Add(dr[0].ToString()); } new SySal.OperaDb.OperaDbCommand("alter session set nls_comp='LINGUISTIC'", Conn).ExecuteNonQuery(); new SySal.OperaDb.OperaDbCommand("alter session set NLS_SORT='BINARY_CI'", Conn).ExecuteNonQuery(); }
object ReadOverride(string name, SySal.OperaDb.OperaDbConnection conn) { object o = new SySal.OperaDb.OperaDbCommand("SELECT VALUE FROM OPERA.LZ_MACHINEVARS WHERE ID_MACHINE = " + IdMachine + " AND NAME = '" + name + "'", conn, null).ExecuteScalar(); if (o != null && o != System.DBNull.Value) { return(o); } o = new SySal.OperaDb.OperaDbCommand("SELECT VALUE FROM OPERA.LZ_SITEVARS WHERE NAME = '" + name + "'", conn, null).ExecuteScalar(); if (o == null) { o = System.DBNull.Value; } return(o); }
private void OnFavoriteChanged(object sender, EventArgs e) { SySal.OperaDb.OperaDbConnection conn = null; try { conn = SySal.OperaDb.OperaDbCredentials.CreateFromRecord().Connect(); conn.Open(); RefreshProgramSettings(conn); } catch (Exception) { } finally { if (conn != null) { conn.Close(); } } }
public frmScheduleCSScanDriver() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // btnSchedule.Enabled = false; Conn = SySal.OperaDb.OperaDbCredentials.CreateFromRecord().Connect(); Conn.Open(); BatchManager = txtBatchManager.Text = Convert.ToString(new SySal.OperaDb.OperaDbCommand("select address from tb_machines where ISBATCHSERVER=1 and id_site = (SELECT value FROM lz_sitevars where name='ID_SITE')", Conn).ExecuteScalar()); cmbConfig.Enabled = false; Utilities.FillComboBox(cmbMachine, @"SELECT ID, NAME FROM TB_MACHINES WHERE ISSCANNINGSERVER=1 and id_site = (SELECT value FROM lz_sitevars where name='ID_SITE' ) ORDER BY NAME", Conn); Utilities.FillComboBox(cmbBrick, @"SELECT UNIQUE TO_CHAR(ID_CS_EVENTBRICK), ID_CS_EVENTBRICK FROM vw_local_predictions ORDER BY ID_cs_EVENTBRICK", Conn); btnSchedule.Enabled = IsFormFilled(); }
static void Main(string[] args) { // // TODO: Add code to start application here // if (args.Length != 3 && args.Length != 4) { Console.WriteLine("usage: GetDBMarks <brick id> <plate id> <type-or-id> <mark set>"); Console.WriteLine("<type> can be either nominal or calibrated; as an alternative, the explicit Id of the calibration requested can be given."); Console.WriteLine("<mark set> can be " + SySal.DAQSystem.Drivers.MarkChar.SpotOptical + " (Spot Optical), " + SySal.DAQSystem.Drivers.MarkChar.LineXRay + " (X-ray lateral), " + SySal.DAQSystem.Drivers.MarkChar.SpotXRay + " (X-ray for CS-brick connection). This parameter is needed when the id is not directly specified."); return; } long id = 0; char mt = SySal.DAQSystem.Drivers.MarkChar.None; bool calibrated = String.Compare(args[2], "calibrated", true) == 0; if (!calibrated && String.Compare(args[2], "nominal", true) != 0) { id = Convert.ToInt64(args[2]); } else { mt = Convert.ToChar(args[3]); } SySal.OperaDb.OperaDbCredentials cred = SySal.OperaDb.OperaDbCredentials.CreateFromRecord(); SySal.OperaDb.OperaDbConnection conn = new SySal.OperaDb.OperaDbConnection(cred.DBServer, cred.DBUserName, cred.DBPassword); conn.Open(); if (id == 0) { long calibrationid; Console.WriteLine(SySal.OperaDb.Scanning.Utilities.GetMapString(Convert.ToInt64(args[0]), Convert.ToInt64(args[1]), calibrated, SySal.OperaDb.Scanning.Utilities.CharToMarkType(mt), out calibrationid, conn, null)); } else { Console.WriteLine(SySal.OperaDb.Scanning.Utilities.GetMapString(Convert.ToInt64(args[0]), Convert.ToInt64(args[1]), id, conn, null)); } conn.Close(); }
public frmReuseSettings(SySal.OperaDb.OperaDbConnection conn, long[] ids) { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // _conn = conn; System.Data.DataSet ds = new System.Data.DataSet(); SySal.OperaDb.OperaDbDataAdapter da = new SySal.OperaDb.OperaDbDataAdapter("SELECT DESCRIPTION FROM TB_PROGRAMSETTINGS WHERE EXECUTABLE='AreaScan2Driver.exe'", _conn); da.Fill(ds); //dataGrid1.SetDataBinding(ds, "Table"); string qry = "SELECT ID, DESCRIPTION FROM TB_PROGRAMSETTINGS WHERE EXECUTABLE = 'AreaScan2Driver.exe'"; if (chkDisplayAll.Checked == true) { qry = "SELECT ID, DESCRIPTION FROM TB_PROGRAMSETTINGS WHERE DRIVERLEVEL=1"; } Utilities.FillListBox(lstAvailable, qry, _conn); }
private void OnLoad(object sender, System.EventArgs e) { DBConn = new SySal.OperaDb.OperaDbConnection(MainForm.DBServer, MainForm.DBUserName, MainForm.DBPassword); DBConn.Open(); System.Data.DataSet ds; ds = new System.Data.DataSet(); ProgramList.Items.Clear(); new SySal.OperaDb.OperaDbDataAdapter("SELECT ID, EXECUTABLE, " + ((progsetwhere.Length == 0) ? "DESCRIPTION" : "trim(substr(name, instr(name, 'PROGSET') + 7)) as DESCRIPTION") + ", DRIVERLEVEL FROM TB_PROGRAMSETTINGS " + progsetwhere + " ORDER BY ID ASC", DBConn, null).Fill(ds); foreach (System.Data.DataRow dr in ds.Tables[0].Rows) { ListViewItem lvi = ProgramList.Items.Add(dr[0].ToString()); lvi.SubItems.Add(dr[1].ToString()); lvi.SubItems.Add(dr[2].ToString()); lvi.SubItems.Add(dr[3].ToString()); } BrickList.Items.Clear(); ds = new System.Data.DataSet(); new SySal.OperaDb.OperaDbDataAdapter("SELECT ID, ID_SET, ID_BRICK FROM TB_EVENTBRICKS ORDER BY ID ASC", DBConn, null).Fill(ds); foreach (System.Data.DataRow dr in ds.Tables[0].Rows) { ListViewItem lvi = BrickList.Items.Add(dr[0].ToString()); lvi.SubItems.Add(dr[1].ToString()); lvi.SubItems.Add(dr[2].ToString()); } MachineList.Items.Clear(); ds = new System.Data.DataSet(); new SySal.OperaDb.OperaDbDataAdapter("SELECT ID, NAME, ADDRESS FROM TB_MACHINES WHERE ID_SITE IN (SELECT VALUE FROM OPERA.LZ_SITEVARS WHERE NAME = 'ID_SITE') ORDER BY ID ASC", DBConn, null).Fill(ds); foreach (System.Data.DataRow dr in ds.Tables[0].Rows) { ListViewItem lvi = MachineList.Items.Add(dr[0].ToString()); lvi.SubItems.Add(dr[1].ToString()); lvi.SubItems.Add(dr[2].ToString()); } NotesText.Text = ""; }
void RefreshProgramSettings(SySal.OperaDb.OperaDbConnection conn) { SySal.OperaDb.OperaDbDataReader rd2 = null; try { lvProgramSettings.Items.Clear(); string sql = ""; if (chkFavorites.Checked) { sql = "select to_number(value), substr(name, length('PROGSET') + 2) as description from opera.lz_sitevars where name like 'PROGSET %' and exists (select * from tb_programsettings where id = to_number(value) and driverlevel = 2 and instr(upper(executable), 'TOTALSCAN') > 0) order by value"; } else { sql = "select id, description from tb_programsettings where driverlevel = 2 and instr(upper(executable), 'TOTALSCAN') > 0 order by id"; } rd2 = new SySal.OperaDb.OperaDbCommand(sql, conn).ExecuteReader(); while (rd2.Read()) { ListViewItem lvi = new ListViewItem(rd2.GetInt64(0).ToString()); lvi.Tag = rd2.GetInt64(0); lvi.SubItems.Add(rd2.GetString(1)); lvProgramSettings.Items.Add(lvi); } } catch (Exception x) { MessageBox.Show(x.ToString(), "Error Accessing DB", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (rd2 != null) { rd2.Close(); } } }
//private Intercalibration3Settings _progSettings; public static long GetConfig(long settingsId, SySal.OperaDb.OperaDbConnection conn) { new frmConfig(settingsId, conn).ShowDialog(); return(_settingsId); }
static void Main(string[] args) { // // TODO: Add code to start application here // if (args.Length != 3) { System.Xml.Serialization.XmlSerializer xmls = null; Console.WriteLine("BatchReconstruct - performs volume reconstruction using LinkedZones from TLG files or OPERA DB tables."); Console.WriteLine("usage: batchreconstruct <XML list file> <output Opera persistence path> <XML config Opera persistence path>"); Console.WriteLine("or: batchreconstruct <DB volume> <output Opera persistence path> <XML config Opera persistence path>"); Console.WriteLine("or: batchreconstruct <input OPERA persistence path> <output Opera persistence path> <XML config Opera persistence path>"); Console.WriteLine("Full volumes are reprocessed for topological reconstruction only."); Console.WriteLine("---------------- DB volume example: db:\\8\\17723900.vol"); Console.WriteLine("First number is ID_EVENTBRICK, second is ID_VOLUME"); Console.WriteLine("---------------- XML list file example (source = filesystem):"); Input inputlist = new Input(); inputlist.Zones = new Zone[3]; inputlist.Zones[0] = new Zone(); inputlist.Zones[0].SheetId = 8; inputlist.Zones[0].Source = @"\\myserver.mydomain\myshare\plate_08.tlg"; inputlist.Zones[0].Z = 0.0; inputlist.Zones[0].AlignmentIgnoreListPath = @"\\myserver\mydomain\myshare\alignignore_plate_08.txt"; inputlist.Zones[1] = new Zone(); inputlist.Zones[1].SheetId = 9; inputlist.Zones[1].Source = @"\\myserver.mydomain\myshare\plate_09.tlg"; inputlist.Zones[1].Z = -1300.0; inputlist.Zones[2] = new Zone(); inputlist.Zones[2].SheetId = 10; inputlist.Zones[2].Source = @"\\myserver.mydomain\myshare\plate_10.tlg"; inputlist.Zones[2].Z = -2600.0; xmls = new System.Xml.Serialization.XmlSerializer(typeof(BatchReconstruct.Input)); xmls.Serialize(Console.Out, inputlist); Console.WriteLine(); Console.WriteLine("---------------- XML list file example (source = OperaDB):"); inputlist.Zones[0].Source = @"db:\1002323.tlg"; inputlist.Zones[1].Source = @"db:\1006326.tlg"; inputlist.Zones[2].Source = @"db:\1009724.tlg"; xmls.Serialize(Console.Out, inputlist); Console.WriteLine(); Console.WriteLine("---------------- XML config file syntax:"); Console.WriteLine("XML configuration syntax:"); BatchReconstruct.Config C = new BatchReconstruct.Config(); C.ReconstructorConfig = (Configuration) new AlphaOmegaReconstructor().Config; xmls = new System.Xml.Serialization.XmlSerializer(typeof(BatchReconstruct.Config)); xmls.Serialize(Console.Out, C); Console.WriteLine(); return; } #if !(DEBUG) try #endif { AlphaOmegaReconstructor R = new AlphaOmegaReconstructor(); System.Xml.Serialization.XmlSerializer xmls = null; xmls = new System.Xml.Serialization.XmlSerializer(typeof(BatchReconstruct.Config)); Config config = (Config)xmls.Deserialize(new System.IO.StringReader(((SySal.OperaDb.ComputingInfrastructure.ProgramSettings)SySal.OperaPersistence.Restore(args[2], typeof(SySal.OperaDb.ComputingInfrastructure.ProgramSettings))).Settings)); R.Config = (SySal.Management.Configuration)config.ReconstructorConfig; R.Progress = new SySal.TotalScan.dProgress(Progress); R.Report = new SySal.TotalScan.dReport(Report); System.Text.RegularExpressions.Regex volrgx = new System.Text.RegularExpressions.Regex(@"db:\\(\d+)\\(\d+)\.vol"); System.Text.RegularExpressions.Match mrgx = volrgx.Match(args[0].ToLower()); Input inputlist = null; SySal.TotalScan.Volume OldVol = null; if (args[0].ToLower().EndsWith(".tsr")) { OldVol = (SySal.TotalScan.Volume)SySal.OperaPersistence.Restore(args[0], typeof(SySal.TotalScan.Volume)); } else { if (mrgx.Success && mrgx.Length == args[0].Length) { SySal.OperaDb.OperaDbCredentials cred = SySal.OperaDb.OperaDbCredentials.CreateFromRecord(); SySal.OperaDb.OperaDbConnection conn = new SySal.OperaDb.OperaDbConnection(cred.DBServer, cred.DBUserName, cred.DBPassword); conn.Open(); System.Data.DataSet ds = new System.Data.DataSet(); new SySal.OperaDb.OperaDbDataAdapter("SELECT TB_VOLUME_SLICES.ID_PLATE, TB_VOLUME_SLICES.ID_ZONE, VW_PLATES.Z FROM TB_VOLUME_SLICES INNER JOIN VW_PLATES ON (TB_VOLUME_SLICES.ID_EVENTBRICK = VW_PLATES.ID_EVENTBRICK AND TB_VOLUME_SLICES.ID_PLATE = VW_PLATES.ID) WHERE TB_VOLUME_SLICES.DAMAGED = 'N' AND TB_VOLUME_SLICES.ID_EVENTBRICK = " + mrgx.Groups[1].Value + " AND TB_VOLUME_SLICES.ID_VOLUME = " + mrgx.Groups[2].Value + " ORDER BY VW_PLATES.Z DESC", conn, null).Fill(ds); inputlist = new Input(); inputlist.Zones = new Zone[ds.Tables[0].Rows.Count]; int sli; for (sli = 0; sli < ds.Tables[0].Rows.Count; sli++) { inputlist.Zones[sli] = new Zone(); inputlist.Zones[sli].SheetId = Convert.ToInt32(ds.Tables[0].Rows[sli][0]); inputlist.Zones[sli].Source = "db:\\" + mrgx.Groups[1] + "\\" + ds.Tables[0].Rows[sli][1].ToString() + ".tlg"; inputlist.Zones[sli].Z = Convert.ToDouble(ds.Tables[0].Rows[sli][2]); } SySal.OperaPersistence.Connection = conn; SySal.OperaPersistence.LinkedZoneDetailLevel = SySal.OperaDb.Scanning.LinkedZone.DetailLevel.BaseFull; } else { System.IO.StreamReader r = new System.IO.StreamReader(args[0]); xmls = new System.Xml.Serialization.XmlSerializer(typeof(BatchReconstruct.Input)); inputlist = (Input)xmls.Deserialize(r); r.Close(); } int i, j, c; for (i = 0; i < inputlist.Zones.Length; i++) { for (j = i + 1; j < inputlist.Zones.Length; j++) { if (inputlist.Zones[i].SheetId == inputlist.Zones[j].SheetId) { Console.WriteLine("Duplicate SheetId found. Sheets will be renumbered with the default sequence."); for (j = 0; j < inputlist.Zones.Length; j++) { inputlist.Zones[j].SheetId = j; } i = inputlist.Zones.Length; break; } } } for (i = 0; i < inputlist.Zones.Length; i++) { SySal.Scanning.Plate.IO.OPERA.LinkedZone lz = (SySal.Scanning.Plate.IO.OPERA.LinkedZone)SySal.OperaPersistence.Restore(inputlist.Zones[i].Source, typeof(SySal.Scanning.Plate.IO.OPERA.LinkedZone)); c = lz.Length; SySal.TotalScan.Segment[] segs = new SySal.TotalScan.Segment[c]; double[] zcor = new double[c]; for (j = 0; j < c; j++) { zcor[j] = lz[j].Info.Intercept.Z; } double zmean = NumericalTools.Fitting.Average(zcor); double dgap; for (j = 0; j < c; j++) { SySal.Tracking.MIPEmulsionTrackInfo info = lz[j].Info; segs[j] = new SySal.TotalScan.Segment(info, new SySal.TotalScan.BaseTrackIndex(j)); dgap = zmean - info.Intercept.Z; info.Intercept.Z = zmean; info.Intercept.X += info.Slope.X * dgap; info.Intercept.Y += info.Slope.Y * dgap; info.TopZ += dgap; info.BottomZ += dgap; info.Intercept.Z = inputlist.Zones[i].Z; double tmptopz = info.TopZ; double tmpbotz = info.BottomZ; dgap = zmean - tmptopz; info.TopZ = inputlist.Zones[i].Z - dgap; info.BottomZ = inputlist.Zones[i].Z - (tmptopz - tmpbotz) - dgap; } SySal.BasicTypes.Vector refc = new SySal.BasicTypes.Vector(); refc.Z = inputlist.Zones[i].Z; SySal.TotalScan.Layer tmpLayer = new SySal.TotalScan.Layer(i, /*System.Convert.ToInt64(mrgx.Groups[1].Value)*/ 0, (int)inputlist.Zones[i].SheetId, 0, refc); tmpLayer.AddSegments(segs); R.AddLayer(tmpLayer); if (inputlist.Zones[i].AlignmentIgnoreListPath != null && inputlist.Zones[i].AlignmentIgnoreListPath.Trim().Length != 0) { if (inputlist.Zones[i].AlignmentIgnoreListPath.ToLower().EndsWith(".tlg")) { R.SetAlignmentIgnoreList(i, ((SySal.Scanning.Plate.IO.OPERA.LinkedZone.BaseTrackIgnoreAlignment)SySal.OperaPersistence.Restore(inputlist.Zones[i].AlignmentIgnoreListPath, typeof(SySal.Scanning.Plate.IO.OPERA.LinkedZone.BaseTrackIgnoreAlignment))).Ids); } else { System.IO.StreamReader r = new System.IO.StreamReader(inputlist.Zones[i].AlignmentIgnoreListPath.Trim()); System.Collections.ArrayList tmpignorelist = new System.Collections.ArrayList(); string line; while ((line = r.ReadLine()) != null) { try { tmpignorelist.Add(System.Convert.ToInt32(line)); } catch (Exception) { } } ; r.Close(); R.SetAlignmentIgnoreList(i, (int[])tmpignorelist.ToArray(typeof(int))); } } Console.WriteLine("Loaded sheet {0} Id {1} Tracks {2}", i, inputlist.Zones[i].SheetId, c); lz = null; } } SySal.TotalScan.Volume V = (OldVol == null) ? R.Reconstruct() : R.RecomputeVertices(OldVol); Console.WriteLine("Result written to: " + SySal.OperaPersistence.Persist(args[1], V)); } #if !(DEBUG) catch (Exception x) { Console.Error.WriteLine(x.ToString()); } #endif }
private static void Execute() { try { //System.Windows.Forms.MessageBox.Show("Eccomi"); ThisThread = System.Threading.Thread.CurrentThread; StartupInfo = (SySal.DAQSystem.Drivers.VolumeOperationInfo)HE.StartupInfo; Conn = new SySal.OperaDb.OperaDbConnection(StartupInfo.DBServers, StartupInfo.DBUserName, StartupInfo.DBPassword); Conn.Open(); (DBKeepAliveThread = new System.Threading.Thread(DBKeepAliveThreadExec)).Start(); System.Xml.Serialization.XmlSerializer xmls = new System.Xml.Serialization.XmlSerializer(typeof(CSScanDriverSettings)); ProgSettings = (CSScanDriverSettings)xmls.Deserialize(new System.IO.StringReader(HE.ProgramSettings)); xmls = null; if (StartupInfo.ExeRepository.EndsWith("\\")) { StartupInfo.ExeRepository = StartupInfo.ExeRepository.Remove(StartupInfo.ExeRepository.Length - 1, 1); } if (StartupInfo.ScratchDir.EndsWith("\\")) { StartupInfo.ScratchDir = StartupInfo.ScratchDir.Remove(StartupInfo.ScratchDir.Length - 1, 1); } if (StartupInfo.LinkedZonePath.EndsWith("\\")) { StartupInfo.LinkedZonePath = StartupInfo.LinkedZonePath.Remove(StartupInfo.LinkedZonePath.Length - 1, 1); } if (StartupInfo.RawDataPath.EndsWith("\\")) { StartupInfo.RawDataPath = StartupInfo.RawDataPath.Remove(StartupInfo.RawDataPath.Length - 1, 1); } //create a directory where to put all acquisition files if (StartupInfo.RawDataPath.IndexOf(System.Convert.ToString(StartupInfo.ProcessOperationId)) < 0) { StartupInfo.RawDataPath = StartupInfo.RawDataPath + "\\cssd_" + StartupInfo.BrickId + "_" + StartupInfo.ProcessOperationId; if (!System.IO.Directory.Exists(StartupInfo.RawDataPath)) { System.IO.Directory.CreateDirectory(StartupInfo.RawDataPath); } } ProgressInfo = HE.ProgressInfo; if (StartupInfo.RecoverFromProgressFile) { try { XmlDocument xmldoc = new XmlDocument(); xmldoc.LoadXml(ProgressInfo.CustomInfo.Replace('[', '<').Replace(']', '>')); System.Xml.XmlNode xmlprog = xmldoc.FirstChild; WaitingOnId = Convert.ToInt64(xmlprog["WaitingOnId"].InnerText); CS1WideAreaScanDone = Convert.ToBoolean(xmlprog["CS1WideAreaScanDone"].InnerText); CS2WideAreaScanDone = Convert.ToBoolean(xmlprog["CS2WideAreaScanDone"].InnerText); CS1WideAreaScanProcOperationId = Convert.ToInt64(xmlprog["CS1WideAreaScanProcOperationId"].InnerText); CS2WideAreaScanProcOperationId = Convert.ToInt64(xmlprog["CS2WideAreaScanProcOperationId"].InnerText); CSMappingDone = Convert.ToBoolean(xmlprog["CSMappingDone"].InnerText); CSCandidatesDone = Convert.ToBoolean(xmlprog["CSCandidatesDone"].InnerText); ComputeScanArea = Convert.ToBoolean(xmlprog["ComputeScanArea"].InnerText); MinX = Convert.ToDouble(xmlprog["MinX"].InnerText, System.Globalization.CultureInfo.InvariantCulture); MaxX = Convert.ToDouble(xmlprog["MaxX"].InnerText, System.Globalization.CultureInfo.InvariantCulture); MinY = Convert.ToDouble(xmlprog["MinY"].InnerText, System.Globalization.CultureInfo.InvariantCulture); MaxY = Convert.ToDouble(xmlprog["MaxY"].InnerText, System.Globalization.CultureInfo.InvariantCulture); ProgressInfo.ExitException = null; HE.WriteLine("Restarting complete"); } catch (Exception ex) { HE.WriteLine("Restarting failed - proceeding to re-initialize process."); ProgressInfo = HE.ProgressInfo; ProgressInfo.Progress = 0.0; ProgressInfo.StartTime = System.DateTime.Now; ProgressInfo.FinishTime = ProgressInfo.StartTime.AddYears(1); HE.WriteLine(ex.Message); } } else { CS1WideAreaScanDone = false; CS2WideAreaScanDone = false; CS1WideAreaScanProcOperationId = 0; CS2WideAreaScanProcOperationId = 0; CSMappingDone = false; CSCandidatesDone = false; ComputeScanArea = true; ProgressInfo = new TaskProgressInfo(); ProgressInfo.Complete = false; ProgressInfo.ExitException = null; ProgressInfo.Progress = 0.0; ProgressInfo.StartTime = System.DateTime.Now; ProgressInfo.FinishTime = ProgressInfo.StartTime.AddYears(1); } UpdateProgress(); HE.InterruptNotifier = new Exe(); if (ProgSettings.WaitForScanningArea) { while (ComputeScanArea == true) { System.Threading.Thread.Sleep(1000); } } UpdateProgress(); for (int i = 0; i < 2; i++) { bool WideAreaScanDone = (i == 0) ? CS1WideAreaScanDone : CS2WideAreaScanDone; while (WideAreaScanDone == false) { if (WaitingOnId == 0) { SySal.DAQSystem.Drivers.ScanningStartupInfo wasdstartupinfo = new SySal.DAQSystem.Drivers.ScanningStartupInfo(); wasdstartupinfo.DBPassword = StartupInfo.DBPassword; wasdstartupinfo.DBServers = StartupInfo.DBServers; wasdstartupinfo.DBUserName = StartupInfo.DBUserName; wasdstartupinfo.ExeRepository = StartupInfo.ExeRepository; wasdstartupinfo.LinkedZonePath = StartupInfo.LinkedZonePath; wasdstartupinfo.MachineId = StartupInfo.MachineId; wasdstartupinfo.Plate = new SySal.DAQSystem.Scanning.MountPlateDesc(); wasdstartupinfo.Plate.BrickId = StartupInfo.BrickId; wasdstartupinfo.Plate.PlateId = i + 1; long calibrationId; wasdstartupinfo.MarkSet = MarkType.SpotXRay; wasdstartupinfo.Plate.MapInitString = SySal.OperaDb.Scanning.Utilities.GetMapString(wasdstartupinfo.Plate.BrickId, wasdstartupinfo.Plate.PlateId, false, MarkType.SpotXRay, out calibrationId, Conn, null); wasdstartupinfo.Plate.TextDesc = "Brick #" + wasdstartupinfo.Plate.BrickId + " Plate #" + wasdstartupinfo.Plate.PlateId; wasdstartupinfo.ProcessOperationId = 0; wasdstartupinfo.ProgramSettingsId = ProgSettings.WideAreaConfigId; wasdstartupinfo.ProgressFile = ""; wasdstartupinfo.RawDataPath = StartupInfo.RawDataPath; wasdstartupinfo.RecoverFromProgressFile = false; wasdstartupinfo.ScratchDir = StartupInfo.ScratchDir; if (ComputeScanArea == true) { wasdstartupinfo.Zones = CalculateZones(wasdstartupinfo.Plate.BrickId, wasdstartupinfo.Plate.PlateId); } else { wasdstartupinfo.Zones = new SySal.DAQSystem.Scanning.ZoneDesc[1]; wasdstartupinfo.Zones[0] = new SySal.DAQSystem.Scanning.ZoneDesc(); wasdstartupinfo.Zones[0].MinX = MinX; wasdstartupinfo.Zones[0].MaxX = MaxX; wasdstartupinfo.Zones[0].MinY = MinY; wasdstartupinfo.Zones[0].MaxY = MaxY; } WaitingOnId = HE.Start(wasdstartupinfo); UpdateProgress(); HE.WriteLine("Starting wasd " + WaitingOnId); } SySal.DAQSystem.Drivers.Status status; if (WaitingOnId != 0) { status = HE.Wait(WaitingOnId); if (status == SySal.DAQSystem.Drivers.Status.Failed) { WaitingOnId = 0; throw new Exception("Scan of the changeable sheet " + (i + 1) + " failed!\n"); } HE.WriteLine("Waiting wasd " + WaitingOnId); } if (WaitingOnId != 0) { status = HE.GetStatus(WaitingOnId); if (status == SySal.DAQSystem.Drivers.Status.Completed) { if (i == 0) { CS1WideAreaScanDone = true; CS1WideAreaScanProcOperationId = WaitingOnId; } else { CS2WideAreaScanDone = true; CS2WideAreaScanProcOperationId = WaitingOnId; } ProgressInfo.Progress = 0.45 * (i + 1); WaitingOnId = 0; break; } HE.WriteLine("Checking status wasd " + WaitingOnId); } UpdateProgress(); } } if (CSMappingDone == false) { HE.WriteLine("Start mapping"); DataProcSrv = HE.DataProcSrv; SySal.DAQSystem.DataProcessingBatchDesc dbd = new SySal.DAQSystem.DataProcessingBatchDesc(); dbd.AliasUsername = StartupInfo.DBUserName; dbd.AliasPassword = StartupInfo.DBPassword; dbd.Description = "Plate doublet mapping B#" + StartupInfo.BrickId; dbd.Id = DataProcSrv.SuggestId; dbd.Token = HE.Token; dbd.MachinePowerClass = 5; dbd.Filename = StartupInfo.ExeRepository + @"\CSMap.exe"; // dbd.CommandLineArguments = StartupInfo.ProcessOperationId + " db:\\" + ProgSettings.CSMapConfigId + ".xml CSMap_" + StartupInfo.BrickId + "_" + StartupInfo.ProcessOperationId + " false " + StartupInfo.ProcessOperationId; dbd.CommandLineArguments = "db:\\" + CS1WideAreaScanProcOperationId + ".tlg " + "db:\\" + CS2WideAreaScanProcOperationId + ".tlg " + "db:\\" + StartupInfo.BrickId + " " + "db:\\" + ProgSettings.CSMapConfigId + ".xml " + StartupInfo.RawDataPath + @"\CSSD " + StartupInfo.ProcessOperationId; if (!DataProcSrv.Enqueue(dbd)) { throw new Exception("Cannot schedule CSd mapping batch " + dbd.Id + " for brick " + StartupInfo.BrickId + ". Aborting."); } while (DataProcSrv.DoneWith(dbd.Id) == false) { System.Threading.Thread.Sleep(100); } dbd = DataProcSrv.Result(dbd.Id); if (System.IO.File.Exists(StartupInfo.RawDataPath + @"\CHECK") == true) { CSMappingDone = true; } else { throw new Exception("Plate Mapping failure"); } } //DUMP MARK FILE System.IO.StreamWriter markFile = null; try { long CalibrationId; string markString = SySal.OperaDb.Scanning.Utilities.GetMapString(StartupInfo.BrickId, 1, false, MarkType.SpotXRay, out CalibrationId, Conn, null); markFile = new System.IO.StreamWriter(StartupInfo.RawDataPath + @"\marks.txt"); markFile.WriteLine(markString); markFile.Flush(); } catch { } finally { if (markFile != null) { markFile.Close(); } } WaitingOnId = 0; ProgressInfo.Progress = 1.0; ProgressInfo.Complete = true; UpdateProgress(); } catch (Exception ex) { if (ProgressInfo == null) { ProgressInfo = new SySal.DAQSystem.Drivers.TaskProgressInfo(); } HE.WriteLine(ex.Message); ProgressInfo.Complete = false; ProgressInfo.ExitException = ex.ToString(); UpdateProgress(); } }
/// <summary> /// Set things in motion. /// </summary> protected override void OnStart(string[] args) { try { int i; if (!EventLog.Exists("Opera")) { EventLog.CreateEventSource("OperaDataProcServer", "Opera"); } EventLog.Source = "OperaDataProcServer"; EventLog.Log = "Opera"; System.Configuration.AppSettingsReader asr = new System.Configuration.AppSettingsReader(); try { DBServer = SySal.OperaDb.OperaDbCredentials.Decode((string)asr.GetValue("DBServer", typeof(string))); DBUserName = SySal.OperaDb.OperaDbCredentials.Decode((string)asr.GetValue("DBUserName", typeof(string))); DBPassword = SySal.OperaDb.OperaDbCredentials.Decode((string)asr.GetValue("DBPassword", typeof(string))); } catch (Exception x) { throw new Exception("Encryption error in credentials.\r\nPlease fill in valid encrypted data (you can use OperaDbGUILogin, for instance), or run the service as the appropriate user."); } SySal.OperaDb.OperaDbConnection conn = new SySal.OperaDb.OperaDbConnection(DBServer, DBUserName, DBPassword); conn.Open(); IPHostEntry iph = Dns.Resolve(Dns.GetHostName()); string [] idstr = new string[iph.Aliases.Length + iph.AddressList.Length]; idstr[0] = iph.HostName; for (i = 0; i < iph.Aliases.Length; i++) { idstr[i] = iph.Aliases[i]; } for (i = 0; i < iph.AddressList.Length; i++) { idstr[i + iph.Aliases.Length] = iph.AddressList[i].ToString(); } string selstr = "LOWER(TB_MACHINES.ADDRESS)='" + iph.HostName.ToLower() + "'"; foreach (string s in idstr) { selstr += (" OR ADDRESS='" + s + "'"); } DataSet ds = new DataSet(); SySal.OperaDb.OperaDbDataAdapter da = new SySal.OperaDb.OperaDbDataAdapter("SELECT TB_SITES.ID, TB_SITES.NAME, TB_MACHINES.ID, TB_MACHINES.NAME, TB_MACHINES.ADDRESS FROM TB_SITES INNER JOIN TB_MACHINES ON (TB_MACHINES.ID_SITE = TB_SITES.ID AND TB_MACHINES.ISDATAPROCESSINGSERVER = 1 AND (" + selstr + "))", conn, null); da.Fill(ds); if (ds.Tables[0].Rows.Count < 1) { throw new Exception("Can't find myself in OperaDb registered machines. This service is made unavailable."); } IdSite = SySal.OperaDb.Convert.ToInt64(ds.Tables[0].Rows[0][0]); SiteName = ds.Tables[0].Rows[0][1].ToString(); IdMachine = SySal.OperaDb.Convert.ToInt64(ds.Tables[0].Rows[0][2]); MachineName = ds.Tables[0].Rows[0][3].ToString(); MachineAddress = ds.Tables[0].Rows[0][4].ToString(); object val; val = ReadOverride("DPS_MachinePowerClass", conn); if (val != System.DBNull.Value) { MachinePowerClass = Convert.ToInt32(val.ToString()); } else { MachinePowerClass = (int)asr.GetValue("MachinePowerClass", typeof(int)); } val = ReadOverride("DPS_PeakWorkingSetMB", conn); if (val != System.DBNull.Value) { PeakWorkingSetMB = Convert.ToInt32(val.ToString()); } else { PeakWorkingSetMB = (int)asr.GetValue("PeakWorkingSetMB", typeof(int)); } val = ReadOverride("DPS_ResultLiveSeconds", conn); if (val != System.DBNull.Value) { ResultLiveTime = System.TimeSpan.FromSeconds(Convert.ToInt32(val.ToString())); } else { ResultLiveTime = System.TimeSpan.FromSeconds((int)asr.GetValue("ResultLiveSeconds", typeof(int))); } val = ReadOverride("DPS_LowPriority", conn); if (val != System.DBNull.Value) { LowPriority = Convert.ToBoolean(val.ToString()); } else { LowPriority = (bool)asr.GetValue("LowPriority", typeof(bool)); } val = ReadOverride("ExeRepository", conn); if (val != System.DBNull.Value) { ExeRepository = val.ToString(); } else { ExeRepository = asr.GetValue("MachinePowerClass", typeof(string)).ToString(); } val = ReadOverride("DPS_WWWPort", conn); if (val != System.DBNull.Value) { WebPort = Convert.ToInt32(val.ToString()); } else { WebPort = (int)asr.GetValue("WWWPort", typeof(int)); } bool showexc = false; val = ReadOverride("DPS_WWWShowExceptions", conn); if (val != System.DBNull.Value) { showexc = Convert.ToBoolean(val.ToString()); } else { showexc = (bool)asr.GetValue("WWWShowExceptions", typeof(bool)); } val = ReadOverride("DPS_MaxOutputText", conn); if (val != System.DBNull.Value) { MaxOutputText = Convert.ToInt32(val.ToString()); } else { try { MaxOutputText = (int)asr.GetValue("MaxOutputText", typeof(int)); } catch (Exception) { MaxOutputText = 65536; } } ChannelServices.RegisterChannel(new TcpChannel((int)SySal.DAQSystem.OperaPort.DataProcessingServer)); DPS = new SySal.DAQSystem.MyDataProcessingServer(EventLog); RemotingServices.Marshal(DPS, "DataProcessingServer.rem"); conn.Close(); WebAccess wa = null; if (WebPort > 0) { WA = new SySal.Web.WebServer(WebPort, wa = new WebAccess()); } if (wa != null) { wa.SetShowExceptions(showexc); } EventLog.WriteEntry("Service starting\r\nThread Priority: " + (LowPriority ? "Below normal" : "Normal") + "\r\nPeak working set (MB): " + PeakWorkingSetMB + "\r\nMachine power class: " + MachinePowerClass + "\r\nSelf-identification yields:\r\nSite: " + SiteName + "\r\nSite Id: " + IdSite + "\r\nMachine: " + MachineName + "\r\nMachine Id: " + IdMachine + "\r\nMachine Address: " + MachineAddress, EventLogEntryType.Information); } catch (System.Exception x) { EventLog.WriteEntry("Service startup failure:\n" + x.ToString(), EventLogEntryType.Error); throw x; } }
/// <summary> /// Draws a batch out ouf the queue or aborts it if it is already being executed. /// A non-null token or a username/password pair must be supplied that matches the one with which the batch was started. /// If the token is supplied, the username/password pair is ignored. /// </summary> /// <param name="id">identifier of the batch to be removed.</param> /// <param name="token">the process token to be used.</param> /// <param name="user">username of the user that started the batch. Ignored if <c>token</c> is non-null.</param> /// <param name="password">password of the user that started the batch. Ignored if <c>token</c> is non-null.</param> public void Remove(ulong id, string token, string user, string password) { lock (m_Queue) { int i; for (i = 0; i < m_Queue.Count && ((DataProcessingBatchDesc)m_Queue[i]).Id != id; i++) { ; } if (i == m_Queue.Count) { throw new Exception("Batch not present in processing queue."); } DataProcessingBatchDesc dpb = (DataProcessingBatchDesc)m_Queue[i]; bool OkToRemove = false; if (token != null) { if (dpb.Token != null) { if (dpb.Token == token) { OkToRemove = true; } else { throw new Exception("A process operation cannot remove a batch of another process operation."); } } else { throw new Exception("A process operation cannot remove a batch that has been started with a specific user request."); } } else { long id_user = 0; SySal.OperaDb.OperaDbConnection conn = null; try { conn = new SySal.OperaDb.OperaDbConnection(OperaDataProcessingServer.DBServer, OperaDataProcessingServer.DBUserName, OperaDataProcessingServer.DBPassword); conn.Open(); id_user = SySal.OperaDb.ComputingInfrastructure.User.CheckLogin(user, password, conn, null); if (dpb.Token != null) { try { SySal.OperaDb.ComputingInfrastructure.User.CheckTokenOwnership(dpb.Token, id_user, null, null, conn, null); OkToRemove = true; } catch (Exception) { throw new Exception("A user cannot remove a batch started by an operation of another user."); } } else { if (String.Compare(dpb.Username, user, true) != 0) { throw new Exception("A user cannot stop a batch scheduled by another user!"); } else { OkToRemove = true; } } } catch (Exception) { if (conn != null) { conn.Close(); } } } if (OkToRemove == false) { throw new Exception("Cannot remove the batch."); } if (i == 0) { try { m_ExecProc.Kill(); m_ExecProcKilled = true; } catch (Exception) {} } else { lock (m_ResultList) { m_Queue.RemoveAt(i); DataProcessingResult dpr = null; for (i = 0; i < m_ResultList.Count; i++) { dpr = (DataProcessingResult)m_ResultList[i]; if (dpr.Desc.Id == id) { return; } } dpr = new DataProcessingResult(dpb, m_ResultLiveTime); dpr.X = new Exception("The batch was removed from the queue."); dpr.Processed = true; m_ResultList.Add(dpr); } } } }
/// <summary> /// Execution thread method. /// </summary> protected void ExecThread() { while (m_QueueNotEmpty.WaitOne()) { while (m_Queue.Count > 0) { SySal.OperaDb.OperaDbCredentials cred = new SySal.OperaDb.OperaDbCredentials(); DataProcessingBatchDesc desc = null; System.Exception retX = null; string retXstr = ""; m_ExecProc = new System.Diagnostics.Process(); lock (m_ExecProc) { m_ExecProcKilled = false; lock (m_Queue) { desc = (DataProcessingBatchDesc)m_Queue[0]; } m_ExecProc.StartInfo.Arguments = desc.CommandLineArguments; m_ExecProc.StartInfo.FileName = desc.Filename; m_ExecProc.StartInfo.UseShellExecute = false; m_ExecProc.StartInfo.RedirectStandardError = true; desc.Started = desc.Finished = System.DateTime.Now; try { cred.DBUserName = (desc.AliasUsername == null) ? "" : desc.AliasUsername; cred.DBPassword = (desc.AliasPassword == null) ? "" : desc.AliasPassword; cred.DBServer = OperaDataProcessingServer.DBServer; cred.OPERAUserName = (desc.Username == null) ? "" : desc.Username; cred.OPERAPassword = (desc.Password == null) ? "" : desc.Password; cred.RecordToEnvironment(m_ExecProc.StartInfo.EnvironmentVariables); desc.Started = System.DateTime.Now; m_ExecProc.Start(); } catch (Exception x) { retX = new DataProcessingException("Internal error occurred during process start.", x); } try { m_ExecProc.PriorityClass = OperaDataProcessingServer.LowPriority ? System.Diagnostics.ProcessPriorityClass.BelowNormal : System.Diagnostics.ProcessPriorityClass.Normal; //m_ExecProc.MaxWorkingSet = new System.IntPtr(OperaDataProcessingServer.PeakWorkingSetMB * 1048576); } catch (Exception) { } } if (retX == null) { //do { try { m_ExecProc.Refresh(); retXstr += m_ExecProc.StandardError.ReadToEnd(); desc.TotalProcessorTime = m_ExecProc.TotalProcessorTime; desc.PeakVirtualMemorySize = m_ExecProc.PeakVirtualMemorySize; desc.PeakWorkingSet = m_ExecProc.PeakWorkingSet; } catch (Exception) {} } //while (m_ExecProc.WaitForExit(1000) == false); desc.Finished = System.DateTime.Now; lock (m_ExecProc) { /* * try * { * retXstr += m_ExecProc.StandardError.ReadToEnd(); * } * catch (Exception) {}*/ if (retXstr == null || retXstr.Length == 0) { retX = null; } else { retX = new DataProcessingException(retXstr); } if (m_ExecProcKilled) { retX = new Exception("Process has been killed."); } } } else { try { retXstr += m_ExecProc.StandardError.ReadToEnd(); } catch (Exception) {} } m_ExecProc = null; SySal.OperaDb.OperaDbConnection conn = null; lock (m_ResultList) lock (m_Queue) { DataProcessingResult dpr = new DataProcessingResult(desc, m_ResultLiveTime); dpr.Processed = true; dpr.X = retX; m_ResultList.Add(dpr); m_Queue.RemoveAt(0); } } } }
public ProcOpInfo(SySal.OperaDb.OperaDbCredentials cred, long procopid, ref SySal.OperaDb.OperaDbConnection Conn) { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // //SySal.OperaDb.OperaDbConnection Conn = null; try { if (Conn == null) { Conn = new SySal.OperaDb.OperaDbConnection(cred.DBServer, cred.DBUserName, cred.DBPassword); Conn.Open(); } System.Data.DataSet dsprocop = new System.Data.DataSet(); new SySal.OperaDb.OperaDbDataAdapter("SELECT /*+INDEX (TB_PROC_OPERATIONS PK_PROC_OPERATIONS) */ ID_MACHINE, ID_PARENT_OPERATION, ID_PROGRAMSETTINGS, DRIVERLEVEL, ID_EVENTBRICK, ID_PLATE, STARTTIME, FINISHTIME, SUCCESS, ID_REQUESTER, ID_CALIBRATION_OPERATION FROM TB_PROC_OPERATIONS WHERE ID = " + procopid, Conn, null).Fill(dsprocop); IDText.Text = procopid.ToString(); ParentIDText.Text = dsprocop.Tables[0].Rows[0][1].ToString(); DriverLevelText.Text = ((SySal.DAQSystem.Drivers.DriverType)Convert.ToInt32(dsprocop.Tables[0].Rows[0][3])).ToString() + " (" + dsprocop.Tables[0].Rows[0][3].ToString() + ")"; BrickText.Text = dsprocop.Tables[0].Rows[0][4].ToString(); PlateText.Text = dsprocop.Tables[0].Rows[0][5].ToString(); StartTimeText.Text = Convert.ToDateTime(dsprocop.Tables[0].Rows[0][6]).ToString("dd/MM/yyyy HH:mm:ss"); if (dsprocop.Tables[0].Rows[0][7] != System.DBNull.Value) { FinishTimeText.Text = Convert.ToDateTime(dsprocop.Tables[0].Rows[0][7]).ToString("dd/MM/yyyy HH:mm:ss"); switch (dsprocop.Tables[0].Rows[0][8].ToString()) { case "N": ResultText.Text = "Failure"; break; case "Y": ResultText.Text = "Success"; break; case "R": ResultText.Text = "Running"; break; default: ResultText.Text = "Other (" + dsprocop.Tables[0].Rows[0][8].ToString() + ")"; break; } } MachineText.Text = new SySal.OperaDb.OperaDbCommand("SELECT /*+INDEX (TB_MACHINES PK_MACHINES) */ NAME FROM TB_MACHINES WHERE ID = " + dsprocop.Tables[0].Rows[0][0].ToString(), Conn, null).ExecuteScalar().ToString(); RequesterText.Text = new SySal.OperaDb.OperaDbCommand("SELECT /*+INDEX (TB_USERS PK_USERS) */ NAME || ' ' || SURNAME FROM VW_USERS WHERE ID = " + dsprocop.Tables[0].Rows[0][9].ToString(), Conn, null).ExecuteScalar().ToString(); CalibrationText.Text = (dsprocop.Tables[0].Rows[0][10] == System.DBNull.Value) ? "None" : dsprocop.Tables[0].Rows[0][10].ToString(); System.Data.DataSet dsprog = new System.Data.DataSet(); new SySal.OperaDb.OperaDbDataAdapter("SELECT /*+INDEX (TB_PROGRAMSETTINGS PK_PROGRAMSETTINGS) */ TEMPLATEMARKS, ID_AUTHOR, DESCRIPTION, EXECUTABLE, SETTINGS FROM TB_PROGRAMSETTINGS WHERE ID = " + dsprocop.Tables[0].Rows[0][2].ToString(), Conn, null).Fill(dsprog); //CalibrationText.Text = (Convert.ToInt32(dsprog.Tables[0].Rows[0][0]) == 0) ? "No" : "Yes"; AuthorText.Text = new SySal.OperaDb.OperaDbCommand("SELECT /*+INDEX (TB_USERS PK_USERS) */ NAME || ' ' || SURNAME FROM VW_USERS WHERE ID = " + dsprog.Tables[0].Rows[0][1].ToString(), Conn, null).ExecuteScalar().ToString(); DescriptionText.Text = dsprog.Tables[0].Rows[0][2].ToString(); ExeText.Text = dsprog.Tables[0].Rows[0][3].ToString(); SettingsText.Text = dsprog.Tables[0].Rows[0][4].ToString(); } catch (Exception x) { if (Conn != null) { Conn.Close(); Conn = null; } MessageBox.Show(x.ToString(), x.Message, MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public frmAreaScan2Config(long settingsId, SySal.OperaDb.OperaDbConnection conn) { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // _connection = conn; Utilities.FillComboBox(linkingComboBox, @"SELECT ID, DESCRIPTION FROM TB_PROGRAMSETTINGS WHERE EXECUTABLE LIKE 'BatchLink%.exe'", conn); Utilities.FillComboBox(scanningComboBox, @"SELECT ID, DESCRIPTION FROM TB_PROGRAMSETTINGS WHERE EXECUTABLE LIKE 'ScanServer%.exe'", conn); Utilities.FillComboBox(qualityComboBox, @"SELECT ID, DESCRIPTION FROM TB_PROGRAMSETTINGS WHERE EXECUTABLE LIKE '%Sel.exe'", conn); if (settingsId != 0) { string settings = (string)(new SySal.OperaDb.OperaDbCommand("SELECT SETTINGS FROM TB_PROGRAMSETTINGS WHERE ID = " + settingsId, conn)).ExecuteScalar(); System.Xml.Serialization.XmlSerializer xmls = new System.Xml.Serialization.XmlSerializer(typeof(AreaScan2Settings)); ProgSettings = (AreaScan2Settings)xmls.Deserialize(new System.IO.StringReader(settings)); _originalConfigName = _currentConfigName = configNameTextBox.Text = (string)(new SySal.OperaDb.OperaDbCommand("SELECT DESCRIPTION FROM TB_PROGRAMSETTINGS WHERE ID = " + settingsId, conn)).ExecuteScalar(); /*linkingComboBox.SelectedValue = _linkingConfigId; * scanningComboBox.SelectedValue = _scanningConfigId; * qualityComboBox.SelectedValue = _qualityCutId;*/ } else { ProgSettings = new AreaScan2Settings(); ProgSettings.Quality = new QualitySettings(); ProgSettings.Recalibration = new RecalibrationSettings(); ProgSettings.Reuse = new ReuseSettings(); } posTolTextBox.Text = ProgSettings.Recalibration.PositionTolerance.ToString(); posTolIncTextBox.Text = ProgSettings.Recalibration.PositionToleranceIncreaseWithSlope.ToString(); slopeTolTextBox.Text = ProgSettings.Recalibration.SlopeTolerance.ToString(); slopeTolIncTextBox.Text = ProgSettings.Recalibration.SlopeToleranceIncreaseWithSlope.ToString(); maxTrialsTextBox.Text = ProgSettings.Quality.MaxTrials.ToString(); baseThicknessTextBox.Text = ProgSettings.Recalibration.BaseThickness.ToString(); txtRecalibrationSelection.Text = ProgSettings.Recalibration.SelectionText; txtMinXDistance.Text = ProgSettings.Recalibration.MinXDistance.ToString(); txtMinYDistance.Text = ProgSettings.Recalibration.MinYDistance.ToString(); txtMinTracks.Text = ProgSettings.Recalibration.MinTracks.ToString(); txtMinDensityBase.Text = ProgSettings.Quality.MinDensityBase.ToString(); txtMinOverlapArea.Text = ProgSettings.Reuse.MinOverlapArea.ToString(); txtMinOverlapFraction.Text = ProgSettings.Reuse.MinOverlapFraction.ToString(); txtMaxMissingArea.Text = ProgSettings.Reuse.MaxMissingArea.ToString(); chkEnableReuse.Checked = ProgSettings.Reuse.Enable; chkEnableReuse_CheckedChanged(this, null); // txtPositionTolerance.Text = ProgSettings.PositionTolerance.ToString(); _linkingConfigId = ProgSettings.LinkConfigId; _scanningConfigId = ProgSettings.ScanningConfigId; _qualityCutId = ProgSettings.QualityCutId; Utilities.SelectId(scanningComboBox, _scanningConfigId); Utilities.SelectId(linkingComboBox, _linkingConfigId); Utilities.SelectId(qualityComboBox, _qualityCutId); if (ProgSettings.Reuse.ProgramSettingsIds != null) { foreach (long id in ProgSettings.Reuse.ProgramSettingsIds) { lstReuseIds.Items.Add(new Utilities.ConfigItem(Utilities.LookupItem(id, _connection), id)); } } btnCreate.Enabled = ConfigNameIsValid() & IsFormFilled(); }
static void Main(string[] args) { if (args.Length > 0 && String.Compare(args[0], "/fulldump", true) == 0) { FullZoneDump = true; string[] oldargs = args; int i; args = new string[oldargs.Length - 1]; for (i = 0; i < args.Length; i++) { args[i] = oldargs[i + 1]; } oldargs = null; } System.Xml.Serialization.XmlSerializer xmls = null; if (args.Length == 5) { MakeSlopeAdjustment = true; try { xmls = new System.Xml.Serialization.XmlSerializer(typeof(AdjustTrackParameterSet)); C = new AdjustTrackParameterSet(); C = (AdjustTrackParameterSet)xmls.Deserialize(new System.IO.StreamReader(args[4])); xmls = null; C = null; } catch { try { xmls = new System.Xml.Serialization.XmlSerializer(typeof(SySal.Executables.BatchLink.Config)); SySal.Executables.BatchLink.Config config = (SySal.Executables.BatchLink.Config)xmls.Deserialize(new System.IO.StreamReader(args[4])); xmls = null; C = new AdjustTrackParameterSet(); C.BottomDeltaSlopeX = config.BottomDeltaSlopeX; C.BottomDeltaSlopeY = config.BottomDeltaSlopeY; C.BottomMultSlopeX = config.BottomMultSlopeX; C.BottomMultSlopeY = config.BottomMultSlopeY; C.TopDeltaSlopeX = config.TopDeltaSlopeX; C.TopDeltaSlopeY = config.TopDeltaSlopeY; C.TopMultSlopeX = config.TopMultSlopeX; C.TopMultSlopeY = config.TopMultSlopeY; } catch { throw new Exception("correction path non correct"); } } string[] oldargs = args; int i; args = new string[oldargs.Length - 1]; for (i = 0; i < args.Length; i++) { args[i] = oldargs[i]; } oldargs = null; } if (args.Length != 4) { Console.WriteLine("usage: DumpZone [/fulldump] <StartupFile path> <RWC path> <TLG path> <series> [XML correction path]"); Console.WriteLine("XML correction syntax could be the batchlink configuration, otherwise"); Console.WriteLine("XML correction syntax:"); xmls = new System.Xml.Serialization.XmlSerializer(typeof(AdjustTrackParameterSet)); System.IO.StringWriter ss = new System.IO.StringWriter(); xmls.Serialize(ss, C); Console.WriteLine(ss.ToString()); ss.Close(); return; } string startupfile = args[0]; string rwcpath = args[1]; string tlgpath = args[2]; int series = System.Convert.ToInt32(args[3]); xmls = new System.Xml.Serialization.XmlSerializer(typeof(SySal.DAQSystem.Drivers.ScanningStartupInfo)); StartupInfo = (SySal.DAQSystem.Drivers.ScanningStartupInfo)xmls.Deserialize(new System.IO.StreamReader(startupfile)); xmls = null; Conn = new SySal.OperaDb.OperaDbConnection(StartupInfo.DBServers, StartupInfo.DBUserName, StartupInfo.DBPassword); Conn.Open(); SySal.OperaDb.Schema.DB = Conn; Trans = Conn.BeginTransaction(); SySal.Scanning.Plate.IO.OPERA.LinkedZone lz = null; try { lz = (SySal.Scanning.Plate.IO.OPERA.LinkedZone)SySal.OperaPersistence.Restore(tlgpath, typeof(SySal.Scanning.Plate.IO.OPERA.LinkedZone)); if (MakeSlopeAdjustment == true && C != null) { AdjustSlopes(lz); } DumpZone(tlgpath, lz, StartupInfo.Plate.BrickId, StartupInfo.Plate.PlateId, StartupInfo.ProcessOperationId, series, StartupInfo.RawDataPath, System.IO.File.GetCreationTime(rwcpath), System.DateTime.Now, Conn, Trans); Trans.Commit(); } catch (Exception x) { if (Trans != null) { Trans.Rollback(); } Console.WriteLine(x.Message); } Conn.Close(); }
private static long DumpZone(string tlgpath, SySal.Scanning.Plate.IO.OPERA.LinkedZone lz, long db_brick_id, long db_plate_id, long db_procop_id, long series, string rawdatapath, DateTime starttime, DateTime endtime, SySal.OperaDb.OperaDbConnection conn, SySal.OperaDb.OperaDbTransaction trans) { try { long db_id_zone = 0; int s, i, n; double dz, basez; SySal.Scanning.Plate.Side side; SySal.DAQSystem.Scanning.IntercalibrationInfo transform = lz.Transform; double TDX = transform.TX - transform.MXX * transform.RX - transform.MXY * transform.RY; double TDY = transform.TY - transform.MYX * transform.RX - transform.MYY * transform.RY; //zone db_id_zone = SySal.OperaDb.Schema.TB_ZONES.Insert(db_brick_id, db_plate_id, db_procop_id, db_id_zone, lz.Extents.MinX, lz.Extents.MaxX, lz.Extents.MinY, lz.Extents.MaxY, tlgpath, starttime, endtime, series, transform.MXX, transform.MXY, transform.MYX, transform.MYY, TDX, TDY); if (FullZoneDump == false) { return(db_id_zone); } //views for (s = 0; s < 2; s++) { if (s == 0) { side = lz.Top; basez = lz.Top.BottomZ; } else { side = lz.Bottom; basez = lz.Bottom.TopZ; } n = ((SySal.Scanning.Plate.IO.OPERA.LinkedZone.Side)side).ViewCount; for (i = 0; i < n; i++) { SySal.Scanning.Plate.IO.OPERA.LinkedZone.View vw = ((SySal.Scanning.Plate.IO.OPERA.LinkedZone.Side)side).View(i); SySal.OperaDb.Schema.TB_VIEWS.Insert(db_brick_id, db_id_zone, s + 1, //i + 1, vw.Id + 1, vw.TopZ, vw.BottomZ, vw.Position.X, vw.Position.Y); } } SySal.OperaDb.Schema.TB_VIEWS.Flush(); int TrackId = 0; int UpTrackId = 0; int DownTrackId = 0; SySal.Tracking.MIPEmulsionTrackInfo info = null; SySal.Tracking.MIPEmulsionTrackInfo tinfo = null; SySal.Tracking.MIPEmulsionTrackInfo binfo = null; //Basetracks for (i = 0; i < lz.Length; i++) { if (lz[i].Info.Sigma >= 0) { info = lz[i].Info; tinfo = lz[i].Top.Info; binfo = lz[i].Bottom.Info; } else { continue; } DownTrackId++; basez = lz.Top.BottomZ; dz = (basez - tinfo.Intercept.Z); SySal.OperaDb.Schema.TB_MIPMICROTRACKS.Insert(db_brick_id, db_id_zone, 1, DownTrackId, tinfo.Intercept.X + tinfo.Slope.X * dz, tinfo.Intercept.Y + tinfo.Slope.Y * dz, tinfo.Slope.X, tinfo.Slope.Y, tinfo.Count, tinfo.AreaSum, System.DBNull.Value, tinfo.Sigma, ((SySal.Scanning.Plate.IO.OPERA.LinkedZone.MIPIndexedEmulsionTrack)(lz.Top[i])).View.Id + 1); UpTrackId++; basez = lz.Bottom.TopZ; dz = (basez - binfo.Intercept.Z); SySal.OperaDb.Schema.TB_MIPMICROTRACKS.Insert(db_brick_id, db_id_zone, 2, UpTrackId, binfo.Intercept.X + binfo.Slope.X * dz, binfo.Intercept.Y + binfo.Slope.Y * dz, binfo.Slope.X, binfo.Slope.Y, binfo.Count, binfo.AreaSum, System.DBNull.Value, binfo.Sigma, ((SySal.Scanning.Plate.IO.OPERA.LinkedZone.MIPIndexedEmulsionTrack)(lz.Bottom[i])).View.Id + 1); TrackId++; basez = ((SySal.Scanning.Plate.IO.OPERA.LinkedZone.MIPIndexedEmulsionTrack)(lz[i].Top)).View.BottomZ; dz = 0; //TODO (basez - info.Intercept.Z); SySal.OperaDb.Schema.TB_MIPBASETRACKS.Insert(db_brick_id, db_id_zone, TrackId, info.Intercept.X + info.Slope.X * dz, info.Intercept.Y + info.Slope.Y * dz, info.Slope.X, info.Slope.Y, info.Count, info.AreaSum, System.DBNull.Value, info.Sigma, 1, DownTrackId, 2, UpTrackId); } //Microtracks for (i = 0; i < lz.Length; i++) { if (lz[i].Info.Sigma >= 0) { continue; } else if (lz[i].Top.Info.Sigma >= 0) { tinfo = lz[i].Top.Info; DownTrackId++; basez = lz.Top.BottomZ; dz = (basez - tinfo.Intercept.Z); SySal.OperaDb.Schema.TB_MIPMICROTRACKS.Insert(db_brick_id, db_id_zone, 1, DownTrackId, tinfo.Intercept.X + tinfo.Slope.X * dz, tinfo.Intercept.Y + tinfo.Slope.Y * dz, tinfo.Slope.X, tinfo.Slope.Y, tinfo.Count, tinfo.AreaSum, System.DBNull.Value, tinfo.Sigma, ((SySal.Scanning.Plate.IO.OPERA.LinkedZone.MIPIndexedEmulsionTrack)(lz.Top[i])).View.Id + 1); } else if (lz[i].Bottom.Info.Sigma >= 0) { binfo = lz[i].Bottom.Info; UpTrackId++; basez = lz.Bottom.TopZ; dz = (basez - binfo.Intercept.Z); SySal.OperaDb.Schema.TB_MIPMICROTRACKS.Insert(db_brick_id, db_id_zone, 2, UpTrackId, binfo.Intercept.X + binfo.Slope.X * dz, binfo.Intercept.Y + binfo.Slope.Y * dz, binfo.Slope.X, binfo.Slope.Y, binfo.Count, binfo.AreaSum, System.DBNull.Value, binfo.Sigma, ((SySal.Scanning.Plate.IO.OPERA.LinkedZone.MIPIndexedEmulsionTrack)(lz.Bottom[i])).View.Id + 1); } } SySal.OperaDb.Schema.TB_MIPMICROTRACKS.Flush(); SySal.OperaDb.Schema.TB_MIPBASETRACKS.Flush(); return(db_id_zone); } catch (Exception x) { throw x; } }
static void Main(string[] args) { if (args.Length != 7) { Console.WriteLine("usage: CSRelatedGraphSelector.exe <tlg file> <ascii file> <brick> <plate> <mingrains> <postol> <slopetol>"); Console.WriteLine("output: BRICK PLATE GRAINS PX PY PZ SX SY SIGMA DPX DPY DSX DSY"); return; } int brickid = Convert.ToInt32(args[2]); if (brickid > 1999999) { Console.WriteLine("No track to select on a CS."); System.IO.File.WriteAllText(args[1], "\r\n"); return; } SySal.OperaDb.OperaDbConnection conn = SySal.OperaDb.OperaDbCredentials.CreateFromRecord().Connect(); conn.Open(); int csid = brickid; try { csid = SySal.OperaDb.Convert.ToInt32(new SySal.OperaDb.OperaDbCommand("SELECT MAX(ID) FROM TB_EVENTBRICKS WHERE MOD(ID,1000000) = " + (brickid - (brickid / 1000000) * 1000000), conn).ExecuteScalar()); } catch (Exception) { } SySal.OperaDb.OperaDbDataReader csr = new SySal.OperaDb.OperaDbCommand("SELECT (ID_PLATE - 1) * 300 + 4850 as Z, POSX, POSY, SLOPEX, SLOPEY FROM VW_LOCAL_CS_CANDIDATES WHERE ID_CS_EVENTBRICK = " + csid, conn).ExecuteReader(); System.Collections.ArrayList arr = new System.Collections.ArrayList(); while (csr.Read()) { SySal.Tracking.MIPEmulsionTrackInfo info = new SySal.Tracking.MIPEmulsionTrackInfo(); info.Intercept.Z = csr.GetDouble(0); info.Intercept.X = csr.GetDouble(1); info.Intercept.Y = csr.GetDouble(2); info.Slope.X = csr.GetDouble(3); info.Slope.Y = csr.GetDouble(4); arr.Add(info); } csr.Close(); double Z = SySal.OperaDb.Convert.ToDouble(new SySal.OperaDb.OperaDbCommand("SELECT Z FROM TB_PLATES WHERE ID_EVENTBRICK = " + brickid + " AND ID = " + Convert.ToInt32(args[3]).ToString(), conn).ExecuteScalar()); conn.Close(); SySal.DataStreams.OPERALinkedZone lz = new SySal.DataStreams.OPERALinkedZone(args[0]); int basen = lz.Length; int i; int mingrains = Convert.ToInt32(args[4]); double postol = Convert.ToDouble(args[5]); double slopetol = Convert.ToDouble(args[6]); string outstr = ""; int sel = 0; for (i = 0; i < basen; i++) { SySal.Tracking.MIPEmulsionTrackInfo lzinfo = lz[i].Info; if (lzinfo.Count < mingrains) { continue; } foreach (SySal.Tracking.MIPEmulsionTrackInfo csinfo in arr) { double dz = Math.Abs(csinfo.Intercept.Z - Z); double slopescatt = 0.014 * Math.Sqrt(dz / (1.3 * 5600.0)); /* assume 1 GeV */ double posscatt = slopescatt * dz / Math.Sqrt(3.0); double dsx = csinfo.Slope.X - lzinfo.Slope.X; double dsy = csinfo.Slope.Y - lzinfo.Slope.Y; if (dsx * dsx + dsy * dsy > (2.0 * (slopescatt * slopescatt + slopetol * slopetol))) { continue; } double dpx = csinfo.Intercept.X + (Z - csinfo.Intercept.Z) * (csinfo.Slope.X + lzinfo.Slope.X) * 0.5 - lzinfo.Intercept.X; double dpy = csinfo.Intercept.Y + (Z - csinfo.Intercept.Z) * (csinfo.Slope.Y + lzinfo.Slope.Y) * 0.5 - lzinfo.Intercept.Y; if (dpx * dpx + dpy * dpy > (2.0 * (posscatt * posscatt + postol * postol))) { continue; } outstr += "\r\n" + brickid + " " + args[3] + " " + lzinfo.Count + " " + lzinfo.Intercept.X + " " + lzinfo.Intercept.Y + " " + Z + " " + lzinfo.Slope.X + " " + lzinfo.Slope.Y + " " + lzinfo.Sigma + " " + dpx + " " + dpy + " " + dsx + " " + dsy; sel++; break; } } Console.WriteLine("Selected: " + sel + " track(s)"); System.IO.File.WriteAllText(args[1], outstr); }
static void Main(string[] args) { SySal.OperaDb.OperaDbCredentials cred = SySal.OperaDb.OperaDbCredentials.CreateFromRecord(); SySal.OperaDb.OperaDbConnection conn = new SySal.OperaDb.OperaDbConnection(cred.DBServer, cred.DBUserName, cred.DBPassword); conn.Open(); Console.WriteLine("namespace SySal.OperaDb"); Console.WriteLine("{"); Console.WriteLine("\t/// <summary>"); Console.WriteLine("\t/// Static class that allows access to schema components of the OPERA DB."); Console.WriteLine("\t/// Its DB field must be set before the class can be used."); Console.WriteLine("\t/// </summary>"); Console.WriteLine("\tpublic class Schema"); Console.WriteLine("\t{"); Console.WriteLine("\t\tprivate Schema() {}"); Console.WriteLine("\t\t/// <summary>"); Console.WriteLine("\t\t/// Retrieval order for query results."); Console.WriteLine("\t\t/// </summary>"); Console.WriteLine("\t\tpublic enum OrderBy { None, Ascending, Descending }"); string ondbsetprepared = ""; System.Data.DataSet ds_tb = new System.Data.DataSet(); new SySal.OperaDb.OperaDbDataAdapter("SELECT TABLE_NAME FROM ALL_TABLES WHERE OWNER = 'OPERA' AND (TABLE_NAME LIKE 'TB_%' OR TABLE_NAME LIKE 'LZ_%') ORDER BY TABLE_NAME ASC", conn, null).Fill(ds_tb); foreach (System.Data.DataRow dr_tb in ds_tb.Tables[0].Rows) { ondbsetprepared += "\t\t\t\tif (" + dr_tb[0].ToString() + ".Prepared) { " + dr_tb[0].ToString() + ".cmd.Connection = null; " + dr_tb[0].ToString() + ".Prepared = false; }\n"; string AutoIdColumn = null; try { AutoIdColumn = new SySal.OperaDb.OperaDbCommand("SELECT COLUMN_NAME FROM ALL_TRIGGER_COLS WHERE TABLE_NAME = '" + dr_tb[0].ToString() + "' AND TABLE_OWNER = 'OPERA' AND COLUMN_USAGE = 'NEW OUT'", conn, null).ExecuteScalar().ToString(); if (AutoIdColumn == "") { AutoIdColumn = null; } } catch (Exception) { AutoIdColumn = null; } Console.WriteLine("\t\t/// <summary>"); Console.WriteLine("\t\t/// Accesses the " + dr_tb[0].ToString() + " table in the DB."); if (AutoIdColumn == null) { Console.WriteLine("\t\t/// For data insertion, the Insert and Flush static methods are used. This class inserts data in batches."); } else { Console.WriteLine("\t\t/// For data insertion, the Insert method is used. Rows are inserted one by one."); } Console.WriteLine("\t\t/// An instance of the class is produced for data retrieval."); Console.WriteLine("\t\t/// </summary>"); Console.WriteLine("\t\tpublic class " + dr_tb[0].ToString()); Console.WriteLine("\t\t{"); Console.WriteLine("\t\t\tinternal " + dr_tb[0].ToString() + "() {}"); Console.WriteLine("\t\t\tSystem.Data.DataRowCollection m_DRC;"); if (AutoIdColumn == null) { Console.WriteLine("\t\t\tconst int ArraySize = 100;"); Console.WriteLine("\t\t\tstatic int index = 0;"); Console.WriteLine("\t\t\t/// <summary>"); Console.WriteLine("\t\t\t/// Since this class uses batch insertion, this method must be called to ensure that all rows are actually inserted into " + dr_tb[0].ToString() + ". Failure to do so will result in incomplete writes."); Console.WriteLine("\t\t\t/// </summary>"); Console.WriteLine("\t\t\tstatic public void Flush() { if (cmd == null || index == 0) return; cmd.ArrayBindCount = index; cmd.ExecuteNonQuery(); index = 0; }"); } ; System.Data.DataSet ds_col = new System.Data.DataSet(); new SySal.OperaDb.OperaDbDataAdapter("SELECT COLUMN_NAME, DATA_TYPE, DATA_PRECISION, DATA_SCALE, NULLABLE, DATA_LENGTH FROM ALL_TAB_COLUMNS WHERE OWNER = 'OPERA' AND TABLE_NAME = '" + dr_tb[0].ToString() + "' ORDER BY COLUMN_ID", conn, null).Fill(ds_col); object pk_obj = new SySal.OperaDb.OperaDbCommand("SELECT CONSTRAINT_NAME FROM ALL_CONSTRAINTS WHERE OWNER = 'OPERA' AND CONSTRAINT_TYPE = 'P' AND TABLE_NAME = '" + dr_tb[0].ToString() + "'", conn, null).ExecuteScalar(); string colstring = ""; string parstring = ""; string parslotstring = ""; int parcount = 0; string insertparamstring = ""; string insertparslotstring = ""; string inserthelpparamstring = ""; foreach (System.Data.DataRow dr_col in ds_col.Tables[0].Rows) { if (parcount > 0) { colstring += ","; parstring += ","; insertparamstring += ","; } parcount++; colstring += dr_col[0].ToString(); parstring += ":p_" + parcount; string array_type = "object"; string data_type = "UNKNOWN-" + dr_col[1].ToString(); string oratype_string = "UNKNOWN-" + dr_col[1].ToString(); string convertstr = "UNKNOWN"; bool isnullable = true; if (dr_col[1].ToString() == "NUMBER" && dr_col[3].ToString() == "0") { if (dr_col[2] == System.DBNull.Value || Convert.ToInt32(dr_col[2]) > 8) { data_type = "long"; oratype_string = "SySal.OperaDb.OperaDbType.Long"; convertstr = "Int64"; } else { data_type = "int"; oratype_string = "SySal.OperaDb.OperaDbType.Int"; convertstr = "Int32"; } } else if (dr_col[1].ToString() == "FLOAT" || dr_col[1].ToString() == "NUMBER") { data_type = "double"; oratype_string = "SySal.OperaDb.OperaDbType.Double"; convertstr = "Double"; } else if (dr_col[1].ToString() == "CHAR") { if (SySal.OperaDb.Convert.ToInt32(dr_col[5]) == 1) { data_type = "char"; oratype_string = "SySal.OperaDb.OperaDbType.String"; convertstr = "Char"; } else { data_type = "string"; oratype_string = "SySal.OperaDb.OperaDbType.String"; convertstr = "String"; } } else if (dr_col[1].ToString() == "VARCHAR2") { data_type = "string"; oratype_string = "SySal.OperaDb.OperaDbType.String"; convertstr = "String"; } else if (dr_col[1].ToString() == "DATE" || dr_col[1].ToString().StartsWith("TIMESTAMP")) { data_type = "System.DateTime"; oratype_string = "SySal.OperaDb.OperaDbType.DateTime"; convertstr = "DateTime"; } else if (dr_col[1].ToString() == "CLOB") { data_type = "string"; oratype_string = "SySal.OperaDb.OperaDbType.CLOB"; convertstr = "String"; } else if (dr_col[1].ToString() == "BLOB") { data_type = "byte []"; oratype_string = "SySal.OperaDb.OperaDbType.BLOB"; convertstr = "Bytes"; } if (dr_col[4].ToString() == "N") { array_type = data_type; isnullable = false; } parslotstring += "\t\t\t\tnewcmd.Parameters.Add(\"p_" + parcount + "\", " + oratype_string + ", System.Data.ParameterDirection.Input)" + ((AutoIdColumn != null) ? "" : (".Value = a_" + dr_col[0].ToString().Replace("#", "_SHARP_"))) + ";\n"; insertparamstring += array_type + " i_" + dr_col[0].ToString().Replace("#", "_SHARP_"); if (AutoIdColumn == null || AutoIdColumn != dr_col[0].ToString()) { inserthelpparamstring += "\t\t\t/// <param name=\"i_" + dr_col[0].ToString().Replace("#", "_SHARP_") + "\">the value to be inserted for " + dr_col[0].ToString() + (isnullable ? (". The value for this parameter can be " + data_type + " or System.DBNull.Value") : "") + ".</param>\n"; } else { inserthelpparamstring += "\t\t\t/// <param name=\"i_" + dr_col[0].ToString().Replace("#", "_SHARP_") + "\">the value to be inserted for " + dr_col[0].ToString() + (isnullable ? (". The value for this parameter can be " + data_type + " or System.DBNull.Value") : "") + ". This value is actually used only if this method call is involved in data publication/replication, otherwise the actual value is generated by the OPERA DB and the supplied value is ignored.</param>\n"; } if (AutoIdColumn == null) { insertparslotstring += "\t\t\t\ta_" + dr_col[0].ToString().Replace("#", "_SHARP_") + "[index] = i_" + dr_col[0].ToString().Replace("#", "_SHARP_") + ";\n"; Console.WriteLine("\t\t\tprivate static " + array_type + " [] a_" + dr_col[0].ToString().Replace("#", "_SHARP_") + " = new " + array_type + "[ArraySize];"); } else { insertparslotstring += "\t\t\t\tcmd.Parameters[" + (parcount - 1) + "].Value = i_" + dr_col[0].ToString().Replace("#", "_SHARP_") + ";\n"; } Console.WriteLine("\t\t\t/// <summary>"); Console.WriteLine("\t\t\t/// Retrieves " + dr_col[0].ToString() + " for the current row." + (isnullable ? (" The return value can be System.DBNull.Value or a value that can be cast to " + data_type + ".") : "")); Console.WriteLine("\t\t\t/// </summary>"); Console.WriteLine("\t\t\tpublic " + array_type + " _" + dr_col[0].ToString().Replace("#", "_SHARP_")); Console.WriteLine("\t\t\t{"); Console.WriteLine("\t\t\t\tget"); Console.WriteLine("\t\t\t\t{"); if (isnullable) { Console.WriteLine("\t\t\t\t\tif (m_DR[" + (parcount - 1) + "] == System.DBNull.Value) return System.DBNull.Value;"); } if (convertstr == "Bytes") { Console.WriteLine("\t\t\t\t\treturn SySal.OperaDb.Convert.To" + convertstr + "(m_DR[" + (parcount - 1) + "]);"); } else { Console.WriteLine("\t\t\t\t\treturn System.Convert.To" + convertstr + "(m_DR[" + (parcount - 1) + "]);"); } Console.WriteLine("\t\t\t\t}"); Console.WriteLine("\t\t\t}"); } if (AutoIdColumn != null) { parslotstring += "\t\t\t\tnewcmd.Parameters.Add(\"o_" + parcount + "\", SySal.OperaDb.OperaDbType.Long, System.Data.ParameterDirection.Output);\n"; Console.WriteLine("\t\t\t/// <summary>"); Console.WriteLine("\t\t\t/// Inserts one row into the DB. The row is inserted immediately."); Console.WriteLine("\t\t\t/// </summary>"); Console.Write(inserthelpparamstring); Console.WriteLine("\t\t\t/// <returns>the value of " + AutoIdColumn + " for the new row.</returns>"); Console.WriteLine("\t\t\tstatic public long Insert(" + insertparamstring + ")"); Console.WriteLine("\t\t\t{"); Console.WriteLine("\t\t\t\tif (!Prepared) { cmd.Connection = Schema.m_DB; Prepared = true; cmd.Prepare(); };"); Console.Write(insertparslotstring); Console.WriteLine("\t\t\t\tcmd.ExecuteNonQuery();"); Console.WriteLine("\t\t\t\treturn SySal.OperaDb.Convert.ToInt64(cmd.Parameters[" + parcount + "].Value);"); Console.WriteLine("\t\t\t}"); } else { Console.WriteLine("\t\t\t/// <summary>"); Console.WriteLine("\t\t\t/// Inserts one row into the DB. The row is actually inserted later, in a batch insertion command. The Flush method must be called to ensure all rows are actually written."); Console.WriteLine("\t\t\t/// </summary>"); Console.Write(inserthelpparamstring); Console.WriteLine("\t\t\tstatic public void Insert(" + insertparamstring + ")"); Console.WriteLine("\t\t\t{"); Console.WriteLine("\t\t\t\tif (!Prepared) { cmd.Connection = Schema.m_DB; Prepared = true; cmd.Prepare(); };"); Console.Write(insertparslotstring); Console.WriteLine("\t\t\t\tif (++index >= ArraySize) { cmd.ArrayBindCount = index; cmd.ExecuteNonQuery(); index = 0; }"); Console.WriteLine("\t\t\t}"); } if (pk_obj != null && pk_obj != System.DBNull.Value) { System.Data.DataSet dpks = new System.Data.DataSet(); new SySal.OperaDb.OperaDbDataAdapter("select column_name from all_cons_columns where all_cons_columns.owner = 'OPERA' and constraint_name = '" + pk_obj.ToString() + "'", conn, null).Fill(dpks); string selpkparams = ""; string orderbyascstring = ""; string orderbydescstring = ""; string selecthelpparamstring = ""; foreach (System.Data.DataRow dpkr in dpks.Tables[0].Rows) { if (selpkparams.Length == 0) { selpkparams = "object i_" + dpkr[0].ToString().Replace("#", "_SHARP_"); orderbyascstring = dpkr[0].ToString() + " ASC"; orderbydescstring = dpkr[0].ToString() + " DESC"; } else { selpkparams += ",object i_" + dpkr[0].ToString().Replace("#", "_SHARP_"); orderbyascstring += "," + dpkr[0].ToString() + " ASC"; orderbydescstring += "," + dpkr[0].ToString() + " DESC"; } selecthelpparamstring += "\t\t\t/// <param name=\"i_" + dpkr[0].ToString().Replace("#", "_SHARP_") + "\">if non-null, only rows that have this field equal to the specified value are returned.</param>\n"; } Console.WriteLine("\t\t\t/// <summary>"); Console.WriteLine("\t\t\t/// Reads a set of rows from " + dr_tb[0].ToString() + " and retrieves them into a new " + dr_tb[0].ToString() + " object."); Console.WriteLine("\t\t\t/// </summary>"); Console.Write(selecthelpparamstring); Console.WriteLine("\t\t\t/// <param name=\"order\">the ordering scheme to be applied to returned rows." + ((dpks.Tables[0].Rows.Count > 1) ? " This applies to all columns in the primary key." : "") + "</param>"); Console.WriteLine("\t\t\t/// <returns>a new instance of the " + dr_tb[0].ToString() + " class that can be used to read the retrieved data.</returns>"); Console.WriteLine("\t\t\tstatic public " + dr_tb[0].ToString() + " SelectPrimaryKey(" + selpkparams + ", OrderBy order)"); Console.WriteLine("\t\t\t{"); Console.WriteLine("\t\t\t\tstring wherestr = \"\";"); Console.WriteLine("\t\t\t\tstring wtempstr = \"\";"); foreach (System.Data.DataRow dpkr in dpks.Tables[0].Rows) { Console.WriteLine("\t\t\t\tif (i_" + dpkr[0].ToString().Replace("#", "_SHARP_") + " != null)"); Console.WriteLine("\t\t\t\t{"); Console.WriteLine("\t\t\t\t\tif (i_" + dpkr[0].ToString().Replace("#", "_SHARP_") + " == System.DBNull.Value) wtempstr = \"" + dpkr[0] + " IS NULL\";"); Console.WriteLine("\t\t\t\t\telse wtempstr = \"" + dpkr[0] + " = \" + i_" + dpkr[0].ToString().Replace("#", "_SHARP_") + ".ToString();"); Console.WriteLine("\t\t\t\t\tif (wherestr.Length == 0) wherestr = wtempstr; else wherestr += \" AND \" + wtempstr;"); Console.WriteLine("\t\t\t\t}"); } Console.WriteLine("\t\t\t\tif (order == OrderBy.Ascending) return SelectWhere(wherestr, \"" + orderbyascstring + "\");"); Console.WriteLine("\t\t\t\telse if (order == OrderBy.Descending) return SelectWhere(wherestr, \"" + orderbydescstring + "\");"); Console.WriteLine("\t\t\t\treturn SelectWhere(wherestr, null);"); Console.WriteLine("\t\t\t}"); } Console.WriteLine("\t\t\t/// <summary>"); Console.WriteLine("\t\t\t/// Reads a set of rows from " + dr_tb[0].ToString() + " and retrieves them into a new " + dr_tb[0].ToString() + " object."); Console.WriteLine("\t\t\t/// </summary>"); Console.WriteLine("\t\t\t/// <param name=\"wherestr\">the string to be used in the WHERE clause. If null or empty, no WHERE clause is generated and all rows are returned.</param>"); Console.WriteLine("\t\t\t/// <param name=\"orderstr\">the string to be used in the ORDER BY clause. If null or empty, no ORDER BY clause is generated and rows are returned in an unspecified, non-deterministic order.</param>"); Console.WriteLine("\t\t\t/// <returns>a new instance of the " + dr_tb[0].ToString() + " class that can be used to read the retrieved data.</returns>"); Console.WriteLine("\t\t\tstatic public " + dr_tb[0].ToString() + " SelectWhere(string wherestr, string orderstr)"); Console.WriteLine("\t\t\t{"); Console.WriteLine("\t\t\t\t" + dr_tb[0].ToString() + " newobj = new " + dr_tb[0].ToString() + "();"); Console.WriteLine("\t\t\t\tSystem.Data.DataSet ds = new System.Data.DataSet();"); Console.WriteLine("\t\t\t\tnew SySal.OperaDb.OperaDbDataAdapter(\"SELECT " + colstring + " FROM " + dr_tb[0] + "\" + ((wherestr == null || wherestr.Trim().Length == 0) ? \"\" : (\" WHERE(\" + wherestr + \")\" + ((orderstr != null && orderstr.Trim() != \"\") ? (\" ORDER BY \" + orderstr): \"\") )), Schema.m_DB).Fill(ds);"); Console.WriteLine("\t\t\t\tnewobj.m_DRC = ds.Tables[0].Rows;"); Console.WriteLine("\t\t\t\tnewobj.m_Row = -1;"); Console.WriteLine("\t\t\t\treturn newobj;"); Console.WriteLine("\t\t\t}"); Console.WriteLine("\t\t\t/// <summary>"); Console.WriteLine("\t\t\t/// the number of rows retrieved."); Console.WriteLine("\t\t\t/// </summary>"); Console.WriteLine("\t\t\tpublic int Count { get { return m_DRC.Count; } }"); Console.WriteLine("\t\t\tinternal int m_Row;"); Console.WriteLine("\t\t\tinternal System.Data.DataRow m_DR;"); Console.WriteLine("\t\t\t/// <summary>"); Console.WriteLine("\t\t\t/// the current row for which field values are exposed."); Console.WriteLine("\t\t\t/// </summary>"); Console.WriteLine("\t\t\tpublic int Row { get { return m_Row; } set { m_Row = value; m_DR = m_DRC[m_Row]; } }"); Console.WriteLine("\t\t\tinternal static bool Prepared = false;"); Console.WriteLine("\t\t\tinternal static SySal.OperaDb.OperaDbCommand cmd = InitCommand();"); Console.WriteLine("\t\t\tprivate static SySal.OperaDb.OperaDbCommand InitCommand()"); Console.WriteLine("\t\t\t{"); Console.WriteLine("\t\t\t\tSySal.OperaDb.OperaDbCommand newcmd = new SySal.OperaDb.OperaDbCommand(\"INSERT INTO " + dr_tb[0].ToString() + " (" + colstring + ") VALUES (" + parstring + ")" + ((AutoIdColumn != null) ? (" RETURNING " + AutoIdColumn + " INTO :o_" + parcount) : "") + "\");"); Console.Write(parslotstring); Console.WriteLine("\t\t\t\treturn newcmd;"); Console.WriteLine("\t\t\t}"); Console.WriteLine("\t\t}"); } System.Data.DataSet ds_pc = new System.Data.DataSet(); new SySal.OperaDb.OperaDbDataAdapter("SELECT OBJECT_NAME FROM ALL_PROCEDURES WHERE OWNER = 'OPERA' AND (OBJECT_NAME LIKE 'PC_%' OR OBJECT_NAME LIKE 'LP_%') ORDER BY OBJECT_NAME ASC", conn, null).Fill(ds_pc); foreach (System.Data.DataRow dr_pc in ds_pc.Tables[0].Rows) { ondbsetprepared += "\t\t\t\tif (" + dr_pc[0].ToString() + ".Prepared) { " + dr_pc[0].ToString() + ".cmd.Connection = null; " + dr_pc[0].ToString() + ".Prepared = false; }\n"; Console.WriteLine("\t\t/// <summary>"); Console.WriteLine("\t\t/// Accesses the " + dr_pc[0].ToString() + " procedure in the DB."); Console.WriteLine("\t\t/// </summary>"); Console.WriteLine("\t\tpublic class " + dr_pc[0].ToString()); Console.WriteLine("\t\t{"); Console.WriteLine("\t\t\tprivate " + dr_pc[0].ToString() + "() {}"); System.Data.DataSet ds_arg = new System.Data.DataSet(); new SySal.OperaDb.OperaDbDataAdapter("SELECT ARGUMENT_NAME, IN_OUT, DATA_TYPE FROM ALL_ARGUMENTS WHERE OWNER = 'OPERA' AND OBJECT_NAME = '" + dr_pc[0].ToString() + "' ORDER BY POSITION ASC", conn, null).Fill(ds_arg); string argstr = ""; string oratype_string = ""; string parslotstring = ""; string callslotstring = ""; string callargstring = ""; string paramretstring = ""; string paramhelpstring = ""; int parcount = 0; foreach (System.Data.DataRow dra in ds_arg.Tables[0].Rows) { parcount++; bool isout = false; bool isinout = false; if (dra[1].ToString() == "OUT") { isout = true; paramretstring += "\t\t\t\tif (" + dra[0].ToString() + " != null) " + dra[0].ToString() + " = cmd.Parameters[" + (parcount - 1).ToString() + "].Value;\n"; paramhelpstring += "\t\t\t/// <param name = \"" + dra[0].ToString() + "\">the value of " + dra[0].ToString() + " obtained from the procedure call as an output. If null, the output is ignored.</param>\n"; } else if (dra[1].ToString() == "IN/OUT") { isinout = true; paramretstring += "\t\t\t\tif (" + dra[0].ToString() + " != null) " + dra[0].ToString() + " = cmd.Parameters[" + (parcount - 1).ToString() + "].Value;\n"; paramhelpstring += "\t\t\t/// <param name = \"" + dra[0].ToString() + "\">the value of " + dra[0].ToString() + " to be used for the procedure call, which can be modified on procedure completion as an output. If null, the input is replaced with a <c>System.DBNull.Value</c> and the output is ignored.</param>\n"; } else if (dra[1].ToString() == "IN") { paramhelpstring += "\t\t\t/// <param name = \"" + dra[0].ToString() + "\">the value of " + dra[0].ToString() + " to be used for the procedure call.</param>\n"; } else { throw new Exception("Unsupported parameter direction " + dra[1].ToString()); } if (dra[2].ToString() == "NUMBER") { oratype_string = "SySal.OperaDb.OperaDbType.Long"; } else if (dra[2].ToString() == "FLOAT") { oratype_string = "SySal.OperaDb.OperaDbType.Double"; } else if (dra[2].ToString() == "CHAR") { oratype_string = "SySal.OperaDb.OperaDbType.String"; } else if (dra[2].ToString() == "VARCHAR2") { oratype_string = "SySal.OperaDb.OperaDbType.String"; } else if (dra[2].ToString() == "DATE" || dra[2].ToString().StartsWith("TIMESTAMP")) { oratype_string = "SySal.OperaDb.OperaDbType.DateTime"; } else if (dra[2].ToString() == "CLOB") { oratype_string = "SySal.OperaDb.OperaDbType.CLOB"; } else { oratype_string = "UNKNOWN-" + dra[2].ToString(); } if (argstr == "") { argstr = (isout ? "ref " : "") + ("object " + dra[0].ToString()); callargstring = ":p_" + parcount.ToString(); } else { argstr += ", " + (isout ? "ref " : "") + ("object " + dra[0].ToString()); callargstring += ",:p_" + parcount.ToString(); } parslotstring += "\t\t\t\tnewcmd.Parameters.Add(\"p_" + parcount + "\", " + oratype_string + ", System.Data.ParameterDirection." + (isout ? "Output" : (isinout ? "InputOutput" : "Input")) + ");\n"; if (!isout) { if (isinout) { callslotstring += "\t\t\t\tif (" + dra[0].ToString() + " == null) cmd.Parameters[" + (parcount - 1) + "].Value = System.DBNull.Value; else cmd.Parameters[" + (parcount - 1) + "].Value = " + dra[0].ToString() + ";\n"; } else { callslotstring += "\t\t\t\tcmd.Parameters[" + (parcount - 1) + "].Value = " + dra[0].ToString() + ";\n"; } } } Console.WriteLine("\t\t\tinternal static bool Prepared = false;"); Console.WriteLine("\t\t\tinternal static SySal.OperaDb.OperaDbCommand cmd = InitCommand();"); Console.WriteLine("\t\t\tprivate static SySal.OperaDb.OperaDbCommand InitCommand()"); Console.WriteLine("\t\t\t{"); Console.WriteLine("\t\t\t\tSySal.OperaDb.OperaDbCommand newcmd = new SySal.OperaDb.OperaDbCommand(\"CALL " + dr_pc[0].ToString() + "(" + callargstring + ")\");"); Console.Write(parslotstring); Console.WriteLine("\t\t\t\treturn newcmd;"); Console.WriteLine("\t\t\t}"); Console.WriteLine("\t\t\t/// <summary>"); Console.WriteLine("\t\t\t/// Calls the procedure."); Console.WriteLine("\t\t\t/// </summary>"); Console.Write(paramhelpstring); Console.WriteLine("\t\t\tpublic static void Call(" + argstr + ")"); Console.WriteLine("\t\t\t{"); Console.WriteLine("\t\t\t\tif (!Prepared) { cmd.Connection = Schema.m_DB; Prepared = true; cmd.Prepare(); };"); Console.Write(callslotstring); Console.WriteLine("\t\t\t\tcmd.ExecuteNonQuery();"); Console.Write(paramretstring); Console.WriteLine("\t\t\t}"); Console.WriteLine("\t\t}"); } Console.WriteLine("\t\tstatic internal SySal.OperaDb.OperaDbConnection m_DB = null;"); Console.WriteLine("\t\t/// <summary>"); Console.WriteLine("\t\t/// The DB connection currently used by the Schema class. Must be set before using any child class."); Console.WriteLine("\t\t/// </summary>"); Console.WriteLine("\t\tstatic public SySal.OperaDb.OperaDbConnection DB"); Console.WriteLine("\t\t{"); Console.WriteLine("\t\t\tget { return m_DB; }"); Console.WriteLine("\t\t\tset"); Console.WriteLine("\t\t\t{"); Console.Write(ondbsetprepared); Console.WriteLine("\t\t\t\tm_DB = value;"); Console.WriteLine("\t\t\t}"); Console.WriteLine("\t\t}"); Console.WriteLine("\t}"); Console.WriteLine("}"); }
void ProcOpRefresh(string selection) { //SySal.OperaDb.OperaDbConnection Conn = null; System.Windows.Forms.Cursor oldcursor = Cursor; Cursor = Cursors.WaitCursor; try { if (Conn == null) { Conn = new SySal.OperaDb.OperaDbConnection(Credentials.DBServer, Credentials.DBUserName, Credentials.DBPassword); Conn.Open(); } ProcOpTree.BeginUpdate(); ProcOpTree.Nodes.Clear(); System.Data.DataSet ds = new System.Data.DataSet(); SySal.OperaDb.OperaDbDataAdapter da = new SySal.OperaDb.OperaDbDataAdapter("SELECT /*+INDEX_RANGE (TB_PROC_OPERATIONS IX_PROC_OPERATIONS_PARENT) */ TB_PROC_OPERATIONS.ID, TB_PROGRAMSETTINGS.DESCRIPTION, TB_PROGRAMSETTINGS.EXECUTABLE, TB_PROC_OPERATIONS.STARTTIME, TB_PROC_OPERATIONS.SUCCESS, TB_PROC_OPERATIONS.ID_EVENTBRICK, TB_PROC_OPERATIONS.ID_PLATE FROM TB_PROC_OPERATIONS INNER JOIN TB_PROGRAMSETTINGS ON (TB_PROC_OPERATIONS.ID_PROGRAMSETTINGS = TB_PROGRAMSETTINGS.ID) WHERE (TB_PROC_OPERATIONS.ID_PARENT_OPERATION IS NULL " + selection + ") ORDER BY STARTTIME DESC", Conn, null); da.Fill(ds); System.Collections.Stack nodestack = new System.Collections.Stack(); foreach (System.Data.DataRow dr in ds.Tables[0].Rows) { int image = 2; if (dr[4].ToString() == "N") { image = 1; } else if (dr[4].ToString() == "Y") { image = 0; } string addinfo = " "; if (dr[5] != System.DBNull.Value) { addinfo += "B#" + dr[5].ToString() + " "; } if (dr[6] != System.DBNull.Value) { addinfo += "P#" + dr[6].ToString() + " "; } TreeNode tn = new TreeNode("#" + dr[0].ToString() + ": " + dr[1].ToString() + addinfo + "(" + dr[2].ToString() + ") - (" + Convert.ToDateTime(dr[3]).ToString("dd/MM/yyyy HH:mm:ss") + ")", image, image); tn.Tag = Convert.ToInt64(dr[0]); ProcOpTree.Nodes.Add(tn); nodestack.Push(tn); } TreeNode nextnode = null; while (nodestack.Count > 0) { nextnode = (TreeNode)nodestack.Pop(); ds = new System.Data.DataSet(); da = new SySal.OperaDb.OperaDbDataAdapter("SELECT /*+INDEX(TB_PROC_OPERATIONS IX_PROC_OPERATIONS_PARENT) */ TB_PROC_OPERATIONS.ID FROM TB_PROC_OPERATIONS WHERE (TB_PROC_OPERATIONS.ID_PARENT_OPERATION = " + nextnode.Tag.ToString() + ") ORDER BY STARTTIME DESC", Conn, null); da.Fill(ds); foreach (System.Data.DataRow dr in ds.Tables[0].Rows) { TreeNode tn = new TreeNode(""); tn.Tag = Convert.ToInt64(dr[0]); nextnode.Nodes.Add(tn); nodestack.Push(tn); } } ProcOpTree.EndUpdate(); //Conn.Close(); } catch (Exception x) { if (Conn != null) { Conn.Close(); Conn = null; } ProcOpTree.EndUpdate(); MessageBox.Show(x.ToString(), "Error refreshing process operation information"); } Cursor = oldcursor; }
private bool Init() { string configfile = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName + ".xml"; System.Xml.Serialization.XmlSerializer xmlc = new System.Xml.Serialization.XmlSerializer(typeof(Configuration)); System.Xml.Serialization.XmlSerializer xmls = new System.Xml.Serialization.XmlSerializer(typeof(NExT.NExTConfiguration)); SySal.OperaDb.OperaDbConnection conn = null; try { TheConfig = (Configuration)xmlc.Deserialize(new System.IO.StringReader(System.IO.File.ReadAllText(configfile))); System.Collections.ArrayList dynsrvparams = new System.Collections.ArrayList(); if (TheConfig.DBServer.Length > 0) { NExT.NExTConfiguration.ServerParameter sp = new SySal.NExT.NExTConfiguration.ServerParameter(); sp.Name = "DBServer"; sp.Value = SySal.OperaDb.OperaDbCredentials.Decode(TheConfig.DBServer); dynsrvparams.Add(sp); sp = new SySal.NExT.NExTConfiguration.ServerParameter(); sp.Name = "DBUsr"; sp.Value = SySal.OperaDb.OperaDbCredentials.Decode(TheConfig.DBUserName); sp = new SySal.NExT.NExTConfiguration.ServerParameter(); sp.Name = "DBPwd"; sp.Value = SySal.OperaDb.OperaDbCredentials.Decode(TheConfig.DBPassword); conn = new SySal.OperaDb.OperaDbConnection( SySal.OperaDb.OperaDbCredentials.Decode(TheConfig.DBServer), SySal.OperaDb.OperaDbCredentials.Decode(TheConfig.DBUserName), SySal.OperaDb.OperaDbCredentials.Decode(TheConfig.DBPassword) ); conn.Open(); IPHostEntry iph = Dns.Resolve(Dns.GetHostName()); string[] idstr = new string[iph.Aliases.Length + iph.AddressList.Length]; idstr[0] = iph.HostName; int i; for (i = 0; i < iph.Aliases.Length; i++) { idstr[i] = iph.Aliases[i]; } for (i = 0; i < iph.AddressList.Length; i++) { idstr[i + iph.Aliases.Length] = iph.AddressList[i].ToString(); } string selstr = "LOWER(TB_MACHINES.ADDRESS)='" + iph.HostName.ToLower() + "'"; foreach (string s in idstr) { selstr += (" OR ADDRESS='" + s + "'"); } DataSet ds = new DataSet(); SySal.OperaDb.OperaDbDataAdapter da = new SySal.OperaDb.OperaDbDataAdapter("SELECT TB_SITES.ID, TB_SITES.NAME, TB_MACHINES.ID, TB_MACHINES.NAME, TB_MACHINES.ADDRESS FROM TB_SITES INNER JOIN TB_MACHINES ON (TB_MACHINES.ID_SITE = TB_SITES.ID AND TB_MACHINES.ISDATAPROCESSINGSERVER = 1 AND (" + selstr + "))", conn, null); da.Fill(ds); if (ds.Tables[0].Rows.Count < 1) { throw new Exception("Can't find myself in OperaDb registered machines. This service is made unavailable."); } long IdSite = SySal.OperaDb.Convert.ToInt64(ds.Tables[0].Rows[0][0]); string SiteName = ds.Tables[0].Rows[0][1].ToString(); long IdMachine = SySal.OperaDb.Convert.ToInt64(ds.Tables[0].Rows[0][2]); string MachineName = ds.Tables[0].Rows[0][3].ToString(); string MachineAddress = ds.Tables[0].Rows[0][4].ToString(); object o = (TheConfig.DBConfigQuery.Length <= 0) ? null : new SySal.OperaDb.OperaDbCommand(TheConfig.DBConfigQuery.Replace("_ID_MACHINE_", IdMachine.ToString()), conn, null).ExecuteScalar(); if (o != null && o != System.DBNull.Value) { TheConfig.Services = (NExT.NExTConfiguration)xmls.Deserialize(new System.IO.StringReader(o.ToString())); } conn.Close(); conn = null; } SySal.NExT.NExTServer.SetupConfiguration(TheConfig.Services, (SySal.NExT.NExTConfiguration.ServerParameter [])dynsrvparams.ToArray(typeof(SySal.NExT.NExTConfiguration.ServerParameter))); WS = new SySal.Web.WebServer(TheConfig.WWWPort, this); } catch (Exception x) { MessageBox.Show("Cannot read/apply server configuration file \"" + configfile + "\".\r\nAttempting to write a sample file.\r\n\r\nError:\r\n" + x.ToString(), "Error reading configuration", MessageBoxButtons.OK, MessageBoxIcon.Error); try { System.IO.StringWriter sw = new System.IO.StringWriter(); xmlc.Serialize(sw, TheConfig); sw.WriteLine(); sw.WriteLine("------------"); sw.WriteLine(); xmls.Serialize(sw, TheConfig.Services); System.IO.File.WriteAllText(configfile, sw.ToString()); } catch (Exception) { } return(false); } finally { if (conn != null) { conn.Close(); } } return(true); }
private void OnBatchList_DblClick(object sender, System.EventArgs e) { try { long selectedid = 0; lock (BatchManagerList) { if (BatchManagerList.SelectedItems.Count != 1) { return; } selectedid = Convert.ToInt64(BatchManagerList.SelectedItems[0].Tag); } if (ScratchDirText.Text.Length == 0) { if (Conn == null) { Conn = new SySal.OperaDb.OperaDbConnection(Credentials.DBServer, Credentials.DBUserName, Credentials.DBPassword); Conn.Open(); } ScratchDirText.Text = new SySal.OperaDb.OperaDbCommand("SELECT VALUE FROM OPERA.LZ_SITEVARS WHERE NAME = 'ScratchDir'", Conn, null).ExecuteScalar().ToString(); } if (!ScratchDirText.Text.EndsWith(@"\")) { ScratchDirText.Text += @"\"; } System.Diagnostics.Process.Start(ScratchDirText.Text + selectedid + "_progress.htm"); } catch (Exception x) { MessageBox.Show("Can't retrieve progress page path because of the following error:\r\n" + x.ToString(), "DB connection error", MessageBoxButtons.OK, MessageBoxIcon.Warning); } return; #if false // TODO: Find a way to deserialize CustomInfo XML elements... SySal.DAQSystem.Drivers.TaskProgressInfo progrinfo = null; long selectedid = 0; lock (BatchManagerList) { if (BatchManagerList.SelectedItems.Count != 1) { return; } selectedid = Convert.ToInt64(BatchManagerList.SelectedItems[0].Tag); try { progrinfo = BMSrv.GetProgressInfo(selectedid); } catch (Exception x) { MessageBox.Show(x.ToString(), x.Message, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } if (progrinfo != null) { ProgressInfo progrdlg = new ProgressInfo(selectedid, progrinfo); progrdlg.ShowDialog(); progrdlg.Dispose(); } #endif }