public Recordset ToRecordSet() { var recordSet = new Recordset(); foreach (var field in _metaData.Fields) { recordSet.Fields.Append(field.Name, field.AdodbDataType, field.DefinedSize, field.Attribute, null); } recordSet.Open(Missing.Value, Missing.Value, CursorTypeEnum.adOpenUnspecified, LockTypeEnum.adLockUnspecified, 0); for (var i = 0; i < _records.Count; i++) { recordSet.AddNew(Missing.Value, Missing.Value); for (var j = 0; j < _metaData.Fields.Length; j++) { recordSet.Fields[j].Value = _records[i][j]; } if (i == _records.Count - 1) recordSet.MoveFirst(); else recordSet.MoveNext(); } return recordSet; }
/// <summary> /// Preenche um ComboBox com os dados de um Recordset. /// </summary> /// <param name="comboBox">O ComboBox a ser preenchido.</param> /// <param name="recordset">O Recordset com os dados.</param> /// <param name="fieldValue">O nome do Field que contém o valor para ComboBox.</param> /// <param name="fieldDescription">O nome do Field que contém a descrição para o ComboBox.</param> public static Recordset AddValuesFromRecordset(this ComboBox comboBox, Recordset recordset, string fieldValue = null, string fieldDescription = null) { if (comboBox == null) throw new ArgumentNullException("comboBox"); if (recordset == null) throw new ArgumentNullException("recordset"); recordset.MoveFirst(); if (fieldDescription == null) { if (fieldValue == null) { var fields = recordset.Fields; if (fields.Count > 1) { fieldValue = fields.Item(0).Name; fieldDescription = fields.Item(1).Name; } else { fieldValue = fieldDescription = fields.Item(0).Name; } } else { var fields = recordset.Fields; if (fields.Count > 1) { fieldDescription = fields.Item(0).Name == fieldValue ? fields.Item(1).Name : fields.Item(0).Name; } else { fieldDescription = fieldValue; } } } var validValues = comboBox.ValidValues; while (!recordset.EoF) { var value = recordset.Fields.Item(fieldValue); var description = recordset.Fields.Item(fieldDescription); validValues.Add(value.Value.ToString(), description.Value.ToString()); recordset.MoveNext(); } return recordset; }
/// <summary> /// Update the Work Point CU Attributes component fiedls. /// </summary> /// <param name="wPfid">New workpoint fid</param> /// <param name="component">Work Point CU Attributes component</param> private void UpdateWorkpointCUAttributes(int wPfid, IGTComponent component) { try { Recordset tempRs = null; int recordCount = 0; tempRs = component.Recordset; if (tempRs != null) { if (m_gTActiveComponent.Recordset != null && m_gTActiveComponent.Recordset.RecordCount > 0) { m_gTActiveComponent.Recordset.MoveFirst(); //if(tempRs.RecordCount > 0 && (m_gTActiveComponent.CNO == 21 || m_gTActiveComponent.CNO == 22)) if (tempRs.RecordCount > 0 && (m_gTActiveComponent.CNO == 21 || m_gTActiveComponent.CNO == 22)) { tempRs.MoveFirst(); while (!tempRs.EOF) { if (tempRs.Fields["ASSOC_FID"].Value != null && !string.IsNullOrEmpty(tempRs.Fields["ASSOC_FID"].Value.ToString())) { int tmpAssocFID = Convert.ToInt32(tempRs.Fields["ASSOC_FID"].Value); int tmpActiveFID = Convert.ToInt32(m_gTActiveComponent.Recordset.Fields["G3E_FID"].Value); short tmpAssocCNO = Convert.ToInt16(tempRs.Fields["UNIT_CNO"].Value); short tmpActiveCNO = Convert.ToInt16(m_gTActiveComponent.Recordset.Fields["G3E_CNO"].Value); //string sWPInstalledWR = string.Empty; //sWPInstalledWR = Convert.ToString(m_gTActiveComponent.Recordset.Fields["WR_ID"].Value); if (tmpAssocFID == tmpActiveFID && tmpAssocCNO == tmpActiveCNO) { tempRs.Delete(); } //if(Convert.ToInt32(tempRs.Fields["ASSOC_FID"].Value) == Convert.ToInt32(m_gTActiveComponent.Recordset.Fields["G3E_FID"].Value)) //{ // tempRs.Delete(); //} } tempRs.MoveNext(); } } int wrNBR = GetWRNumber(); while (!m_gTActiveComponent.Recordset.EOF) { string sInstalledWR = Convert.ToString(m_gTActiveComponent.Recordset.Fields["WR_ID"].Value); string sEditeddWR = Convert.ToString(m_gTActiveComponent.Recordset.Fields["WR_EDITED"].Value); if (!String.IsNullOrEmpty(Convert.ToString(m_gTActiveComponent.Recordset.Fields["CU_C"].Value)) && !String.IsNullOrEmpty(Convert.ToString(m_gTActiveComponent.Recordset.Fields["ACTIVITY_C"].Value))) { if ((sInstalledWR.Equals(m_dataContext.ActiveJob) && (String.IsNullOrEmpty(sEditeddWR))) || (sEditeddWR.Equals(m_dataContext.ActiveJob))) { recordCount = tempRs.RecordCount + 1; tempRs.AddNew(); tempRs.Fields["G3E_FID"].Value = wPfid; tempRs.Fields["G3E_FNO"].Value = 191; tempRs.Fields["G3E_CNO"].Value = component.CNO; // tempRs.Fields["G3E_CID"].Value = recordCount; tempRs.Fields["ACTIVITY_C"].Value = m_gTActiveComponent.Recordset.Fields["ACTIVITY_C"].Value; tempRs.Fields["CIAC_C"].Value = m_gTActiveComponent.Recordset.Fields["CIAC_C"].Value; tempRs.Fields["CU_C"].Value = m_gTActiveComponent.Recordset.Fields["CU_C"].Value; tempRs.Fields["CU_DESC"].Value = m_gTActiveComponent.Recordset.Fields["CU_DESC"].Value; tempRs.Fields["ASSOC_FID"].Value = m_gTActiveComponent.Recordset.Fields["G3E_FID"].Value; tempRs.Fields["ASSOC_FNO"].Value = m_gTActiveComponent.Recordset.Fields["G3E_FNO"].Value; tempRs.Fields["LENGTH_FLAG"].Value = m_gTActiveComponent.Recordset.Fields["LENGTH_FLAG"].Value; tempRs.Fields["MACRO_CU_C"].Value = m_gTActiveComponent.Recordset.Fields["MACRO_CU_C"].Value; tempRs.Fields["PRIME_ACCT_ID"].Value = m_gTActiveComponent.Recordset.Fields["PRIME_ACCT_ID"].Value; tempRs.Fields["QTY_LENGTH_Q"].Value = m_gTActiveComponent.Recordset.Fields["QTY_LENGTH_Q"].Value; tempRs.Fields["UNIT_CID"].Value = m_gTActiveComponent.Recordset.Fields["G3E_CID"].Value; tempRs.Fields["UNIT_CNO"].Value = m_gTActiveComponent.CNO; tempRs.Fields["VINTAGE_YR"].Value = m_gTActiveComponent.Recordset.Fields["VINTAGE_YR"].Value; if (m_WorkpointSequence == 0) { //m_WorkpointSequence = m_gtcommonFunctions.GetWorkManagementSequence(); m_WorkpointSequence = m_gtcommonFunctions.NextWorkMgmtSeq; } else { m_WorkpointSequence = m_WorkpointSequence + 1; } if (wrNBR == 0) { tempRs.Fields["WM_SEQ"].Value = string.Format("{0}{1}", m_dataContext.ActiveJob, m_WorkpointSequence.ToString().PadLeft(4, '0')); } else { tempRs.Fields["WM_SEQ"].Value = string.Format("{0}{1}", wrNBR, m_WorkpointSequence.ToString().PadLeft(4, '0')); } tempRs.Fields["WORK_INSTRUCTION_T"].Value = m_gtcommonFunctions.GetWorkInstruction(Convert.ToString(m_gTActiveComponent.Recordset.Fields["CU_C"].Value)); tempRs.Update(); } } m_gTActiveComponent.Recordset.MoveNext(); } } } } catch { throw; } }
/// <summary> /// Locate the associated Work Point feature (if it exists) for the active WR job. /// </summary> /// <param name="gTCommonComponent">Common component</param> /// <returns></returns> private IGTKeyObjects FindWorkpointsOfFeature(IGTComponent gTCommonComponent) { string strStructureId = null; string sql = ""; Recordset rsWorkpoints = null; int count = 0; IGTKeyObjects workPointKeyObjects = GTClassFactory.Create <IGTKeyObjects>(); try { if (gTCommonComponent != null && gTCommonComponent.Recordset.RecordCount > 0) { gTCommonComponent.Recordset.MoveFirst(); strStructureId = Convert.ToString(gTCommonComponent.Recordset.Fields["STRUCTURE_ID"].Value); } if (!string.IsNullOrEmpty(strStructureId)) { sql = string.Format("select G3E_FID,G3E_FNO from WORKPOINT_N where STRUCTURE_ID = '{0}' and WR_NBR = '{1}'", strStructureId, m_dataContext.ActiveJob); rsWorkpoints = m_dataContext.Execute(sql, out count, (int)ADODB.CommandTypeEnum.adCmdText, null); if (rsWorkpoints != null && rsWorkpoints.RecordCount > 0) { workPointKeyObjects = GTClassFactory.Create <IGTKeyObjects>(); rsWorkpoints.MoveFirst(); while (!rsWorkpoints.EOF) { IGTKeyObject workPoint = m_dataContext.OpenFeature(Convert.ToInt16(rsWorkpoints.Fields["G3E_FNO"].Value), Convert.ToInt32(rsWorkpoints.Fields["G3E_FID"].Value)); workPointKeyObjects.Add(workPoint); rsWorkpoints.MoveNext(); } } else if (m_NewWorkpointFidList.Count > 0) { foreach (KeyValuePair <int, int> wpListFid in m_NewWorkpointFidList) { if (wpListFid.Key == Convert.ToInt32(gTCommonComponent.Recordset.Fields["G3E_FID"].Value)) { IGTKeyObject workPoint = m_dataContext.OpenFeature(191, wpListFid.Value); workPointKeyObjects.Add(workPoint); } } } } else if (m_NewWorkpointFidList.Count > 0) { foreach (KeyValuePair <int, int> wpListFid in m_NewWorkpointFidList) { if (wpListFid.Key == Convert.ToInt32(gTCommonComponent.Recordset.Fields["G3E_FID"].Value)) { IGTKeyObject workPoint = m_dataContext.OpenFeature(191, wpListFid.Value); workPointKeyObjects.Add(workPoint); } } } } catch { throw; } return(workPointKeyObjects); }
/// <summary> /// Get the pole attributes and populates Ticket Attributes class /// </summary> /// <returns>True, if Ticket Attributes are populated successfully. Else returns false</returns> private bool GetPoleAttributes() { string serviceAreaCode = string.Empty; string countyBoundaryId = string.Empty; int nearestServicePointFid = 0; Dictionary <int, double> servicePointsDictionary = null; try { m_TicketAttributes = new TicketAttributes(); IGTKeyObject gTKeyObject = m_DataContext.OpenFeature(110, m_PoleFid); Recordset rs = gTKeyObject.Components.GetComponent(1).Recordset; if (rs != null && rs.RecordCount > 0) { rs.MoveFirst(); m_TicketAttributes.POLE_FID = m_PoleFid; m_TicketAttributes.POLE_NUMBER = Convert.ToString(rs.Fields["STRUCTURE_ID"].Value); m_TicketAttributes.MISCELLANEOUS_ID = m_WrNumber; m_TicketAttributes.LATITUDE = Convert.ToString(rs.Fields["LATITUDE"].Value); m_TicketAttributes.LONGITUDE = Convert.ToString(rs.Fields["LONGITUDE"].Value); } IGTGeometry geometry = gTKeyObject.Components.GetComponent(11002).Geometry; IGTPoint point = GTClassFactory.Create <IGTPoint>(); point.X = geometry.FirstPoint.X; point.Y = geometry.FirstPoint.Y; point.Z = geometry.FirstPoint.Z; customBoundaryQuery boundaryQuery = new customBoundaryQuery(point, 235);// County boundary FNO 235 Recordset resultRs1 = boundaryQuery.PerformPointInPolygon(); if (resultRs1 != null && resultRs1.RecordCount > 0) { IGTKeyObject countyFeature = m_DataContext.OpenFeature(Convert.ToInt16(resultRs1.Fields["G3E_FNO"].Value), Convert.ToInt32(resultRs1.Fields["G3E_FID"].Value)); Recordset boundaryAttributesRs = countyFeature.Components.GetComponent(23501).Recordset; // // County Boundary Attributes if (boundaryAttributesRs != null && boundaryAttributesRs.RecordCount > 0) { boundaryAttributesRs.MoveFirst(); m_TicketAttributes.COUNTY = Convert.ToString(boundaryAttributesRs.Fields["NAME"].Value); if (!string.IsNullOrEmpty(Convert.ToString(boundaryAttributesRs.Fields["ID"].Value))) { countyBoundaryId = Convert.ToString(boundaryAttributesRs.Fields["ID"].Value).Replace("TX", string.Empty).Trim(); } } } if (!string.IsNullOrEmpty(countyBoundaryId)) { int nJunsMemberId = 0; Recordset contactRs = GetRecordSet(string.Format("SELECT NJUNS_MEMBER_ID,CONTACT_NAME,CONTACT_PHONE FROM NJUNS_CONTACTS WHERE COUNTY_N_ID = {0}", countyBoundaryId)); if (contactRs != null && contactRs.RecordCount > 0) { contactRs.MoveFirst(); m_TicketAttributes.CONTACT_NAME = Convert.ToString(contactRs.Fields["CONTACT_NAME"].Value); m_TicketAttributes.CONTACT_PHONE = Convert.ToString(contactRs.Fields["CONTACT_PHONE"].Value); // m_TicketAttributes.PLACE = Convert.ToString(contactRs.Fields["NJUNS_PLACE_NAME"].Value); nJunsMemberId = Convert.ToInt32(contactRs.Fields["NJUNS_MEMBER_ID"].Value); contactRs.Close(); contactRs = null; } contactRs = GetRecordSet(string.Format("SELECT NJUNS_MEMBER FROM NJUNS_MEMBER WHERE NJUNS_MEMBER_ID = {0}", nJunsMemberId)); if (contactRs != null && contactRs.RecordCount > 0) { contactRs.MoveFirst(); m_TicketAttributes.CREATED_MEMBER = Convert.ToString(contactRs.Fields["NJUNS_MEMBER"].Value); m_TicketAttributes.POLE_OWNER = Convert.ToString(contactRs.Fields["NJUNS_MEMBER"].Value); } } customBufferQuery oCustomBufferQuery = new customBufferQuery(point, m_DistanceFromPoleInFeet, 55); //Closest Premise feature within 300 feet of the Pole. Service point FNO 55 servicePointsDictionary = oCustomBufferQuery.PerformBufferQuery(); if (servicePointsDictionary != null && servicePointsDictionary.Count > 0) { servicePointsDictionary.OrderBy(key => key.Value); nearestServicePointFid = servicePointsDictionary.First().Key; IGTKeyObject servicePointFeature = m_DataContext.OpenFeature(55, nearestServicePointFid); Recordset premiseAttributesRs = servicePointFeature.Components.GetComponent(5504).Recordset; // PREMISE_N if (premiseAttributesRs != null && premiseAttributesRs.RecordCount > 0) { premiseAttributesRs.MoveFirst(); m_TicketAttributes.HOUSE_NUMBER = Convert.ToString(premiseAttributesRs.Fields["HOUSE_NBR"].Value); m_TicketAttributes.STREET_NAME = Convert.ToString(premiseAttributesRs.Fields["DIR_LEADING_C"].Value) + " " + Convert.ToString(premiseAttributesRs.Fields["STREET_NM"].Value) + " " + Convert.ToString(premiseAttributesRs.Fields["STREET_TYPE_C"].Value) + " " + Convert.ToString(premiseAttributesRs.Fields["DIR_TRAILING_C"].Value); } } // Set default vaues m_TicketAttributes.TICKET_NUMBER = string.Empty; m_TicketAttributes.TICKET_TYPE = "Transfer"; m_TicketAttributes.TICKET_STATUS = "OPEN"; m_TicketAttributes.STATE = "TX"; m_TicketAttributes.PRIORITY_CODE = "3"; m_TicketAttributes.NJUNS_TICKET_ID = -1; m_TicketAttributes.DAYS_INTERVAL = "30"; m_TicketAttributes.JOB_TYPE = "Transfer"; m_TicketAttributes.NUMBER_OF_POLES = "1"; m_TicketAttributes.REMARKS = string.Empty; return(true); } catch (Exception) { MessageBox.Show("Failed to populate some ticket attributes.", "Custom Create Ticket Error", MessageBoxButtons.OK); return(false); } }
//public RestrictedArea(short Fno, int Fid) //{ // m_fno = Fno; // m_fid = Fid; // m_iGtApplication = GTClassFactory.Create<IGTApplication>(); // m_iGtDataContext = m_iGtApplication.DataContext; //} /// <summary> /// Process Restricted Area validation /// </summary> /// <returns>true if the process is complete without errors, else returns false</returns> public bool Process() { IGTGeometry featureGeometry = null; IGTSpatialService gTSpatialService = null; IGTComponent restrictedAreaAttributes = null; try { foreach (IGTKeyObject feature in m_features) { m_fno = feature.FNO; m_fid = feature.FID; IGTComponents selectedfeatureComponents = m_iGtDataContext.OpenFeature(m_fno, m_fid).Components; CommonFunctions commonFunctions = new CommonFunctions(); short primaryCno = commonFunctions.GetPrimaryGraphicCno(m_fno, true); // If the CNO is zero (not defined), then try the detail CNO if (0 == primaryCno) { primaryCno = commonFunctions.GetPrimaryGraphicCno(m_fno, false); } IGTComponent primaryGraphicComponent = selectedfeatureComponents.GetComponent(primaryCno); if (primaryGraphicComponent != null) { Recordset graphicCompRs = primaryGraphicComponent.Recordset; if (graphicCompRs != null && graphicCompRs.RecordCount > 0) { graphicCompRs.MoveFirst(); // Retrieve the geometry of the primary graphic component featureGeometry = primaryGraphicComponent.Geometry; // Find any Restricted Area features whose area component overlaps the retrieved geometry; if none are found, return with a successful status. gTSpatialService = GTClassFactory.Create <IGTSpatialService>(); gTSpatialService.DataContext = m_iGtDataContext; gTSpatialService.Operator = GTSpatialOperatorConstants.gtsoEntirelyContainedBy; gTSpatialService.FilterGeometry = featureGeometry; Recordset restrictedAreaFeaturesRs = gTSpatialService.GetResultsByFNO(new short[] { RestrictedAreaFno }); if (restrictedAreaFeaturesRs != null && restrictedAreaFeaturesRs.RecordCount > 0) { //Prathyusha //if (restrictedAreaFeaturesRs.RecordCount == 0) //{ // return false; //} restrictedAreaFeaturesRs.MoveFirst(); while (!restrictedAreaFeaturesRs.EOF) { int fid = Convert.ToInt32(restrictedAreaFeaturesRs.Fields["G3E_FID"].Value); restrictedAreaAttributes = m_iGtDataContext.OpenFeature(RestrictedAreaFno, fid).Components.GetComponent(RestrictedAreaAttributesCno); if (!ValidateRestrictedAreaFeature(restrictedAreaAttributes)) { return(false); } restrictedAreaFeaturesRs.MoveNext(); } return(true); } } } } return(true);// Prathyusha: return false; } catch (Exception) { throw; } }
/// <summary> /// This function will take the Recordset(may change how this works) and convert it to an excel document. Then it will send it to the call center via email. /// </summary> public static void ExportData(DataGridView submital) { try { Microsoft.Office.Interop.Excel.Application Excel = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel._Workbook workbook = Excel.Workbooks.Add(Type.Missing); Worksheet worksheet = null; worksheet = workbook.Sheets["Sheet1"]; worksheet = workbook.ActiveSheet; Microsoft.Office.Interop.Excel.Range cutRange; Microsoft.Office.Interop.Excel.Range insertRange; Microsoft.Office.Interop.Excel.Range deleteRange; for (int i = 1; i < submital.Columns.Count; i++) { worksheet.Cells[1, i] = submital.Columns[i].HeaderText; } List <DataGridViewRow> rowsForSubmit = new List <DataGridViewRow>(); System.Data.DataTable test1 = new System.Data.DataTable(); foreach (DataGridViewColumn column in submital.Columns) { test1.Columns.Add(column.Name); } int excelRowIndex = 2; foreach (DataGridViewRow row in submital.Rows) { DataGridViewCheckBoxCell checkbox = row.Cells[0] as DataGridViewCheckBoxCell; bool bChecked = ("" != checkbox.Value.ToString() && null != checkbox && null != checkbox.Value && true == (bool)checkbox.Value); if (bChecked) { for (int i = 1; i < submital.Columns.Count - 2; i++) { row.Cells[2].Value = System.DateTime.Today; if (row.Cells[i].Value != null) { worksheet.Cells[excelRowIndex, i] = row.Cells[i].Value.ToString(); } } excelRowIndex++; } } deleteRange = worksheet.Range["B:B"]; deleteRange.Delete(Microsoft.Office.Interop.Excel.XlDeleteShiftDirection.xlShiftToLeft); deleteRange = worksheet.Range["S:S"]; deleteRange.Delete(Microsoft.Office.Interop.Excel.XlDeleteShiftDirection.xlShiftToLeft); cutRange = worksheet.Range["A:A"]; insertRange = worksheet.Range["R:R"]; insertRange.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftToRight, cutRange.Cut()); string attachmentLocation = "SELECT * FROM SYS_GENERALPARAMETER WHERE PARAM_NAME = ? AND SUBSYSTEM_NAME = ?"; Recordset paramGrabber = gtDataContext.OpenRecordset(attachmentLocation, CursorTypeEnum.adOpenDynamic, LockTypeEnum.adLockOptimistic, -1, "ATTACHMENT_LOCATION", "REQUEST_ESI_LOCATION_CC"); paramGrabber.MoveFirst(); string filename = paramGrabber.Fields["PARAM_VALUE"].Value as string; try { workbook.SaveAs(filename + "\\ESI_Location_Request_" + Environment.UserName + "_" + DateTime.Now.ToString("yyyyMMddHHmmss")); string sendfile = workbook.Path + "\\" + workbook.Name; Excel.Quit(); SubmitEmail(sendfile); } catch { MessageBox.Show(string.Format("Unable to save file to location {0}", filename), "G/Technology"); } } catch (Exception error) { MessageBox.Show("Error in ExportData (" + error.Message + ")", "G/Technology"); } }
/// <summary> /// Inserts named view data into the tables ASSET_HISTORY_VIEW,ASSET_HISTORY_VIEWFILTER,ASSET_HISTORY_VIEWSORT /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnSave_Click(object sender, EventArgs e) { int viewId = 0; Recordset rs = null; try { string sql = ""; if (!string.IsNullOrEmpty(txtViewname.Text)) { sql = "select max(view_id)+1 from ASSET_HISTORY_VIEW"; rs = m_gTDataContext.OpenRecordset(sql, ADODB.CursorTypeEnum.adOpenDynamic, ADODB.LockTypeEnum.adLockReadOnly, (int)ADODB.CommandTypeEnum.adCmdText, null); if (rs != null && rs.RecordCount > 0) { rs.MoveFirst(); if (string.IsNullOrEmpty(Convert.ToString(rs.Fields[0].Value))) { viewId = 1; } else { viewId = Convert.ToInt32(rs.Fields[0].Value); } } rs = null; sql = "select count(*) from ASSET_HISTORY_VIEW where view_nm = :1"; rs = m_gTDataContext.OpenRecordset(sql, ADODB.CursorTypeEnum.adOpenDynamic, ADODB.LockTypeEnum.adLockReadOnly, (int)ADODB.CommandTypeEnum.adCmdText, new object[] { txtViewname.Text }); if (rs != null && rs.RecordCount > 0) { rs.MoveFirst(); if (Convert.ToInt32(rs.Fields[0].Value) > 0) { if (MessageBox.Show(GTClassFactory.Create <IGTApplication>().ApplicationWindow, "View name already exist in database. Do you want to replace it?", "G/Technology", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { sql = null; sql = string.Format("DELETE FROM ASSET_HISTORY_VIEWFILTER where VIEW_ID = (SELECT VIEW_ID FROM ASSET_HISTORY_VIEW WHERE VIEW_NM='{0}')", txtViewname.Text); ExecuteCommand(sql); sql = string.Format("DELETE FROM ASSET_HISTORY_VIEWSORT where VIEW_ID = (SELECT VIEW_ID FROM ASSET_HISTORY_VIEW WHERE VIEW_NM='{0}')", txtViewname.Text); ExecuteCommand(sql); sql = string.Format("DELETE FROM ASSET_HISTORY_VIEW where VIEW_NM = '{0}'", txtViewname.Text); ExecuteCommand(sql); sql = string.Format("commit", txtViewname.Text); ExecuteCommand(sql); sql = SaveViewWithGivenName(viewId); this.DialogResult = DialogResult.OK; } else { this.DialogResult = DialogResult.None; } } else { sql = SaveViewWithGivenName(viewId); this.DialogResult = DialogResult.OK; } } } else { MessageBox.Show("View name should not be empty.", "G/Techonology", MessageBoxButtons.OK, MessageBoxIcon.Information); this.DialogResult = DialogResult.None; } } catch (Exception ex) { MessageBox.Show("Error during execution of Review Asset History custom command." + Environment.NewLine + ex.Message, "G/Techonology", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (rs != null) { rs.Close(); rs = null; } } }
virtual public ADODB.Recordset ExecuteSql(string sql) { Recordset oRS = new Recordset(); OleDbConnection cn = null; OleDbDataReader reader = null; try { cn = new OleDbConnection(dbRoot.ConnectionString); cn.Open(); try { cn.ChangeDatabase(this.Name); } catch { } // some databases don't have the concept of catalogs. Catch this and throw it out OleDbCommand command = new OleDbCommand(sql, cn); command.CommandType = CommandType.Text; reader = command.ExecuteReader(); DataTable schema; string dataType, fieldname; int length; bool firstTime = true; while (reader.Read()) { if (firstTime) { schema = reader.GetSchemaTable(); foreach (DataRow row in schema.Rows) { fieldname = row["ColumnName"].ToString(); dataType = row["DataType"].ToString(); length = Convert.ToInt32(row["ColumnSize"]); oRS.Fields.Append(fieldname, GetADOType(dataType), length, FieldAttributeEnum.adFldIsNullable, System.Reflection.Missing.Value); } oRS.Open(System.Reflection.Missing.Value, System.Reflection.Missing.Value, CursorTypeEnum.adOpenStatic, LockTypeEnum.adLockOptimistic, 1); firstTime = false; } oRS.AddNew(System.Reflection.Missing.Value, System.Reflection.Missing.Value); for(int i = 0; i < reader.FieldCount; i++) { if (reader[i] is System.Guid) { oRS.Fields[i].Value = "{" + reader[i].ToString() + "}"; } else { oRS.Fields[i].Value = reader[i]; } } } cn.Close(); //Move to the first record if (!firstTime) { oRS.MoveFirst(); } else { oRS = null; } } catch (Exception ex) { if ((reader != null) && (!reader.IsClosed)) { reader.Close(); reader = null; } if ((cn != null) && (cn.State == ConnectionState.Open)) { cn.Close(); cn = null; } throw ex; } return oRS; }
/// <summary> /// Validate /// </summary> /// <param name="ErrorPriorityArray"></param> /// <param name="ErrorMessageArray"></param> public void Validate(out string[] ErrorPriorityArray, out string[] ErrorMessageArray) { GTValidationLogger gTValidationLogger = null; IGTComponent comp = Components[ComponentName]; int FID = 0; string fieldValue = string.Empty; if (comp != null && comp.Recordset != null && comp.Recordset.RecordCount > 0) { FID = int.Parse(comp.Recordset.Fields["G3E_FID"].Value.ToString()); fieldValue = Convert.ToString(comp.Recordset.Fields[FieldName].Value); } if (new gtLogHelper().CheckIfLoggingIsEnabled()) { LogEntries logEntries = new LogEntries { ActiveComponentName = ComponentName, ActiveFID = FID, ActiveFieldName = FieldName, ActiveFieldValue = fieldValue, JobID = DataContext.ActiveJob, RelatedComponentName = "N/A", RelatedFID = 0, RelatedFieldName = "N/A", RelatedFieldValue = "N/A", ValidationInterfaceName = "Phase Agreement", ValidationInterfaceType = "FI" }; gTValidationLogger = new GTValidationLogger(logEntries); gTValidationLogger.LogEntry("TIMING", "START", "Phase Agreement Entry", "N/A", ""); } ErrorPriorityArray = null; ErrorMessageArray = null; IGTKeyObject affectedFeatureKeyObject = GTClassFactory.Create <IGTKeyObject>(); IGTKeyObjects relatedFeaturesKeyObjects = GTClassFactory.Create <IGTKeyObjects>(); List <char> downstreamPhaseList = new List <char>(); List <char> upstreamPhaseList = new List <char>(); List <char> insidePhaseList = new List <char>(); List <char> parallelPhaseList = new List <char>(); List <char> outsidePhaseList = new List <char>(); List <string> errorMessage = new List <string>(); List <string> errorPriority = new List <string>(); GTClassFactory.Create <IGTApplication>().SetStatusBarText(GTStatusPanelConstants.gtaspcMessage, "Phase Agreement FI"); try { if (!CheckAffectedFeatureIsSecondary()) // Check for affected feature is secondary or not { if (m_affectedConnectivityRs.RecordCount > 0) { m_affectedConnectivityRs.MoveFirst(); m_aNode1 = Convert.ToInt32(m_affectedConnectivityRs.Fields[ATTRIB_NODE1].Value == DBNull.Value ? 0.0 : m_affectedConnectivityRs.Fields[ATTRIB_NODE1].Value); m_aNode2 = Convert.ToInt32(m_affectedConnectivityRs.Fields[ATTRIB_NODE2].Value == DBNull.Value ? 0.0 : m_affectedConnectivityRs.Fields[ATTRIB_NODE2].Value); if (m_aNode1 != 0 || m_aNode2 != 0) { m_activeFeaturePhase = Convert.ToString(m_affectedConnectivityRs.Fields[ATTRIB_PHASE].Value); affectedFeatureKeyObject = DataContext.OpenFeature(Convert.ToInt16(Components[ComponentName].Recordset.Fields[ATTRIB_FNO].Value), Convert.ToInt32(Components[ComponentName].Recordset.Fields[ATTRIB_FID].Value)); // Gets the related features of affected feature. relatedFeaturesKeyObjects = GetRelatedFeatures(affectedFeatureKeyObject, m_cRNO); GetNumberOfNodes(affectedFeatureKeyObject); if (m_numberofNodes == 2) { ConnectivityFactory connecFactory = new ConnectivityHelperFactory(); //Collects phase list of parallel features of affected feature. GetParallelFeaturesPhaseList(affectedFeatureKeyObject, connecFactory, ref parallelPhaseList); //Collects phase list of Upstream features of affected feature. GetUpstreamFeaturesPhaseList(affectedFeatureKeyObject, connecFactory, ref upstreamPhaseList); //Collects phase list of DownStream features of affected feature. GetDownStreamFeaturesPhaseList(affectedFeatureKeyObject, connecFactory, ref downstreamPhaseList); //Collects phase list of Inside features of affected feature. GetInsideFeaturesPhaseList(affectedFeatureKeyObject, connecFactory, ref insidePhaseList); //Collects phase list of Outside features of affected feature. GetOutsideFeaturesPhaseList(affectedFeatureKeyObject, connecFactory, ref outsidePhaseList); } //Validates the Phase values based on different conditions ValidatePhase(outsidePhaseList, insidePhaseList, parallelPhaseList, upstreamPhaseList, downstreamPhaseList, relatedFeaturesKeyObjects, affectedFeatureKeyObject.FNO, ref errorPriority, ref errorMessage); if (errorMessage.Count > 0) { ErrorPriorityArray = errorPriority.ToArray(); ErrorMessageArray = errorMessage.ToArray(); } } } } if (gTValidationLogger != null) { gTValidationLogger.LogEntry("TIMING", "END", "Phase Agreement Exit", "N/A", ""); } } catch (Exception ex) { throw new Exception("Error during Phase agreement Validation" + ex.Message); } finally { downstreamPhaseList = null; upstreamPhaseList = null; insidePhaseList = null; outsidePhaseList = null; } }
public void Execute() { GTClassFactory.Create <IGTApplication>().SetStatusBarText(GTStatusPanelConstants.gtaspcMessage, "Aggregate Phase FI"); IGTComponent activeComponent = Components[ComponentName]; short cNo = 0; string field = string.Empty; string alphabetizedPhase = string.Empty; string alphabetizedOperatedPhase = string.Empty; try { if (activeComponent != null) { //Get the active feature current CID int aCID = Convert.ToInt32(activeComponent.Recordset.Fields["G3E_CID"].Value); if ((aCID != 0)) { int anoPhase = Convert.ToInt32(m_Arguments.GetArgument(0)); int anoPhaseQty = Convert.ToInt32(m_Arguments.GetArgument(1)); int anoPhaseOperated = Convert.ToInt32(m_Arguments.GetArgument(2)); Tuple <string, string> phaseValues = GetAggregatePhaseValue(); Recordset phaseRs = DataContext.MetadataRecordset("G3E_ATTRIBUTEINFO_OPTABLE", "G3E_ANO = " + anoPhase);// GetRecordSet(sqlString); // Update PHASE if (phaseRs.RecordCount > 0) { phaseRs.MoveFirst(); cNo = Convert.ToInt16(phaseRs.Fields["G3E_CNO"].Value); field = Convert.ToString(phaseRs.Fields["G3E_FIELD"].Value); IGTComponent connectivityComponent = Components.GetComponent(cNo); connectivityComponent.Recordset.MoveFirst(); alphabetizedPhase = GetAlphabetizedPhase(phaseValues.Item1); connectivityComponent.Recordset.Fields[field].Value = alphabetizedPhase; } Recordset operatedPhaseRs = DataContext.MetadataRecordset("G3E_ATTRIBUTEINFO_OPTABLE", "G3E_ANO = " + anoPhaseOperated); // Update As-Operated Phase if (operatedPhaseRs.RecordCount > 0) { operatedPhaseRs.MoveFirst(); cNo = Convert.ToInt16(operatedPhaseRs.Fields["G3E_CNO"].Value); field = Convert.ToString(operatedPhaseRs.Fields["G3E_FIELD"].Value); IGTComponent connectivityComponent = Components.GetComponent(cNo); connectivityComponent.Recordset.MoveFirst(); alphabetizedOperatedPhase = GetAlphabetizedPhase(phaseValues.Item2); connectivityComponent.Recordset.Fields[field].Value = alphabetizedOperatedPhase; } // Update PHASE QUANTITY if (anoPhaseQty != 0) { Recordset phaseQuantityRs = DataContext.MetadataRecordset("G3E_ATTRIBUTEINFO_OPTABLE", "G3E_ANO = " + anoPhaseQty); if (phaseQuantityRs.RecordCount > 0) { phaseQuantityRs.MoveFirst(); cNo = Convert.ToInt16(phaseQuantityRs.Fields["G3E_CNO"].Value); field = Convert.ToString(phaseQuantityRs.Fields["G3E_FIELD"].Value); IGTComponent primaryAttributeComponent = Components.GetComponent(cNo); primaryAttributeComponent.Recordset.MoveFirst(); primaryAttributeComponent.Recordset.Fields[field].Value = GetDistinctPhaseCount(alphabetizedPhase); } } } } } catch (Exception ex) { MessageBox.Show("Error during Phase Aggregation FI execution. " + ex.Message, "G/Technology"); } }
/// <summary> /// Method to validate each record in spreadsheet before the information in that record is applied to the GIS. /// </summary> /// <param name="p_dataTable">Worksheet data Datatable</param> /// <returns></returns> public DataTable ValidateSpreadsheetRecord(DataTable p_dataTable) { DataAccess dataAccess = new DataAccess(m_oGTApplication.DataContext); DataRow dataRow = null; try { for (int i = 0; i < p_dataTable.Rows.Count; i++) { // Each instance of an error needs to call this before executing the continue // as well as at the end of each iteration (for successful transactions). void EvaluateErrors() { dataRow = ProcessingImport(p_dataTable.Rows[i]); UpdateDataTable(ref p_dataTable, i, dataRow); m_nbrDataBaseChanges = true; } m_oGTApplication.SetStatusBarText(GTStatusPanelConstants.gtaspcMessage, "Street Light Import Tool : Validating Spreadsheet Record"); p_dataTable.Rows[i]["TRANSACTION DATE"] = DateTime.Now; if (Convert.ToString(p_dataTable.Rows[i]["TRANSACTION STATUS"]).ToUpper() != "SUCCESS" && Convert.ToString(p_dataTable.Rows[i]["TRANSACTION STATUS"]).ToUpper() != "WARNING") { if (String.IsNullOrEmpty(Convert.ToString(p_dataTable.Rows[i]["TRANSACTION TYPE"])) || String.IsNullOrEmpty(Convert.ToString(p_dataTable.Rows[i]["ESI LOCATION"])) || String.IsNullOrEmpty(Convert.ToString(p_dataTable.Rows[i]["LAMP TYPE"])) || String.IsNullOrEmpty(Convert.ToString(p_dataTable.Rows[i]["WATTAGE"])) || String.IsNullOrEmpty(Convert.ToString(p_dataTable.Rows[i]["LUMINAIRE STYLE"])) || String.IsNullOrEmpty(Convert.ToString(p_dataTable.Rows[i]["ONCOR STRUCTURE"])) || String.IsNullOrEmpty(Convert.ToString(p_dataTable.Rows[i]["LOCATION DESCRIPTION"]))) { p_dataTable.Rows[i]["TRANSACTION STATUS"] = "ERROR"; p_dataTable.Rows[i]["TRANSACTION COMMENT"] = "One or more required fields do not contain data."; EvaluateErrors(); continue; } if (!(Convert.ToString(p_dataTable.Rows[i]["TRANSACTION TYPE"]).ToUpper() == "ADD" || Convert.ToString(p_dataTable.Rows[i]["TRANSACTION TYPE"]).ToUpper() == "REMOVE")) { p_dataTable.Rows[i]["TRANSACTION STATUS"] = "ERROR"; p_dataTable.Rows[i]["TRANSACTION COMMENT"] = "Invalid Transaction Type"; EvaluateErrors(); continue; } string[] args = new string[] { Convert.ToString(p_dataTable.Rows[i]["ESI LOCATION"]) }; Recordset accountRS = dataAccess.GetRecordset("select * from STLT_ACCOUNT where ESI_LOCATION=?", args); if (accountRS != null && accountRS.RecordCount == 0) { p_dataTable.Rows[i]["TRANSACTION STATUS"] = "ERROR"; p_dataTable.Rows[i]["TRANSACTION COMMENT"] = "ESI Location does not exist in the STLT_ACCOUNT table."; EvaluateErrors(); continue; } accountRS.MoveFirst(); if (Convert.ToString(p_dataTable.Rows[i]["ESI LOCATION"]) != Convert.ToString(accountRS.Fields["ESI_LOCATION"].Value) || Convert.ToString(p_dataTable.Rows[i]["LAMP TYPE"]) != Convert.ToString(accountRS.Fields["LAMP_TYPE"].Value) || (Convert.ToString(p_dataTable.Rows[i]["WATTAGE"]) != Convert.ToString(accountRS.Fields["WATTAGE"].Value)) || Convert.ToString(p_dataTable.Rows[i]["LUMINAIRE STYLE"]) != Convert.ToString(accountRS.Fields["LUMINARE_STYLE"].Value)) { p_dataTable.Rows[i]["TRANSACTION STATUS"] = "ERROR"; p_dataTable.Rows[i]["TRANSACTION COMMENT"] = "Account not found that matches ESI LOCATION, LAMP TYPE, WATTAGE, and LUMINAIRE STYLE."; EvaluateErrors(); continue; } string strCUCode = dataAccess.GetCustomerOwnedCUCode(Convert.ToString(p_dataTable.Rows[i]["LAMP TYPE"]), Convert.ToString(p_dataTable.Rows[i]["LUMINAIRE STYLE"]), Convert.ToString(p_dataTable.Rows[i]["WATTAGE"])); if (string.IsNullOrEmpty(strCUCode)) { p_dataTable.Rows[i]["TRANSACTION STATUS"] = "ERROR"; p_dataTable.Rows[i]["TRANSACTION COMMENT"] = "Distinct customer-owned CU not found that matches LAMP TYPE, WATTAGE, and LUMINAIRE STYLE"; EvaluateErrors(); continue; } if (!String.IsNullOrEmpty(Convert.ToString(p_dataTable.Rows[i]["STREETLIGHT ID"]))) { Recordset streetLightAttributeRS = dataAccess.GetRecordset(String.Format("select * from STREETLIGHT_N WHERE ACCOUNT_ID='{0}' and CO_IDENTIFIER='{1}'", Convert.ToString(p_dataTable.Rows[i]["ESI LOCATION"]), Convert.ToString(p_dataTable.Rows[i]["STREETLIGHT ID"]))); if (Convert.ToString(p_dataTable.Rows[i]["TRANSACTION TYPE"]).ToUpper() == "ADD") { if (streetLightAttributeRS != null && streetLightAttributeRS.RecordCount > 0) { p_dataTable.Rows[i]["TRANSACTION STATUS"] = "ERROR"; p_dataTable.Rows[i]["TRANSACTION COMMENT"] = "Duplicate Street Light exists with this ESI Location and Street Light ID."; EvaluateErrors(); continue; } } if (Convert.ToString(p_dataTable.Rows[i]["TRANSACTION TYPE"]).ToUpper() == "REMOVE") { if (streetLightAttributeRS != null && streetLightAttributeRS.RecordCount == 0) { p_dataTable.Rows[i]["TRANSACTION STATUS"] = "ERROR"; p_dataTable.Rows[i]["TRANSACTION COMMENT"] = "No Street Light found for this ESI Location and Street Light ID."; EvaluateErrors(); continue; } else if (streetLightAttributeRS.RecordCount > 1) { p_dataTable.Rows[i]["TRANSACTION STATUS"] = "ERROR"; p_dataTable.Rows[i]["TRANSACTION COMMENT"] = "Multiple Street Lights were found for this ESI Location and Street Light ID."; EvaluateErrors(); continue; } } } if (!(Convert.ToString(p_dataTable.Rows[i]["ONCOR STRUCTURE"]) == 'Y'.ToString() || Convert.ToString(p_dataTable.Rows[i]["ONCOR STRUCTURE"]) == 'N'.ToString())) { p_dataTable.Rows[i]["TRANSACTION STATUS"] = "ERROR"; p_dataTable.Rows[i]["TRANSACTION COMMENT"] = "ONCOR STRUCTURE must be Y or N."; EvaluateErrors(); continue; } if (String.IsNullOrEmpty(Convert.ToString(p_dataTable.Rows[i]["ONCOR STRUCTURE ID"])) && String.IsNullOrEmpty(Convert.ToString(p_dataTable.Rows[i]["GPS X"])) && String.IsNullOrEmpty(Convert.ToString(p_dataTable.Rows[i]["GPS Y"]))) { if (dataAccess.GetBoundaryFID(Convert.ToString(p_dataTable.Rows[i]["ESI LOCATION"])) == 0) { p_dataTable.Rows[i]["TRANSACTION STATUS"] = "ERROR"; p_dataTable.Rows[i]["TRANSACTION COMMENT"] = "No STRUCTURE ID, GPS given. Account does not have a Boundary or Structure defined."; } EvaluateErrors(); continue; } Recordset commonRS = dataAccess.GetRecordset(String.Format("select * from COMMON_N WHERE STRUCTURE_ID='{0}'", Convert.ToString(p_dataTable.Rows[i]["ONCOR STRUCTURE ID"]))); if (Convert.ToString(p_dataTable.Rows[i]["ONCOR STRUCTURE"]) == 'Y'.ToString()) { if (commonRS != null && commonRS.RecordCount == 0) { p_dataTable.Rows[i]["TRANSACTION STATUS"] = "ERROR"; p_dataTable.Rows[i]["TRANSACTION COMMENT"] = "ONCOR STRUCTURE is Y but no Structure found for STRUCTURE ID."; EvaluateErrors(); continue; } else if (commonRS.RecordCount > 1) { p_dataTable.Rows[i]["TRANSACTION STATUS"] = "ERROR"; p_dataTable.Rows[i]["TRANSACTION COMMENT"] = "ONCOR STRUCTURE is Y and multiple Structures found for STRUCTURE ID."; EvaluateErrors(); continue; } } if (Convert.ToString(p_dataTable.Rows[i]["ONCOR STRUCTURE"]) == 'N'.ToString()) { if (commonRS != null && commonRS.RecordCount > 0) { p_dataTable.Rows[i]["TRANSACTION STATUS"] = "ERROR"; p_dataTable.Rows[i]["TRANSACTION COMMENT"] = "STRUCTURE ID has a value but ONCOR STRUCTURE flag is set to N."; EvaluateErrors(); continue; } } if (!String.IsNullOrEmpty(Convert.ToString(p_dataTable.Rows[i]["GPS X"])) && !String.IsNullOrEmpty(Convert.ToString(p_dataTable.Rows[i]["GPS Y"])) && !CheckGPSCoordinates(Convert.ToString(p_dataTable.Rows[i]["GPS X"]), Convert.ToString(p_dataTable.Rows[i]["GPS Y"]))) { p_dataTable.Rows[i]["TRANSACTION STATUS"] = "ERROR"; p_dataTable.Rows[i]["TRANSACTION COMMENT"] = "GPS Coordinates are either malformed or outside of the expected range of 93.0W – 107.0W and 25.0N – 37.0N."; EvaluateErrors(); continue; } } // For the cases where no errors were encountered, // the SUCCESSFUL transactions also need to be counted. EvaluateErrors(); } } catch { throw; } finally { dataAccess = null; } return(p_dataTable); }
public void Activate() { string sql = "SELECT G3E_FID FROM WORKPOINT_N WHERE WR_NBR=:1 AND G3E_FNO=191"; Recordset rsValidate = null; int jFid = 0; short jFno = 0; IGTKeyObject jKeyObject = null; IGTJobManagementService oJobManagement = GTClassFactory.Create <IGTJobManagementService>(); oJobManagement.DataContext = m_ogtApplication.DataContext; try { if (ValidateCommand()) { ADODB.Recordset rsPendingEdits = oJobManagement.FindPendingEdits(); if (rsPendingEdits != null && rsPendingEdits.RecordCount > 0) { oJobManagement.DiscardJob(); //ALM 1321 - Automatically discard job at the start and assume that there are no unposted data m_oGTTransactionManager.RefreshDatabaseChanges(); m_ogtApplication.RefreshWindows(); } rsValidate = m_ogtApplication.DataContext.OpenRecordset(sql, ADODB.CursorTypeEnum.adOpenDynamic, ADODB.LockTypeEnum.adLockReadOnly, (int)ADODB.CommandTypeEnum.adCmdText, new object[] { m_ogtApplication.DataContext.ActiveJob }); if (rsValidate == null || rsValidate.RecordCount == 0) { return; } m_oGTTransactionManager.Begin("Revert Job"); commonRevertAPI rFeature = new commonRevertAPI(m_ogtApplication); rsValidate.MoveFirst(); while (!rsValidate.EOF) { jFno = 191; jFid = Convert.ToInt32(rsValidate.Fields["G3E_FID"].Value); jKeyObject = m_ogtApplication.DataContext.OpenFeature(jFno, jFid); rFeature.m_FromJob = "JOB"; rFeature.RevertWPFeature(jKeyObject); rsValidate.MoveNext(); } if (rFeature.m_uProcessedCUs) { MessageBox.Show("Check remaining Work Points to make manual corrections.", "G/Technology", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1); } if (m_oGTTransactionManager.TransactionInProgress) { m_oGTTransactionManager.Commit(); m_oGTTransactionManager.RefreshDatabaseChanges(); } } } catch (Exception ex) { MessageBox.Show(ex.Message, "G/Technology", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); m_oGTTransactionManager.Rollback(); } finally { if (rsValidate != null) { if (rsValidate.State == 1) { rsValidate.Close(); rsValidate.ActiveConnection = null; } rsValidate = null; } } }
virtual public ADODB.Recordset ExecuteSql(string sql) { Recordset oRS = new Recordset(); OleDbConnection cn = null; OleDbDataReader reader = null; try { cn = new OleDbConnection(dbRoot.ConnectionString); cn.Open(); try { cn.ChangeDatabase(this.Name); } catch { } // some databases don't have the concept of catalogs. Catch this and throw it out OleDbCommand command = new OleDbCommand(sql, cn); command.CommandType = CommandType.Text; reader = command.ExecuteReader(); DataTable schema; string dataType, fieldname; int length; bool firstTime = true; while (reader.Read()) { if (firstTime) { schema = reader.GetSchemaTable(); foreach (DataRow row in schema.Rows) { fieldname = row["ColumnName"].ToString(); dataType = row["DataType"].ToString(); length = Convert.ToInt32(row["ColumnSize"]); oRS.Fields.Append(fieldname, GetADOType(dataType), length, FieldAttributeEnum.adFldIsNullable, System.Reflection.Missing.Value); } oRS.Open(System.Reflection.Missing.Value, System.Reflection.Missing.Value, CursorTypeEnum.adOpenStatic, LockTypeEnum.adLockOptimistic, 1); firstTime = false; } oRS.AddNew(System.Reflection.Missing.Value, System.Reflection.Missing.Value); for (int i = 0; i < reader.FieldCount; i++) { if (reader[i] is System.Guid) { oRS.Fields[i].Value = "{" + reader[i].ToString() + "}"; } else { oRS.Fields[i].Value = reader[i]; } } } cn.Close(); //Move to the first record if (!firstTime) { oRS.MoveFirst(); } else { oRS = null; } } catch (Exception ex) { if ((reader != null) && (!reader.IsClosed)) { reader.Close(); reader = null; } if ((cn != null) && (cn.State == ConnectionState.Open)) { cn.Close(); cn = null; } throw ex; } return(oRS); }
/// <summary> /// Method to set feature state of the virtual point to match the associated feature. /// </summary> private void SetFieldsOfVirtualPoints(String p_associatedFeatureState, IGTComponent p_gTAssociateComponent) { string strActiveFeatureState = ""; string strActiveFeatureNormalState = ""; string strActiveFeatureOperaState = ""; List <string> installedFs = new List <string> { "PPI", "ABI" }; List <string> removedFs = new List <string> { "PPR", "ABR", "PPA", "ABA" }; try { Recordset vpCommonRs = m_gComps["COMMON_N"].Recordset; if (Convert.ToInt16(vpCommonRs.Fields["G3E_FNO"].Value) == 40 || Convert.ToInt16(vpCommonRs.Fields["G3E_FNO"].Value) == 80) { if (p_associatedFeatureState == "PPI") { strActiveFeatureState = "PPR"; strActiveFeatureNormalState = "OPEN"; strActiveFeatureOperaState = "CLOSED"; } else if (p_associatedFeatureState == "ABI") { strActiveFeatureState = "ABR"; strActiveFeatureNormalState = "OPEN"; strActiveFeatureOperaState = "CLOSED"; } else if (p_associatedFeatureState == "PPR") { strActiveFeatureState = "PPI"; strActiveFeatureNormalState = "CLOSED"; strActiveFeatureOperaState = "OPEN"; } else if (p_associatedFeatureState == "ABR") { strActiveFeatureState = "ABI"; strActiveFeatureNormalState = "CLOSED"; strActiveFeatureOperaState = "OPEN"; } } else if (Convert.ToInt16(vpCommonRs.Fields["G3E_FNO"].Value) == 6 || Convert.ToInt16(vpCommonRs.Fields["G3E_FNO"].Value) == 82) { if (p_associatedFeatureState == "PPI" || p_associatedFeatureState == "ABI") { strActiveFeatureState = p_associatedFeatureState; strActiveFeatureNormalState = "CLOSED"; strActiveFeatureOperaState = "OPEN"; } } if (vpCommonRs != null && vpCommonRs.RecordCount > 0) { if (!(vpCommonRs.EOF && vpCommonRs.BOF)) { vpCommonRs.MoveFirst(); vpCommonRs.Fields["FEATURE_STATE_C"].Value = strActiveFeatureState; vpCommonRs.Update(); m_gtFeatureState = Convert.ToString(vpCommonRs.Fields["FEATURE_STATE_C"].Value); } } Recordset vpConnecRs = m_gComps["CONNECTIVITY_N"].Recordset; Recordset rsAssociatedConn = p_gTAssociateComponent.Recordset; if (vpConnecRs != null && vpConnecRs.RecordCount > 0) { if (!(vpConnecRs.EOF && vpConnecRs.BOF)) { vpConnecRs.MoveFirst(); if (rsAssociatedConn != null && rsAssociatedConn.RecordCount > 0) { if (!(rsAssociatedConn.EOF && rsAssociatedConn.BOF)) { rsAssociatedConn.MoveFirst(); vpConnecRs.Fields["STATUS_NORMAL_C"].Value = strActiveFeatureNormalState; vpConnecRs.Fields["STATUS_OPERATED_C"].Value = strActiveFeatureOperaState; vpConnecRs.Fields["FEEDER_1_ID"].Value = rsAssociatedConn.Fields["FEEDER_1_ID"].Value; vpConnecRs.Fields["FEEDER_NBR"].Value = rsAssociatedConn.Fields["FEEDER_NBR"].Value; vpConnecRs.Fields["FEEDER_TYPE_C"].Value = rsAssociatedConn.Fields["FEEDER_TYPE_C"].Value; vpConnecRs.Fields["SSTA_C"].Value = rsAssociatedConn.Fields["SSTA_C"].Value; vpConnecRs.Fields["VOLT_1_Q"].Value = rsAssociatedConn.Fields["VOLT_1_Q"].Value; vpConnecRs.Fields["VOLT_2_Q"].Value = rsAssociatedConn.Fields["VOLT_2_Q"].Value; vpConnecRs.Fields["PROTECTIVE_DEVICE_FID"].Value = rsAssociatedConn.Fields["PROTECTIVE_DEVICE_FID"].Value; vpConnecRs.Fields["UPSTREAM_NODE"].Value = rsAssociatedConn.Fields["UPSTREAM_NODE"].Value; vpConnecRs.Fields["UPSTREAM_PROTDEV_Q"].Value = rsAssociatedConn.Fields["UPSTREAM_PROTDEV_Q"].Value; } } } } } catch { throw; } }
public void InsertQuery() { try { this.mDataGridView.Rows.Clear(); this.mDataGridView.Columns.Clear(); Layer3Ds m_layer = mSceneControl.Scene.Layers; foreach (Layer3D mlayer in m_layer) { if (mlayer.Selection != null) { mlayer.Selection.Clear(); } } QueryParameter para = new QueryParameter(); para.HasGeometry = true; para.SpatialQueryMode = SpatialQueryMode.Intersect; para.SpatialQueryObject = m_rec; Recordset recordset = null; Layer3DDataset layer = null; for (int i = 0; i < 3; i++) { if (i == 0) { recordset = mUseData.OutWaterNetWork.Query(para); layer = mUseData.OutWaterLines; } else if (i == 1) { recordset = mUseData.SupplyWaterNetWork.Query(para); layer = mUseData.SupplyWaterLines; } else if (i == 2) { recordset = mUseData.ElectricNetWork.Query(para); layer = mUseData.ElectricLayer; } List <Int32> ids = new List <int>(recordset.RecordCount); while (!recordset.IsEOF) { ids.Add(recordset.GetID()); recordset.MoveNext(); } layer.Selection.AddRange(ids.ToArray()); layer.Selection.UpdateData(); layer.Selection.Style.LineColor = Color.GreenYellow; mSceneControl.Scene.Refresh(); //在DataGrid中显示表 recordset.MoveFirst(); FieldInfos fieldinfos = recordset.GetFieldInfos(); foreach (FieldInfo fieldInfo in fieldinfos) { if (i >= 1) { break; } if (!fieldInfo.IsSystemField) { if (fieldInfo.Name == "SmPPoint" || fieldInfo.Name == "SmNPoint") { continue; } string mCaption = fieldInfo.Caption; this.mDataGridView.Columns.Add(mCaption, mCaption); } } //初始化行 DataGridViewRow dataGridViewRow; recordset.MoveFirst(); //根据选中的个数将对象的信息添加到列表中 while (!recordset.IsEOF) { dataGridViewRow = new DataGridViewRow(); for (int a = 0; a < recordset.FieldCount; a++) { if (!recordset.GetFieldInfos()[a].IsSystemField) { if (recordset.GetFieldInfos()[a].Name == "SmPPoint" || recordset.GetFieldInfos()[a].Name == "SmNPoint") { continue; } //定义并获取字段值 object filevalue = recordset.GetFieldValue(a); //添加到相应的位置 DataGridViewTextBoxCell cell = new DataGridViewTextBoxCell(); if (filevalue != null) { cell.ValueType = filevalue.GetType(); cell.Value = filevalue; } dataGridViewRow.Cells.Add(cell); } } this.mDataGridView.Rows.Add(dataGridViewRow); recordset.MoveNext(); } this.mDataGridView.Update(); recordset.Dispose(); } mSceneControl.Action = Action3D.Pan2; mSceneControl.Scene.Refresh(); } catch (System.Exception ex) { Trace.WriteLine(ex.Message); } }
/// <summary> /// Method to read the Ticket attributes for the input GIS ticket Id /// </summary> /// <param name="gisTicketId">Njuns Ticket ID</param> /// <param name="ticketNumber">ticketNumber</param> /// <param name="ticketId">Njuns Ticket ID</param> /// <returns>true, if ticket attributes exists in GIS. Else returns false.</returns> internal bool GetTicketAttributes(int gisTicketId, int ticketNumber = 0, string nJunsTicketId = "") { List <string> memberCodeList; List <string> poleOwnerList; try { string sql = string.Empty; if (ticketNumber > 0 && !string.IsNullOrEmpty(nJunsTicketId)) { sql = string.Format("SELECT * FROM GIS_ONC.NJUNS_TICKET WHERE TICKET_NUMBER = {0} AND NJUNS_TICKET_ID = '{1}'", ticketNumber, nJunsTicketId); } else { sql = string.Format("SELECT * FROM GIS_ONC.NJUNS_TICKET WHERE GIS_NJUNS_TICKET_ID = {0}", gisTicketId); } Recordset ticketAttributesRs = GetRecordSet(sql); if (ticketAttributesRs != null && ticketAttributesRs.RecordCount == 0) { MessageBox.Show(m_InterfacePoint + " : " + " Invalid ticket ID.", "Submit Ticket Error", MessageBoxButtons.OK); return(false); } m_Type = Convert.ToString(ticketAttributesRs.Fields["TICKET_TYPE"].Value); m_StructureId = Convert.ToString(ticketAttributesRs.Fields["POLE_NUMBER"].Value); m_Wr = Convert.ToString(ticketAttributesRs.Fields["MISCELLANEOUS_ID"].Value); m_NjunsMemberCode = Convert.ToString(ticketAttributesRs.Fields["NJUNS_MEMBER_CODE"].Value); m_PoleOwner = Convert.ToString(ticketAttributesRs.Fields["POLE_OWNER"].Value); m_PoleNumber = m_StructureId; m_status = Convert.ToString(ticketAttributesRs.Fields["TICKET_STATUS"].Value); m_StartDate = Convert.ToDateTime(ticketAttributesRs.Fields["START_DATE"].Value); m_WorkRequestedDate = Convert.ToDateTime(ticketAttributesRs.Fields["WORK_REQUESTED_DATE"].Value); m_State = Convert.ToString(ticketAttributesRs.Fields["STATE"].Value); m_County = Convert.ToString(ticketAttributesRs.Fields["COUNTY"].Value); m_Place = Convert.ToString(ticketAttributesRs.Fields["PLACE"].Value); m_HouseNumber = Convert.ToString(ticketAttributesRs.Fields["HOUSE_NUMBER"].Value); m_StreetName = Convert.ToString(ticketAttributesRs.Fields["STREET_NAME"].Value); m_PriorityCode = Convert.ToString(ticketAttributesRs.Fields["PRIORITY_CODE"].Value); m_PlotFilePath = Convert.ToString(ticketAttributesRs.Fields["PLOT"].Value); m_InvoiceFilePath = Convert.ToString(ticketAttributesRs.Fields["INVOICE"].Value); m_JobType = Convert.ToString(ticketAttributesRs.Fields["JOB_TYPE"].Value); m_NumberOfPoles = Convert.ToString(ticketAttributesRs.Fields["NUMBER_OF_POLES"].Value); m_DaysInterval = Convert.ToString(ticketAttributesRs.Fields["DAYS_INTERVAL"].Value); m_Remarks = Convert.ToString(ticketAttributesRs.Fields["REMARKS"].Value); ticketAttributesRs.Close(); ticketAttributesRs = null; BuildLists(out memberCodeList, out poleOwnerList); ticketAttributesRs = GetRecordSet(string.Format("SELECT * FROM GIS_ONC.NJUNS_STEP WHERE GIS_NJUNS_TICKET_ID = {0}", gisTicketId)); if (ticketAttributesRs != null && ticketAttributesRs.RecordCount == 0) { MessageBox.Show(m_InterfacePoint + " : " + " Invalid ticket ID.", "Submit Ticket Error", MessageBoxButtons.OK); return(false); } ticketAttributesRs.MoveFirst(); TicketStepType[] ticketStepType = new TicketStepType[ticketAttributesRs.RecordCount]; int i = 0; while (!ticketAttributesRs.EOF) { ticketStepType[i] = new TicketStepType(); ticketStepType[i].DaysInterval = Convert.ToString(ticketAttributesRs.Fields["DAYS_INTERVAL"].Value); ticketStepType[i].JobType = Convert.ToString(ticketAttributesRs.Fields["JOB_TYPE"].Value); MemberType mType = new MemberType(); mType.Value = Convert.ToString(ticketAttributesRs.Fields["NJUNS_MEMBER"].Value); Recordset njunsGuidRs = GetRecordSet(string.Format("SELECT NJUNS_CODE_GUID FROM NJUNS_MEMBER_COUNTY MC, NJUNS_MEMBER M WHERE MC.NJUNS_MEMBER_ID = M.NJUNS_MEMBER_ID AND M.NJUNS_MEMBER = '{0}'", mType.Value)); if (njunsGuidRs != null && njunsGuidRs.RecordCount > 0) { njunsGuidRs.MoveFirst(); mType.Id = Convert.ToString(njunsGuidRs.Fields["NJUNS_CODE_GUID"].Value); } ticketStepType[i].NjunsMemberCode = mType; ticketStepType[i].CustomNjunsMemberValue = mType.Value; ticketStepType[i].NumberOfPoles = Convert.ToString(ticketAttributesRs.Fields["NUMBER_POLES"].Value); ticketStepType[i].Remarks = Convert.ToString(ticketAttributesRs.Fields["REMARKS"].Value); ticketStepType[i].ReferenceId = Convert.ToString(i + 1); i = i + 1; ticketAttributesRs.MoveNext(); } m_ticketStepTypeList = ticketStepType.ToList(); return(true); } catch (Exception) { throw; } }
public void Execute() { string city = string.Empty; string county = string.Empty; string zipCode = string.Empty; string insideCityLimits = string.Empty; try { Recordset premiseAttributesRs = Components[ComponentName].Recordset; if (premiseAttributesRs != null && premiseAttributesRs.RecordCount > 0) { premiseAttributesRs.MoveFirst(); } while (!premiseAttributesRs.EOF) { city = Convert.ToString(premiseAttributesRs.Fields["CITY_C"].Value); county = Convert.ToString(premiseAttributesRs.Fields["COUNTY_C"].Value); zipCode = Convert.ToString(premiseAttributesRs.Fields["ZIP_C"].Value); insideCityLimits = Convert.ToString(premiseAttributesRs.Fields["INSIDE_CITY_LIMITS_YN"].Value); if (Convert.ToInt16(premiseAttributesRs.Fields["G3E_CID"].Value) == 1) { if (string.IsNullOrEmpty(city) && string.IsNullOrEmpty(county) && string.IsNullOrEmpty(zipCode) && string.IsNullOrEmpty(insideCityLimits)) { CopyValuesFromBoundaries(premiseAttributesRs); } if (!string.IsNullOrEmpty(city) || !string.IsNullOrEmpty(county) || !string.IsNullOrEmpty(zipCode) || !string.IsNullOrEmpty(insideCityLimits)) { m_City = city; m_CountyCode = county; m_ZipCode = zipCode; m_CityLimits = insideCityLimits; } premiseAttributesRs.MoveNext(); } else { if (!string.IsNullOrEmpty(city) || !string.IsNullOrEmpty(county) || !string.IsNullOrEmpty(zipCode) || !string.IsNullOrEmpty(insideCityLimits)) { m_City = city; m_CountyCode = county; m_ZipCode = zipCode; m_CityLimits = insideCityLimits; } if (string.IsNullOrEmpty(city) && string.IsNullOrEmpty(county) && string.IsNullOrEmpty(zipCode) && string.IsNullOrEmpty(insideCityLimits)) { premiseAttributesRs.Fields["CITY_C"].Value = m_City; premiseAttributesRs.Fields["COUNTY_C"].Value = m_CountyCode; premiseAttributesRs.Fields["ZIP_C"].Value = m_ZipCode; premiseAttributesRs.Fields["INSIDE_CITY_LIMITS_YN"].Value = m_CityLimits; } premiseAttributesRs.MoveNext(); } } } catch (Exception ex) { GUIMode guiMode = new GUIMode(); if (guiMode.InteractiveMode) { MessageBox.Show("Error during execution of Set Premise Location By Boundary FI. " + ex.Message, "G/Technology"); } else { int tmpRecModified = 0; string tmpQry = string.Empty; tmpQry = "begin insert into gis_stg.interface_log " + "(SUB_INTERFACE_NAME,INTERFACE_NAME,COMPONENT_NAME,CORRELATION_ID,LOG_DETAIL) " + "values ('ccGISAutomationBroker','ccGISAutomationBroker','fiSetPremiseLocationByBoundary',0," + "'Error during execution of Set Premise Location By Boundary FI. " + ex.Message + "'); end;"; m_DataContext.Execute(tmpQry, out tmpRecModified, (int)CommandTypeEnum.adCmdText); } } }
private void CopyPhaseAndPositionFromChangeoutInstance(int changeOutInstance) { try { string phase = string.Empty; string phasePosition = string.Empty; string isNeutral = string.Empty; short cno = GetUnitOrBankAttributeCNoForFNo(m_oFeature.FNO); if (cno == 0) { return; } Recordset attributeRS = m_oDataContext.OpenFeature(m_oFeature.FNO, m_oFeature.FID).Components.GetComponent(cno).Recordset; if (attributeRS != null && attributeRS.RecordCount > 0) { attributeRS.Filter = "G3E_CID = " + changeOutInstance; if (!(attributeRS.EOF && attributeRS.BOF)) { try { phase = Convert.ToString(attributeRS.Fields["PHASE_C"].Value); phasePosition = Convert.ToString(attributeRS.Fields["PHASE_POS_C"].Value); } catch (Exception) { } try { isNeutral = Convert.ToString(attributeRS.Fields["NEUTRAL_YN"].Value); } catch (Exception) { } } attributeRS.Filter = FilterGroupEnum.adFilterNone; attributeRS.MoveFirst(); attributeRS.MoveLast(); if (!(attributeRS.EOF && attributeRS.BOF)) { try { attributeRS.Fields["PHASE_C"].Value = phase; attributeRS.Fields["PHASE_POS_C"].Value = phasePosition; } catch (Exception) { } try { attributeRS.Fields["NEUTRAL_YN"].Value = isNeutral; } catch { } } } } catch (Exception) { throw; } }
/// <summary> /// Uploads the report file to SharePoint /// </summary> /// <param name="fileName">The absolute path to the file</param> /// <param name="fileType">The file type</param> /// <param name="url">URL for the document management file</param> /// <param name="docMgmtFileName">Filename for the document management file</param> /// <returns>Boolean indicating status</returns> public bool UploadReport(string fileName, string fileType, ref string url, ref string docMgmtFileName) { bool bReturnValue = false; try { m_Application.SetStatusBarText(GTStatusPanelConstants.gtaspcMessage, ConstantsDT.MESSAGE_REPORT_UPLOADING); m_Application.BeginWaitCursor(); string tmpQry = "select param_name, param_value from sys_generalparameter " + "where SUBSYSTEM_NAME = ?"; Recordset tmpRs = m_Application.DataContext.OpenRecordset(tmpQry, CursorTypeEnum.adOpenDynamic, LockTypeEnum.adLockReadOnly, (int)CommandTypeEnum.adCmdText, "Doc_Management"); if (!(tmpRs.BOF && tmpRs.EOF)) { tmpRs.MoveFirst(); OncDocManage.OncDocManage rptToSave = new OncDocManage.OncDocManage(); while (!tmpRs.EOF) { if (tmpRs.Fields["PARAM_NAME"].Value.ToString() == "JOBWO_REL_PATH") { rptToSave.SPRelPath = tmpRs.Fields["PARAM_VALUE"].Value.ToString(); } if (tmpRs.Fields["PARAM_NAME"].Value.ToString() == "SP_URL") { rptToSave.SPSiteURL = tmpRs.Fields["PARAM_VALUE"].Value.ToString(); } if (tmpRs.Fields["PARAM_NAME"].Value.ToString() == "ROOT_PATH") { rptToSave.SPRootPath = tmpRs.Fields["PARAM_VALUE"].Value.ToString(); } tmpRs.MoveNext(); } rptToSave.SrcFilePath = fileName; rptToSave.WrkOrd_Job = m_Application.DataContext.ActiveJob; rptToSave.SPFileName = fileName.Substring(fileName.LastIndexOf("\\") + 1); rptToSave.SPFileType = fileType; bool bSpFileAdded = rptToSave.AddSPFile(true); if (bSpFileAdded == false) { MessageBox.Show(m_Application.ApplicationWindow, ConstantsDT.ERROR_REPORT_SAVING + ": " + "Error adding " + rptToSave.SPFileName + " to SharePoint.", ConstantsDT.APPLICATION_NAME, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); bReturnValue = false; } else { bReturnValue = true; } url = rptToSave.RetFileURL; docMgmtFileName = rptToSave.RetFileName; tmpRs = null; } else { MessageBox.Show(m_Application.ApplicationWindow, ConstantsDT.ERROR_REPORT_SAVING + ": " + "Error finding General Parameters JOBWO_REL_PATH or 'SP_URL", ConstantsDT.APPLICATION_NAME, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); bReturnValue = false; } } catch (Exception ex) { MessageBox.Show(m_Application.ApplicationWindow, ConstantsDT.ERROR_REPORT_SAVING + ": " + ex.Message, ConstantsDT.APPLICATION_NAME, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); bReturnValue = false; } m_Application.EndWaitCursor(); m_Application.SetStatusBarText(GTStatusPanelConstants.gtaspcMessage, ""); return(bReturnValue); }
public void GetRecorsetOfAssociateFeaturesForVP(IGTGeometry p_tempGeometry, short[] lstFNO, ref DataTable p_associatedRs, short p_AactiveFno, Dictionary <short, string> p_relatedFeatures) { DataAccess dataAccess = null; Recordset rsTemp = null; IGTKeyObject gTKeyObject = null; List <string> IsolationFs = new List <string> { "PPI", "ABI" }; List <string> byPassFs = new List <string> { "PPR", "ABR", "PPI", "ABI" }; bool emptyRecord = true; p_associatedRs = new DataTable("Results"); p_associatedRs.Columns.Add("Feature"); p_associatedRs.Columns.Add("Feature Instance"); p_associatedRs.Columns.Add("G3E_FNO"); string value = null; try { IGTSpatialService spatialService = GTClassFactory.Create <IGTSpatialService>(); spatialService.DataContext = m_oGTApplication.DataContext; spatialService.Operator = GTSpatialOperatorConstants.gtsoIndexIntersect; spatialService.FilterGeometry = p_tempGeometry; Recordset rsCommon = null; rsTemp = spatialService.GetResultsByFNO(lstFNO); if (rsTemp != null && rsTemp.RecordCount > 0) { rsTemp.MoveFirst(); while (!rsTemp.EOF) { gTKeyObject = m_oGTApplication.DataContext.OpenFeature(Convert.ToInt16(rsTemp.Fields["g3e_fno"].Value), Convert.ToInt32(rsTemp.Fields["G3E_FID"].Value)); rsCommon = gTKeyObject.Components["COMMON_N"].Recordset; if (rsCommon != null && rsCommon.RecordCount > 0) { rsCommon.MoveFirst(); if (p_AactiveFno == 40 || p_AactiveFno == 80) { if (byPassFs.Contains(Convert.ToString(rsCommon.Fields["FEATURE_STATE_C"].Value))) { DataRow row = p_associatedRs.NewRow(); value = ""; p_relatedFeatures.TryGetValue(Convert.ToInt16(rsTemp.Fields["g3e_fno"].Value), out value); row["Feature"] = value; row["Feature Instance"] = Convert.ToInt32(rsTemp.Fields["G3E_FID"].Value); row["G3E_FNO"] = Convert.ToInt16(rsTemp.Fields["g3e_fno"].Value); p_associatedRs.Rows.Add(row); emptyRecord = false; } } else if (p_AactiveFno == 6 || p_AactiveFno == 82) { if (IsolationFs.Contains(Convert.ToString(rsCommon.Fields["FEATURE_STATE_C"].Value))) { DataRow row = p_associatedRs.NewRow(); value = ""; p_relatedFeatures.TryGetValue(Convert.ToInt16(rsTemp.Fields["g3e_fno"].Value), out value); row["Feature"] = value; row["Feature Instance"] = Convert.ToInt32(rsTemp.Fields["G3E_FID"].Value); row["G3E_FNO"] = Convert.ToInt16(rsTemp.Fields["g3e_fno"].Value); p_associatedRs.Rows.Add(row); emptyRecord = false; } } } rsTemp.MoveNext(); } } if (emptyRecord) { p_associatedRs = null; } } catch { throw; } finally { if (dataAccess != null) { dataAccess = null; } } }
/// <summary> /// This function gathers all premises that should be displayed. Any premise w/out a number that /// is attached to a selected service point or, if no service points are found, all premises without /// numbers. This should get data in a format that cn be used in a data grid. /// </summary> public static void LoadData() { try { IGTKeyObjects servicePoints = GTClassFactory.Create <IGTKeyObjects>(); IGTJobHelper jobHelper = GTClassFactory.Create <IGTJobHelper>(); selectedObjects = gtApp.SelectedObjects.GetObjects(); string PremiseMetaDataQuery = "SELECT COLUMN_NAME, DATA_TYPE, DATA_LENGTH, DATA_PRECISION, DATA_SCALE FROM ALL_TAB_COLUMNS WHERE TABLE_NAME = 'PREMISE_N'"; PremiseMetaRecords = gtDataContext.OpenRecordset(PremiseMetaDataQuery, CursorTypeEnum.adOpenDynamic, LockTypeEnum.adLockOptimistic, -1); PremiseMetaRecords.MoveFirst(); while (!PremiseMetaRecords.EOF && PremiseMetaRecords.RecordCount > 0) { string[] values = { PremiseMetaRecords.Fields["DATA_TYPE"].Value.ToString(), PremiseMetaRecords.Fields["DATA_LENGTH"].Value.ToString(), PremiseMetaRecords.Fields["DATA_PRECISION"].Value.ToString(), PremiseMetaRecords.Fields["DATA_SCALE"].Value.ToString() }; ColumnRules.Add(PremiseMetaRecords.Fields["COLUMN_NAME"].Value.ToString(), new List <string>(values)); PremiseMetaRecords.MoveNext(); } //If we have objects selected if (selectedObjects.Count > 0) {//this code is a bit broken, instead of doing 1 call it calls multiple times. List <int> FIDs = new List <int>(); int badObject = 0; foreach (IGTDDCKeyObject x in selectedObjects) { if (x.FNO == FNO) { if (!FIDs.Contains(x.FID))//don't want this to trigger the else statement { FIDs.Add(x.FID); } } else { badObject++; } } //If we have Service Points selected if (FIDs.Count > 0 && badObject == 0) { //LOGIC to detect service points and if they have premise records w/out ESI Locations string FIDsString = string.Join(", ", FIDs); //if we have service points if (FIDs.Count > 0) { //LOGIC to detect service points and if they have premise records w/out ESI Locations string PremiseQuery = "SELECT * FROM PREMISE_N WHERE G3E_FID IN (" + FIDsString + " ) AND PREMISE_NBR IS null"; PremiseRecords = gtDataContext.OpenRecordset(PremiseQuery, CursorTypeEnum.adOpenDynamic, LockTypeEnum.adLockOptimistic, -1); if (PremiseRecords.EOF && PremiseRecords.BOF) { ErrorMessage = "All selected Service Points have ESI Locations."; } } } //Anything other than Service Points selected else { ErrorMessage = "The select set contains features other than Service Points." + Environment.NewLine + Environment.NewLine + "Before running the command select a Service Point or unselect all features to process all Service Points in the active Job."; } } // If no objects are selected else { Recordset edits; edits = jobHelper.FindPendingEdits(); List <int> FIDs = new List <int>(); //if we have edits in the current job if (edits != null && !edits.EOF) { edits.MoveFirst(); if (edits.Fields["G3E_FNO"].Value == FNO) {//hard coding in column index FIDs.Add(Convert.ToInt32(edits.Fields["G3E_FID"].Value.ToString())); edits.MoveNext(); } while (!edits.EOF) { if (edits.Fields["G3E_FNO"].Value == FNO) { FIDs.Add(Convert.ToInt32(edits.Fields["G3E_FID"].Value.ToString())); } edits.MoveNext(); } //We need to make a string from our list of FIDS string FIDsString = string.Join(", ", FIDs); //if we have service points if (FIDs.Count > 0) { //LOGIC to detect service points and if they have premise records w/out ESI Locations string PremiseQuery = "SELECT * FROM PREMISE_N WHERE G3E_FID IN (" + FIDsString + " ) AND PREMISE_NBR IS null"; PremiseRecords = gtDataContext.OpenRecordset(PremiseQuery, CursorTypeEnum.adOpenDynamic, LockTypeEnum.adLockOptimistic, -1); if (PremiseRecords.EOF && PremiseRecords.BOF) { ErrorMessage = "All Service Points have ESI Locations."; } } //no service points edited in job else { ErrorMessage = "No Service Points in active job."; } } else { ErrorMessage = "No Service Points in active job."; } } } catch (Exception error) { MessageBox.Show("Error in LoadData (" + error.Message + ")", "G/Technology"); } }
/// <summary> /// 加载地下管道线 /// </summary> public void LoadPipeLine3D() { try { m_SelectedGeoNetwork = new List <NetworkGeometry>(); DatasetVector dataset_PipeLine = m_workspace.Datasources["Pipeline3D"].Datasets["PipeLine3D"] as DatasetVector; DatasetVector dataset_PipePoint = m_workspace.Datasources["Pipeline3D"].Datasets["PipePoint3D"] as DatasetVector; Layer3DSettingVector setvetor = new Layer3DSettingVector(); setvetor.Style.AltitudeMode = AltitudeMode.RelativeToGround; setvetor.Style.LineSymbolID = 962048; setvetor.Style.LineWidth = 0.35; Layer3DDataset layer_ditie = m_sceneControl.Scene.Layers.Add(dataset_PipeLine, setvetor, true, "PipeLine3D"); Layer3DDataset layer_pipepoint = m_sceneControl.Scene.Layers.Add(dataset_PipePoint, setvetor, true, "PipePoint3D"); if (dataset_PipePoint != null) { Theme3DUnique theme = new Theme3DUnique(); theme.UniqueExpression = "SmID"; GeoStyle3D style3D = new GeoStyle3D(); style3D.AltitudeMode = AltitudeMode.RelativeToGround; style3D.Marker3DScaleX = 2.2; style3D.Marker3DScaleY = 2.2; style3D.Marker3DScaleZ = 2.2; style3D.IsMarker3D = true; theme.DefaultStyle = style3D; Recordset rs = dataset_PipePoint.Query("", CursorType.Static); rs.MoveFirst(); while (!rs.IsEOF) { Theme3DUniqueItem item = new Theme3DUniqueItem(); item.Unique = rs.GetID().ToString(); item.IsModellingStyleEnabled = true; GeoStyle3D tempStyle = new GeoStyle3D(style3D); PickNodeToLine(rs.GetID()); GeoPoint3D geoPoint3D = rs.GetGeometry() as GeoPoint3D; List <Vector3d> arrVector3d = new List <Vector3d>(); for (Int32 curIndex = 0; curIndex < m_SelectedGeoNetwork.Count; curIndex++) { NetworkGeometry geoNetWork = m_SelectedGeoNetwork[curIndex]; if (geoNetWork != null) { Vector3d vec = new Vector3d(); GeoLine3D geoLine = geoNetWork.geometry as GeoLine3D; if (geoNetWork.bIsIn) { if (geoLine != null) { Point3Ds point3D = geoLine[0]; Point3D pntTNode = point3D[1]; Point3D pntFNode = point3D[0]; Vector3d vecTNode = SphericalToCartesian(pntTNode.X * DTOR, pntTNode.Y * DTOR, pntTNode.Z); Vector3d vecFNode = SphericalToCartesian(pntFNode.X * DTOR, pntFNode.Y * DTOR, pntFNode.Z); vec = new Vector3d(vecFNode.x - vecTNode.x, vecFNode.y - vecTNode.y, vecFNode.z - vecTNode.z); vec.Normalize(); } } else { if (geoLine != null) { Point3Ds point3D = geoLine[0]; Point3D pntFNode = point3D[0]; Point3D pntTNode = point3D[1]; Vector3d vecTNode = SphericalToCartesian(pntTNode.X * DTOR, pntTNode.Y * DTOR, pntTNode.Z); Vector3d vecFNode = SphericalToCartesian(pntFNode.X * DTOR, pntFNode.Y * DTOR, pntFNode.Z); vec = new Vector3d(vecTNode.x - vecFNode.x, vecTNode.y - vecFNode.y, vecTNode.z - vecFNode.z); vec.Normalize(); } } vec = FromAngleAxis(vec, -geoPoint3D.X * DTOR, new Vector3d(0, 1, 0)); vec = FromAngleAxis(vec, geoPoint3D.Y * DTOR, new Vector3d(1, 0, 0)); vec.Normalize(); arrVector3d.Add(vec); } } Vector3d vecX = new Vector3d(); Vector3d vecY = new Vector3d(); Vector3d vecZ = new Vector3d(); switch (m_SelectedGeoNetwork.Count) { case 2: //弯头或阀门 { if (arrVector3d.Count == 2) { vecX = arrVector3d[0].Normalize().Sub(); vecY = arrVector3d[1].Normalize(); } double dAngle1_2 = vecX.DotProduct(vecY); if (Math.Abs(dAngle1_2) < 0.3) { tempStyle.MarkerSymbolID = 54441; } else if (-1 < dAngle1_2 && dAngle1_2 < 0.7) { tempStyle.MarkerSymbolID = 54442; } else { vecY.z = 0; Vector3d vec = new Vector3d(0, 0, 1); vecX = vecY.CrossProduct(vec); tempStyle.MarkerSymbolID = 54435; } } break; case 3: //三通 { tempStyle.MarkerSymbolID = 54437; if (arrVector3d.Count == 3) { Vector3d vec1 = arrVector3d[0]; Vector3d vec2 = arrVector3d[1]; Vector3d vec3 = arrVector3d[2]; double dAngle1_2 = vec1.DotProduct(vec2); double dAngle1_3 = vec1.DotProduct(vec3); double dAngle2_3 = vec2.DotProduct(vec3); if (Math.Abs(dAngle1_2) < 0.3) { if (Math.Abs(dAngle1_3) < 0.3) { vecX = vec1.Normalize().Sub(); vecY = vec2.Normalize(); } else { vecX = vec2.Normalize().Sub(); vecY = vec1.Normalize(); } } else { vecX = vec3.Normalize().Sub(); vecY = vec1.Normalize(); } } } break; case 4: //四通 { tempStyle.MarkerSymbolID = 54438; if (arrVector3d.Count == 4) { Vector3d vec1 = arrVector3d[0]; Vector3d vec2 = arrVector3d[1]; Vector3d vec3 = arrVector3d[2]; double dAngle1_2 = vec1.DotProduct(vec2); double dAngle1_3 = vec1.DotProduct(vec3); vecX = vec1; if (Math.Abs(dAngle1_2) < 0.3) { vecY = vec2.Normalize(); } else { vecY = vec3.Normalize(); } } } break; default: //结点 { tempStyle.MarkerSymbolID = 330101; } break; } if (m_SelectedGeoNetwork.Count > 1) { vecZ = vecX.CrossProduct(vecY); vecZ.Normalize(); Vector3d vecRotate = ToEulerAnglesXYZ(vecX, vecY, vecZ); tempStyle.Marker3DRotateX = -vecRotate.x * RTOD; tempStyle.Marker3DRotateY = -vecRotate.y * RTOD; tempStyle.Marker3DRotateZ = -vecRotate.z * RTOD; } item.Style = tempStyle; theme.Add(item); rs.MoveNext(); } rs.Dispose(); Layer3D layer_theme = m_sceneControl.Scene.Layers.Add(dataset_PipePoint, theme, true, "underPipeLine3D"); layer_theme.IsSelectable = false; if (m_sceneControl.Scene.Layers.Contains("PipePoint3D")) { m_sceneControl.Scene.Layers.Remove("PipePoint3D"); } Camera camera = m_sceneControl.Scene.Camera; camera.AltitudeMode = AltitudeMode.RelativeToGround; camera.Altitude = 26.978640816174448; camera.Latitude = 39.992608337161023; camera.Longitude = 116.3898561529368; camera.Tilt = 59.567389444384283; camera.Heading = 300.19323029928478; m_sceneControl.Scene.Fly(camera, 1); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private IEnumerable<ImportEntity> MapMasterDataList(Recordset rs) { rs.MoveFirst(); while (!(rs.EoF)) { var imports = new ImportEntity(); var list = new List<string>(); for (int i = 0; i < rs.Fields.Count; i++) { string field = rs.Fields.Item(i).Value.ToString(); list.Add(field); } imports.Fields = list.ToArray(); imports.MasterDataCollective = masterdataEntity; MasterDataList.Add(imports); rs.MoveNext(); } return MasterDataList; }
public void Validate(out string[] ErrorPriorityArray, out string[] ErrorMessageArray) { ADODB.Recordset rs = null; ADODB.Recordset rsTemp = null; int record = 0; bool isPhaseExists = false; ErrorPriorityArray = null; ErrorMessageArray = null; try { List <string> errorMsg = new List <string>(); List <string> errorPriority = new List <string>(); string priority = Convert.ToString(_arguments.GetArgument(0)); Recordset commonComponentRs = Components.GetComponent(1).Recordset; commonComponentRs.MoveFirst(); string orientation = Convert.ToString(commonComponentRs.Fields["ORIENTATION_C"].Value); int fNo = Convert.ToInt32(commonComponentRs.Fields["G3E_FNO"].Value); string featureName = Convert.ToString(GetRecordSet(string.Format("select g3e_username NAME from g3e_feature where g3e_fno = {0}", fNo)).Fields["NAME"].Value); int fId = Convert.ToInt32(commonComponentRs.Fields["G3E_FID"].Value); bool isFeatureConnected = CheckFeatureConnectivity(fId); if (orientation == "OH" && featureName.ToUpper().Contains("PRIMARY") && isFeatureConnected && !CheckPhaseAndPhasePosition(out isPhaseExists)) { errorPriority.Add(priority); errorMsg.Add("Overhead feature is missing phase position values."); } if (CheckPhaseAndPhasePosition(out isPhaseExists)) { if (!isPhaseExists) { errorPriority.Add(priority); errorMsg.Add("Phase Position attributes do not match specified phase."); } } if (ValidatePhasePositionWithSets()) { errorPriority.Add(priority); errorMsg.Add("Phase Position attributes are not consistent with respect to one another."); } if (_fieldName == "PHASE_POS_C") { string sqlStmt = "Select {0},count({0}) from {1} where g3e_fid={2} and g3e_fno={3} GROUP BY {0} having count({0})>1"; //string sqlQuery = "Select listagg(a.{0},',') within group (order by a.PHASE_POS_C) as PhasePosition from {1} a where g3e_fid={2} and not exists (Select vl_key from VL_PHASE_POSITION p where p.vl_key=a.{0})"; IGTComponent gtComponent = _components[_componentName]; if (gtComponent != null) { rs = gtComponent.Recordset; if (rs != null && rs.RecordCount > 0) { rs.MoveFirst(); if (Convert.ToInt32(rs.Fields["G3e_CID"].Value) == 1) { //JIRA 195- check Duplicate Phase Position rsTemp = _dataContext.Execute(string.Format(sqlStmt, _fieldName, _componentName, rs.Fields["G3e_FID"].Value, rs.Fields["G3e_FNO"].Value), out record, (int)ADODB.CommandTypeEnum.adCmdText, null); if (rsTemp != null && rsTemp.RecordCount > 0) { errorMsg.Add("Feature having duplicate Phase Position. Phase Position should be unique across all the wires within same conductor."); errorPriority.Add(priority); } /* * Commneted this code as per Shubham suggestion * * // As per the JIRA 476 - Business Rule Validate Unknown Values in Phase Position * rsTemp = _dataContext.Execute(string.Format(sqlQuery, _fieldName, _componentName, rs.Fields["G3e_FID"].Value), out record, (int)ADODB.CommandTypeEnum.adCmdText, null); * if (rsTemp != null && rsTemp.RecordCount > 0) * { * rsTemp.MoveFirst(); * phasePosition = Convert.ToString(rsTemp.Fields[0].Value); * if (!string.IsNullOrEmpty(phasePosition)) * { * errorMsg.Add("Phase Position " + rsTemp.Fields[0].Value + " are unknown Values"); * errorPriority.Add("P2"); * } * } */ } } } if (errorMsg.Count > 0) { ErrorPriorityArray = errorPriority.ToArray(); ErrorMessageArray = errorMsg.ToArray(); } } } catch (Exception ex) { MessageBox.Show(ex.Message, Caption); } finally { rsTemp = null; } }
private void ProcessingFormation() { IGTComponent gTContainsComponent = m_activeKeyObject.Components["CONTAIN_N"]; if (gTContainsComponent != null && gTContainsComponent.Recordset != null && gTContainsComponent.Recordset.RecordCount > 0) { Recordset rsContains = gTContainsComponent.Recordset; Recordset rsDuctivity = null; rsContains.MoveFirst(); while (!rsContains.EOF) { IGTKeyObject formationOwner = m_dataContext.OpenFeature(Convert.ToInt16(rsContains.Fields["G3E_OWNERFNO"].Value), Convert.ToInt32(rsContains.Fields["G3E_OWNERFID"].Value)); if (formationOwner.Components.Count > 0 && formationOwner.Components["DUCTIVITY_N"] != null && formationOwner.Components["DUCTIVITY_N"].Recordset != null && formationOwner.Components["DUCTIVITY_N"].Recordset.RecordCount > 0) { rsDuctivity = formationOwner.Components["DUCTIVITY_N"].Recordset; IGTKeyObjects ownerKeyObjects = LocateOwnersOfActiveFeature(122, formationOwner); foreach (IGTKeyObject gtownerKeyObject in ownerKeyObjects) { if (gtownerKeyObject.FID != formationOwner.FID) { List <short> structFNO = new List <short> { 106, 107, 108, 109, 110, 113, 114, 115, 116, 117, 120, 2500 }; if (structFNO.Contains(Convert.ToInt16(gtownerKeyObject.FNO))) { IGTKeyObjects ownerWorkpoints = FindWorkpointsOfFeature(gtownerKeyObject.Components.GetComponent(1)); if (ownerWorkpoints != null) { if (ownerWorkpoints.Count <= 0) { CreateNewWorkpointFeature( Convert.ToInt16(m_activeKeyObject.Components.GetComponent(1).Recordset.Fields["G3E_FNO"].Value), Convert.ToInt32(m_activeKeyObject.Components.GetComponent(1).Recordset.Fields["G3E_FID"].Value), true, Convert.ToString(gtownerKeyObject.Components.GetComponent(1).Recordset.Fields["STRUCTURE_ID"].Value), 0, gtownerKeyObject.FNO, gtownerKeyObject.FID); } else { UpdateWorkpointComponents(Convert.ToInt16(gtownerKeyObject.Components.GetComponent(1).Recordset.Fields["G3E_FNO"].Value), Convert.ToInt32(gtownerKeyObject.Components.GetComponent(1).Recordset.Fields["G3E_FID"].Value), ownerWorkpoints[0], false, Convert.ToString(gtownerKeyObject.Components.GetComponent(1).Recordset.Fields["STRUCTURE_ID"].Value), 0, true); } } } } } } rsContains.MoveNext(); } } }
/// <summary> /// Method to set the 'Configured Phase' attribute of Primary Conductor - OH (Network) Attributes /// </summary> /// <returns></returns> private string PrepareConfiguredPhaseAttribute() { List <KeyValuePair <string, string> > PositionsAndPhasePair = null; string configuredPhase = string.Empty; bool isSet1 = false; bool isSet2 = false; bool isSet3 = false; bool set1Complete = false; bool set2Complete = false; bool set3Complete = false; try { Recordset ohAttributesRs = Components[ComponentName].Recordset; if (ohAttributesRs != null) { PositionsAndPhasePair = new List <KeyValuePair <string, string> >(); string phasePosition = string.Empty; string phase = string.Empty; ohAttributesRs.MoveFirst(); while (!ohAttributesRs.EOF) { phase = Convert.ToString(ohAttributesRs.Fields["PHASE_C"].Value); phasePosition = Convert.ToString(ohAttributesRs.Fields["PHASE_POS_C"].Value); if (string.IsNullOrEmpty(phase) || string.IsNullOrEmpty(phasePosition)) { return(string.Empty); } PositionsAndPhasePair.Add(new KeyValuePair <string, string>(phasePosition, phase)); // Key - PhasePosition , Value - Phase ohAttributesRs.MoveNext(); } foreach (KeyValuePair <string, string> KeyValue in PositionsAndPhasePair) { if (set1.Contains(KeyValue.Key)) { if (isSet2 || isSet3) { configuredPhase = string.Empty; break; } if (set1Complete) { continue; } isSet1 = true; string[] set1Split = set1.Split(','); string tempString = string.Empty; string tempKey = string.Empty; foreach (string position in set1Split) { var keyValues = (PositionsAndPhasePair.Where(x => x.Key == position)); foreach (KeyValuePair <string, string> keyVal in keyValues) { if (tempKey == keyVal.Key) { return(string.Empty); } configuredPhase = configuredPhase + keyVal.Value; tempKey = keyVal.Key; } } set1Complete = true; } else if (set2.Contains(KeyValue.Key)) { if (isSet1 || isSet3) { configuredPhase = string.Empty; break; } if (set2Complete) { continue; } isSet2 = true; string[] set2Split = set2.Split(','); string tempString = string.Empty; string tempKey = string.Empty; foreach (string position in set2Split) { var keyValues = (PositionsAndPhasePair.Where(x => x.Key == position)); foreach (KeyValuePair <string, string> keyVal in keyValues) { if (tempKey == keyVal.Key) { return(string.Empty); } configuredPhase = configuredPhase + keyVal.Value; tempKey = keyVal.Key; } } set2Complete = true; } else if (set3.Contains(KeyValue.Key)) { if (isSet2 || isSet1) { configuredPhase = string.Empty; break; } if (set3Complete) { continue; } isSet3 = true; string[] set3Split = set3.Split(','); string tempString = string.Empty; string tempKey = string.Empty; foreach (string position in set3Split) { var keyValues = (PositionsAndPhasePair.Where(x => x.Key == position)); foreach (KeyValuePair <string, string> keyVal in keyValues) { if (tempKey == keyVal.Key) { return(string.Empty); } configuredPhase = configuredPhase + keyVal.Value; tempKey = keyVal.Key; } } set3Complete = true; } } } return(configuredPhase); } catch (Exception) { throw; } }
/// <summary> /// Update the Related Work Point attribute of the Second Work Point. /// </summary> /// <param name="gTOwnerKeyObjects">Owner Key Object of Active Key Object</param> private void UpdateRelatedWPAttribute(IGTKeyObjects gTOwnerKeyObjects) { IGTComponent gtActiveFeatureCommonCom = null; int Owner1Id = 0; int Owner2Id = 0; int Owner1Fid = 0; int Owner2Fid = 0; IGTKeyObject gTOwner1KeyObject = null; IGTKeyObject gTOwner2KeyObject = null; IGTKeyObjects gTWorkPointOwner1KeyObjects = null; IGTKeyObjects gTWorkPointOwner2KeyObjects = null; IGTComponent gTOwner1Component = null; IGTComponent gTOwner2Component = null; Recordset tmpOwnerrs = null; int WorkPointNumber = 0; string sql = ""; int count = 0; try { gtActiveFeatureCommonCom = m_activeKeyObject.Components.GetComponent(1); Owner1Id = Convert.ToInt32(gtActiveFeatureCommonCom.Recordset.Fields["OWNER1_ID"].Value); Owner2Id = Convert.ToInt32(gtActiveFeatureCommonCom.Recordset.Fields["OWNER2_ID"].Value); sql = "select G3E_FID from COMMON_N where g3e_id = ?"; tmpOwnerrs = m_dataContext.Execute(sql, out count, (int)ADODB.CommandTypeEnum.adCmdText, Owner1Id); if (tmpOwnerrs != null && tmpOwnerrs.RecordCount > 0) { tmpOwnerrs.MoveFirst(); if (!(tmpOwnerrs.EOF && tmpOwnerrs.BOF)) { Owner1Fid = Convert.ToInt32(tmpOwnerrs.Fields["G3E_FID"].Value); } } sql = "select G3E_FID from COMMON_N where g3e_id = ?"; tmpOwnerrs = m_dataContext.Execute(sql, out count, (int)ADODB.CommandTypeEnum.adCmdText, Owner2Id); if (tmpOwnerrs != null && tmpOwnerrs.RecordCount > 0) { tmpOwnerrs.MoveFirst(); if (!(tmpOwnerrs.EOF && tmpOwnerrs.BOF)) { Owner2Fid = Convert.ToInt32(tmpOwnerrs.Fields["G3E_FID"].Value); } } foreach (IGTKeyObject keyObj in gTOwnerKeyObjects) { if (keyObj.FID == Owner1Fid) { gTOwner1KeyObject = keyObj; } else if (keyObj.FID == Owner2Fid) { gTOwner2KeyObject = keyObj; } } gTWorkPointOwner1KeyObjects = FindWorkpointsOfFeature(gTOwner1KeyObject.Components.GetComponent(1)); gTWorkPointOwner2KeyObjects = FindWorkpointsOfFeature(gTOwner2KeyObject.Components.GetComponent(1)); gTOwner1Component = gTWorkPointOwner1KeyObjects[0].Components["WORKPOINT_CU_N"]; bool wpRUpdate = false; if (gTOwner1Component.Recordset != null && gTOwner1Component.Recordset.RecordCount > 0) { gTOwner1Component.Recordset.MoveFirst(); gTOwner2Component = gTWorkPointOwner2KeyObjects[0].Components["WORKPOINT_N"]; if (gTOwner1Component.Recordset != null && gTOwner1Component.Recordset.RecordCount > 0) { gTOwner2Component.Recordset.MoveFirst(); WorkPointNumber = Convert.ToInt32(gTOwner2Component.Recordset.Fields["wp_nbr"].Value); while (!gTOwner1Component.Recordset.EOF) { if (!String.IsNullOrEmpty(Convert.ToString(gTOwner1Component.Recordset.Fields["ASSOC_FID"].Value)) && Convert.ToInt32(gTOwner1Component.Recordset.Fields["ASSOC_FID"].Value) == m_activeKeyObject.FID) { gTOwner1Component.Recordset.Fields["WP_RELATED"].Value = WorkPointNumber; wpRUpdate = true; } gTOwner1Component.Recordset.MoveNext(); } } } if (!wpRUpdate) { gTOwner2Component = gTWorkPointOwner2KeyObjects[0].Components["WORKPOINT_CU_N"]; if (gTOwner2Component.Recordset != null && gTOwner2Component.Recordset.RecordCount > 0) { gTOwner2Component.Recordset.MoveFirst(); gTOwner1Component = gTWorkPointOwner1KeyObjects[0].Components["WORKPOINT_N"]; if (gTOwner2Component.Recordset != null && gTOwner2Component.Recordset.RecordCount > 0) { gTOwner1Component.Recordset.MoveFirst(); WorkPointNumber = Convert.ToInt32(gTOwner1Component.Recordset.Fields["wp_nbr"].Value); while (!gTOwner2Component.Recordset.EOF) { if (!String.IsNullOrEmpty(Convert.ToString(gTOwner2Component.Recordset.Fields["ASSOC_FID"].Value)) && Convert.ToInt32(gTOwner2Component.Recordset.Fields["ASSOC_FID"].Value) == m_activeKeyObject.FID) { gTOwner2Component.Recordset.Fields["WP_RELATED"].Value = WorkPointNumber; } gTOwner2Component.Recordset.MoveNext(); } } } } } catch { throw; } }
/// <summary> /// 将超图的Geometry格式转换为geojson/wkt/wkb格式 /// </summary> /// <param name="convertDataEnum"></param> private void ConvertGeometryToFormat(ConvertDataEnum convertDataEnum) { var shapeFieldName = filePathTextBlock.Text; if (string.IsNullOrEmpty(shapeFieldName)) { throw new Exception($"shp文件为空!"); } Workspace workspace = new Workspace(); DatasourceConnectionInfo info = new DatasourceConnectionInfo(); //将shp文件的数据转存为udb临时数据,而不是读取在内存中,防止内存泄漏 var filePath = $"{Directory.GetCurrentDirectory()}\\{Guid.NewGuid().ToString()}"; var files = new List <string> { $"{filePath}.udb", $"{filePath}.udd" }; string targetDatasetName = "targetDatasetName"; //临时数据源 DatasourceConnectionInfo tempInfo = new DatasourceConnectionInfo(); //设置数据源连接的引擎类型 tempInfo.EngineType = EngineType.UDB; tempInfo.Alias = targetDatasetName; tempInfo.Server = filePath; // 创建/打开数据库数据源 Datasource tempDatasource = workspace.Datasources.Create(tempInfo); Recordset recordset = null, tempRecordset = null; if (tempDatasource != null) { ImportResult result = ImportShpToTemp(shapeFieldName, tempDatasource, targetDatasetName); if (result.FailedSettings.Length == 0) { try { for (int index = 0; index < tempDatasource.Datasets.Count; index++) { DatasetVector tempDatasetVector = (DatasetVector)tempDatasource.Datasets[index]; tempRecordset = tempDatasetVector.GetRecordset(false, SuperMap.Data.CursorType.Dynamic); //没有数据 if (tempRecordset.RecordCount == 0) { continue; } var tempFieldInfos = tempDatasetVector.FieldInfos; tempRecordset.MoveFirst(); //遍历记录集 for (Int32 i = 0; i < tempRecordset.RecordCount; i++) { Geometry geometry = tempRecordset.GetGeometry(); if (convertDataEnum == ConvertDataEnum.ToGeoJSON) { var geoJSONTxt = Toolkit.GeometryToGeoJson(geometry); var dic = $"{Directory.GetCurrentDirectory()}\\geoJSON"; if (!Directory.Exists(dic)) { Directory.CreateDirectory(dic); } var geoJSONFilePath = $"{dic}\\{i}.txt"; System.IO.File.WriteAllText(geoJSONFilePath, geoJSONTxt); } else if (convertDataEnum == ConvertDataEnum.ToWKB) { var bytes = Toolkit.GeometryToWKB(geometry); } else if (convertDataEnum == ConvertDataEnum.ToWKT) { var wktTxt = Toolkit.GeometryToWKT(geometry); var dic = $"{Directory.GetCurrentDirectory()}\\WKT"; if (!Directory.Exists(dic)) { Directory.CreateDirectory(dic); } var wktFilePath = $"{dic}\\{i}.txt"; System.IO.File.WriteAllText(wktFilePath, wktTxt); } tempRecordset.MoveNext(); } } } catch (Exception ex) { throw ex; } finally { //示例程序BatchAdd说明要释放记录集 if (recordset != null) { recordset.Dispose(); } if (tempRecordset != null) { tempRecordset.Dispose(); } // 释放工作空间资源 info.Dispose(); workspace.Dispose(); //GC.Collect(); foreach (var file in files) { if (File.Exists(file)) { File.Delete(file); } } } } else { throw new Exception($"导入{shapeFieldName}失败!"); } } }
public static Recordset GetRecordSet(DataGridView dataGridView) { //string mthdNamespace = "ReportsLibrary.DGVRecordSet.GetRecordSet"; if (dataGridView == null) { //Logging.LogEvent("ArgumentNull", mthdNamespace, new List<Logging.Arguments> { new Logging.Arguments() { ArgumentName = "dataGridView", ArgumentValue = "Null" } }); return(null); } try { Recordset result = new Recordset(); result.CursorLocation = CursorLocationEnum.adUseClient; Fields resultFields = result.Fields; DataGridViewColumnCollection iColumns = dataGridView.Columns; foreach (DataGridViewColumn iColumn in iColumns) { if (iColumn.Visible == true) { DataTypeEnum fieldType = TranslateType(iColumn.ValueType); if (fieldType == DataTypeEnum.adVarChar) { resultFields.Append(iColumn.HeaderText, fieldType, 300); } else { iColumn.HeaderText = iColumn.HeaderText == "" ? "{Empty}" : iColumn.HeaderText; resultFields.Append(iColumn.HeaderText, fieldType); } } } result.Open(); foreach (DataGridViewRow iRow in dataGridView.Rows) { result.AddNew(); foreach (DataGridViewColumn iColumn in dataGridView.Columns) { if (iColumn.Visible == true) { if (iRow.Cells[iColumn.Index].Value == null) { if (iColumn.ValueType == typeof(String)) { iRow.Cells[iColumn.Index].Value = ""; } if (iColumn.ValueType == typeof(Boolean)) { iRow.Cells[iColumn.Index].Value = false; } } if (iRow.Cells[iColumn.Index].Value.GetType() == typeof(DBNull)) { if (iColumn.ValueType == typeof(String)) { iRow.Cells[iColumn.Index].Value = ""; } if (iColumn.ValueType == typeof(Boolean)) { iRow.Cells[iColumn.Index].Value = false; } } resultFields[iColumn.HeaderText].Value = iRow.Cells[iColumn.Index].Value; } } } if (!result.BOF) { result.MoveFirst(); } return(result); } catch (Exception ex) { //MessageBox.Show("Message: " + ex.Message + "\nStackTrace: " + Logging.StackTraceToString(ex), "Exception"); //Logging.LogException(ex); return(null); } }
/// <summary> /// Method to check of the Vegetation management PlotTemplate in Workspace. /// </summary> /// <param name="p_vegMngSheetTemp">Name of the copy of the Vegetation management HTML sheet template</param> /// <param name="p_newTreeTrimmingfeature">Current placed feature</param> public void CreateVegetationManagementPlotTemplateCopy(string p_vegMngSheetTemp, IGTKeyObject p_newTreeTrimmingfeature) { string plotTemplateName = null; Recordset rs = null; bool found = false; IGTNamedPlot template = null; try { rs = m_oGTApplication.DataContext.OpenRecordset("select PARAM_VALUE from sys_generalparameter where PARAM_NAME='VegMgmtEstimate_Plot'", CursorTypeEnum.adOpenStatic, LockTypeEnum.adLockReadOnly, (int)CommandTypeEnum.adCmdText); if (rs != null && rs.RecordCount > 0) { rs.MoveFirst(); plotTemplateName = Convert.ToString(rs.Fields["PARAM_VALUE"].Value); IGTNamedPlots npcollection = m_oGTApplication.NamedPlots; if (npcollection != null) { if (npcollection.Count > 0) { foreach (IGTNamedPlot np in npcollection) { if (np.Name == plotTemplateName) { template = np; found = true; break; } } } } if (!found) { DialogResult result = MessageBox.Show(m_oGTApplication.ApplicationWindow, "Unable to generate plot; missing template " + plotTemplateName + ". Send anyway? ", "G /Technology", MessageBoxButtons.OKCancel, MessageBoxIcon.Question); switch (result) { case DialogResult.OK: { break; } case DialogResult.Cancel: { m_oUserCancelRequest = true; if (!String.IsNullOrEmpty(p_vegMngSheetTemp)) { File.Delete(p_vegMngSheetTemp); } break; } } } else { CreatePlotWindowAndPlotPDF(template, p_newTreeTrimmingfeature); } } } catch (Exception) { m_oUserCancelRequest = true; throw; } }
private void btnExport_Click(object sender, EventArgs e) { try { SaveFileDialog saveFile = new SaveFileDialog { Filter = "Excel文件|*.xlsx", AddExtension = true, InitialDirectory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop), OverwritePrompt = true, }; if (saveFile.ShowDialog() == DialogResult.OK) { DataSet ds = new DataSet(); DataTable dt = new DataTable { TableName = "重大危险源" }; Recordset objRt = null; try { objRt = (m_Application.Workspace.Datasources["Resource"].Datasets["DangerResource"] as DatasetVector).GetRecordset(false, CursorType.Static); foreach (FieldInfo info in objRt.GetFieldInfos()) { if (info.Name.ToLower().Contains("sm")) { continue; } dt.Columns.Add(new DataColumn { ColumnName = info.Name, Caption = info.Caption }); } objRt.MoveFirst(); while (!objRt.IsEOF) { DataRow row = dt.NewRow(); for (int i = 0; i < dt.Columns.Count; i++) { row[i] = objRt.GetFieldValue(dt.Columns[i].ColumnName); } dt.Rows.Add(row); objRt.MoveNext(); } } catch (Exception ex) { Log.OutputBox(ex); } finally { if (objRt != null) { objRt.Close(); objRt.Dispose(); } } ds.Tables.Add(dt); ExcelHelper excel = new ExcelHelper(); if (excel.ToFile(ds, saveFile.FileName)) { m_Application.MessageBox.Show("数据导出成功!若提示文件损坏,请尝试修复。"); } else { m_Application.MessageBox.Show("数据导出失败!"); } } } catch (Exception ex) { Log.OutputBox(ex); } }
/// <summary> /// Method to re-own child features to replaced feature /// </summary> private void ReOwnToNewFeatureAndSetActivity() { try { if (m_childFeatureInfoList != null) { string structureId = Convert.ToString(oFeatureCreator.m_newFeature.Components.GetComponent(1).Recordset.Fields["STRUCTURE_ID"].Value); foreach (ChildFeatureInfo info in m_childFeatureInfoList) { IGTKeyObject childKeyObject = m_dataContext.OpenFeature(info.GtKeyObject.FNO, info.GtKeyObject.FID); Recordset tempRs = childKeyObject.Components.GetComponent(1).Recordset; tempRs.MoveFirst(); if (info.Owner1IdExists) { tempRs.Fields["OWNER1_ID"].Value = oFeatureCreator.m_newG3eId; } else if (info.Owner2IdExists) { tempRs.Fields["OWNER2_ID"].Value = oFeatureCreator.m_newG3eId; } // ALM-1993-ONCORDEV-2572 - Update same structure id to each of the non-linear child features if (!IsActiveFeatureIsLinear(info.GtKeyObject.FNO)) { tempRs.Fields["STRUCTURE_ID"].Value = structureId; } tempRs.Update(Type.Missing, Type.Missing); } // Set activity foreach (ChildFeatureInfo info in m_childFeatureInfoList) { if (info.GtKeyObject.Components.GetComponent(21) != null) { Recordset rs = info.GtKeyObject.Components.GetComponent(21).Recordset; if (rs != null && rs.RecordCount > 0) { rs.MoveFirst(); } if (oHelper.CheckForCorrectionModeProperty() || m_jobType == "WR-MAPCOR") { while (!rs.EOF) { rs.Fields["ACTIVITY_C"].Value = "TC"; rs.MoveNext(); } } else { while (!rs.EOF) { rs.Fields["ACTIVITY_C"].Value = "T"; rs.MoveNext(); } } } if (info.GtKeyObject.Components.GetComponent(22) != null) { Recordset rs1 = info.GtKeyObject.Components.GetComponent(22).Recordset; if (rs1 != null && rs1.RecordCount > 0) { rs1.MoveFirst(); } if (oHelper.CheckForCorrectionModeProperty() || m_jobType == "WR-MAPCOR") { while (!rs1.EOF) { if (Convert.ToString(rs1.Fields["RETIREMENT_C"].Value).Equals("1") || Convert.ToString(rs1.Fields["RETIREMENT_C"].Value).Equals("2")) { rs1.Fields["ACTIVITY_C"].Value = "TC"; } rs1.MoveNext(); } } else { while (!rs1.EOF) { if (Convert.ToString(rs1.Fields["RETIREMENT_C"].Value).Equals("1") || Convert.ToString(rs1.Fields["RETIREMENT_C"].Value).Equals("2")) { rs1.Fields["ACTIVITY_C"].Value = "T"; } rs1.MoveNext(); } } } } } } catch (Exception) { m_TransactionManager.Rollback(); throw; } }
private void CopyValuesFromBoundaries(Recordset premiseAttributesRs) { short fNo = 0; int fId = 0; string city = string.Empty; string county = string.Empty; string zipCode = string.Empty; string insideCityLimits = string.Empty; string tmpQry = string.Empty; try { short cityFNO = Convert.ToInt16(m_Arguments.GetArgument(0)); int cityANO = Convert.ToInt32(m_Arguments.GetArgument(1)); short countyFNO = Convert.ToInt16(m_Arguments.GetArgument(2)); int countyANO = Convert.ToInt32(m_Arguments.GetArgument(3)); short zipFNO = Convert.ToInt16(m_Arguments.GetArgument(4)); int zipANO = Convert.ToInt32(m_Arguments.GetArgument(5)); Recordset commonComponentRs = Components.GetComponent(1).Recordset; if (commonComponentRs != null && commonComponentRs.RecordCount > 0) { commonComponentRs.MoveFirst(); fNo = Convert.ToInt16(commonComponentRs.Fields["G3E_FNO"].Value); fId = Convert.ToInt32(commonComponentRs.Fields["G3E_FID"].Value); } short primaryGraphicCno = GetPrimaryGraphicCno(fNo); if (primaryGraphicCno == 0) { return; } IGTKeyObject servicePointFeature = m_DataContext.OpenFeature(fNo, fId); IGTOrientedPointGeometry geometry = (IGTOrientedPointGeometry)servicePointFeature.Components.GetComponent(primaryGraphicCno).Geometry; if (geometry == null) { return; } IGTPoint point = GTClassFactory.Create <IGTPoint>(); point.X = geometry.FirstPoint.X; point.Y = geometry.FirstPoint.Y; // City customBoundaryQuery objCustomBoundaryQuery = new customBoundaryQuery(point, cityFNO); Recordset rs = objCustomBoundaryQuery.PerformPointInPolygon(); if (rs != null && rs.RecordCount > 0) { IGTKeyObject cityFeature = DataContext.OpenFeature(Convert.ToInt16(rs.Fields["G3E_FNO"].Value), Convert.ToInt32(rs.Fields["G3E_FID"].Value)); Recordset tempRs = m_DataContext.MetadataRecordset("G3E_ATTRIBUTEINFO_OPTABLE", "G3E_ANO = " + cityANO); if (tempRs != null && tempRs.RecordCount > 0) { tempRs.MoveFirst(); string field = Convert.ToString(tempRs.Fields["G3E_FIELD"].Value); short cno = 0; if (!string.IsNullOrEmpty(Convert.ToString(tempRs.Fields["G3E_CNO"].Value))) { cno = Convert.ToInt16(tempRs.Fields["G3E_CNO"].Value); } if (!string.IsNullOrEmpty(field)) { if ((string.IsNullOrEmpty(Convert.ToString(premiseAttributesRs.Fields["CITY_C"].Value))) && cno > 0) { Recordset cityRs = cityFeature.Components.GetComponent(cno).Recordset; if (cityRs != null && cityRs.RecordCount > 0) { cityRs.MoveFirst(); city = Convert.ToString(cityRs.Fields[field].Value); } if (!string.IsNullOrEmpty(city)) { //premiseAttributesRs.Fields["CITY_C"].Value = city; m_City = city; //premiseAttributesRs.Fields["INSIDE_CITY_LIMITS_YN"].Value = "Y"; m_CityLimits = "Y"; } } } } } // County objCustomBoundaryQuery = new customBoundaryQuery(point, countyFNO); Recordset rs1 = objCustomBoundaryQuery.PerformPointInPolygon(); if (rs1 != null && rs1.RecordCount > 0) { IGTKeyObject countyFeature = DataContext.OpenFeature(Convert.ToInt16(rs1.Fields["G3E_FNO"].Value), Convert.ToInt32(rs1.Fields["G3E_FID"].Value)); Recordset tempRs1 = m_DataContext.MetadataRecordset("G3E_ATTRIBUTEINFO_OPTABLE", "G3E_ANO = " + countyANO); if (tempRs1 != null && tempRs1.RecordCount > 0) { tempRs1.MoveFirst(); string field = Convert.ToString(tempRs1.Fields["G3E_FIELD"].Value); short cno = 0; if (!string.IsNullOrEmpty(Convert.ToString(tempRs1.Fields["G3E_CNO"].Value))) { cno = Convert.ToInt16(tempRs1.Fields["G3E_CNO"].Value); } if (!string.IsNullOrEmpty(field)) { if ((string.IsNullOrEmpty(Convert.ToString(premiseAttributesRs.Fields["COUNTY_C"].Value))) && cno > 0) { Recordset countyRs = countyFeature.Components.GetComponent(cno).Recordset; if (countyRs != null && countyRs.RecordCount > 0) { countyRs.MoveFirst(); county = Convert.ToString(countyRs.Fields[field].Value); } if (!string.IsNullOrEmpty(county)) { //premiseAttributesRs.Fields["COUNTY_C"].Value = county; m_CountyCode = county; } } } } } // Zip Code objCustomBoundaryQuery = new customBoundaryQuery(point, zipFNO); Recordset rs2 = objCustomBoundaryQuery.PerformPointInPolygon(); if (rs2 != null && rs2.RecordCount > 0) { IGTKeyObject zipCodeFeature = DataContext.OpenFeature(Convert.ToInt16(rs2.Fields["G3E_FNO"].Value), Convert.ToInt32(rs2.Fields["G3E_FID"].Value)); Recordset tempRs2 = m_DataContext.MetadataRecordset("G3E_ATTRIBUTEINFO_OPTABLE", "G3E_ANO = " + zipANO); if (tempRs2 != null && tempRs2.RecordCount > 0) { tempRs2.MoveFirst(); string field = Convert.ToString(tempRs2.Fields["G3E_FIELD"].Value); short cno = 0; if (!string.IsNullOrEmpty(Convert.ToString(tempRs2.Fields["G3E_CNO"].Value))) { cno = Convert.ToInt16(tempRs2.Fields["G3E_CNO"].Value); } if (!string.IsNullOrEmpty(field)) { if ((string.IsNullOrEmpty(Convert.ToString(premiseAttributesRs.Fields["ZIP_C"].Value))) && cno > 0) { Recordset zipRs = zipCodeFeature.Components.GetComponent(cno).Recordset; if (zipRs != null && zipRs.RecordCount > 0) { zipRs.MoveFirst(); zipCode = Convert.ToString(zipRs.Fields[field].Value); } if (!string.IsNullOrEmpty(zipCode)) { //premiseAttributesRs.Fields["ZIP_C"].Value = zipCode; m_ZipCode = zipCode; } } } } try { premiseAttributesRs.Fields["CITY_C"].Value = m_City; premiseAttributesRs.Fields["INSIDE_CITY_LIMITS_YN"].Value = m_CityLimits; premiseAttributesRs.Fields["COUNTY_C"].Value = m_CountyCode; premiseAttributesRs.Fields["ZIP_C"].Value = m_ZipCode; } catch (Exception ex) { if (ex.Message == "Operation was canceled.") { int tmpRecModified = 0; tmpQry = "begin update premise_n set CITY_C = '" + m_City + "', INSIDE_CITY_LIMITS_YN = '" + m_CityLimits + "', COUNTY_C = '" + m_CountyCode + "', ZIP_C = '" + m_ZipCode + "' where g3e_fid = " + premiseAttributesRs.Fields["G3E_FID"].Value.ToString() + " and g3e_cid = " + premiseAttributesRs.Fields["G3E_CID"].Value.ToString() + "; end;"; m_DataContext.Execute(tmpQry, out tmpRecModified, (int)CommandTypeEnum.adCmdText); } else { throw; } } } } catch (Exception) { throw; } }
protected ADODB.Recordset ExecuteIntoRecordset(string sql, IDbConnection cn) { Recordset oRS = new Recordset(); IDataReader reader = null; try { IDbCommand command = cn.CreateCommand(); command.CommandText = sql; command.CommandType = CommandType.Text; reader = command.ExecuteReader(); DataTable schema; string dataType, fieldname; int length; bool firstTime = true; // Skip columns contains the index of any columns that we cannot handle, array types and such ... Hashtable skipColumns = null; while (reader.Read()) { if (firstTime) { skipColumns = new Hashtable(); schema = reader.GetSchemaTable(); int colID = 0; foreach (DataRow row in schema.Rows) { fieldname = row["ColumnName"].ToString(); dataType = row["DataType"].ToString(); length = Convert.ToInt32(row["ColumnSize"]); try { oRS.Fields.Append(fieldname, GetADOType(dataType), length, FieldAttributeEnum.adFldIsNullable, System.Reflection.Missing.Value); } catch { // We can't handle this column type, ie, Firebird array types skipColumns[colID] = colID; } colID++; } oRS.Open(System.Reflection.Missing.Value, System.Reflection.Missing.Value, CursorTypeEnum.adOpenStatic, LockTypeEnum.adLockOptimistic, 1); firstTime = false; } oRS.AddNew(System.Reflection.Missing.Value, System.Reflection.Missing.Value); for(int i = 0, j = 0; i < reader.FieldCount; i++) { // Skip columns that we cannot handle if(!skipColumns.ContainsKey(i)) { if (reader[j] is System.Guid) { oRS.Fields[j].Value = "{" + reader[j].ToString() + "}"; } else { try { oRS.Fields[j].Value = reader[j]; } catch { // For some reason it wouldn't accept this value? oRS.Fields[j].Value = DBNull.Value; } } j++; } } } cn.Close(); //Move to the first record if (!firstTime) { oRS.MoveFirst(); } else { oRS = null; } } catch (Exception ex) { if ((reader != null) && (!reader.IsClosed)) { reader.Close(); reader = null; } if ((cn != null) && (cn.State == ConnectionState.Open)) { cn.Close(); cn = null; } throw ex; } return oRS; }