public static Field getFieldByPos(HL7Message message, SegmentType segmentType, int position, int segmentOrder = -1) { Field f = new Field(); List <Segment> segments = new List <Segment>(); try { if (segmentOrder == NEG_ONE) { segments = message.segments.FindAll(x => x.segmentType == segmentType); } else { segments = message.segments.FindAll(x => x.segmentType == segmentType && x.fields[FIRST_ELEMENT].value == segmentOrder.ToString()); } int fieldIndex = NEG_ONE; foreach (Segment s in segments) { if (fieldIndex == NEG_ONE) { fieldIndex = s.fields.FindIndex(x => x.position == position); // adding to avoid bad locations if (fieldIndex == NEG_ONE && segmentType == SegmentType.PV1 && position == 11) { // build empty location f = HL7MessageUtility.getEmptyLocationNotFound(); } else { f = s.fields[fieldIndex]; } } } } catch (Exception e) { List <string> parameters = new List <string>(); parameters.Add(message.segments.Count.ToString()); parameters.Add(segmentType.ToString()); parameters.Add(position.ToString()); parameters.Add(segmentOrder.ToString()); ErrorLogger.LogError(e, "Field.getFieldByPos(HL7Message message, SegmentType segmentType, int position, int segmentOrder = -1)" , String.Join(Generic.PIPE.ToString(), parameters.ToArray())); } return(f); }
public void onDebugStartWithMessage() { string path = @"C:\Users\chrisb\Documents\ApplicationDevelopment\Working\HL7Broker.root\HL7Broker\HL7Broker\Messages\ORMSC_LOCATION.hl7"; string input = HL7Message.ReadHL7FromFile(path); // attempt to scrub message string hl7Input = HL7MessageUtility.scrubHL7MessageForParse(input); // Get Incoming HL7 Message Configuration HL7Message hl7Message = HL7MessageDAO.getMessage(hl7Input); string value = HL7MessageUtility.getValueByPosition(hl7Message, Generic.SegmentType.PV1, "11.2"); }
public static void handleIncomingHL7MessageToBroker(string hl7Input, Communication interfaceCommunication, HL7Broker.Model.Socket socket) { // attempt to scrub message hl7Input = HL7MessageUtility.scrubHL7MessageForParse(hl7Input); // Get Incoming HL7 Message Configuration HL7Message hl7Message = HL7MessageDAO.getMessage(hl7Input); // if the message is not null if (hl7Message != null) { // set the hl7 message to the socket object socket.setHL7Message(hl7Message); } }
public static void handleAckForService(HL7Message hl7Message, Message message, string ackResponseMessage) { // get the message control id to build the ack string messageControlId = HL7MessageUtility.getValueByPosition(hl7Message, SegmentType.MSH, MESSAGE_HEADER_CONTROL_ID); // get the message date stamp string messageDateStamp = HL7MessageUtility.getValueByPosition(hl7Message, SegmentType.MSH, MESSAGE_DATE_STAMP_POSITION); // get the correct ack response bool isRejected = ShieldsExpressLinkUtility.handleCheckApplicationRejected(ackResponseMessage); // if the ack message is rejected, apply act type AcknowledgementDAO.AcknowledgementType ackMessageEnum = (isRejected) ? AcknowledgementDAO.AcknowledgementType.AR: AcknowledgementDAO.AcknowledgementType.AA; // get ack response string strAckResponse = HL7MessageUtility.getAck(ackMessageEnum.ToString(), messageControlId, messageDateStamp, MESSAGE_HEADER_APPLICATION_NAME, MESSAGE_HEADER_FACILITY_NAME, ackResponseMessage); // build ack response Acknowledgement ackResponse = new Acknowledgement() { acknowledgementTypeId = (int)ackMessageEnum, messageId = message.id, raw = strAckResponse, createdDttm = DateTime.Now }; // insert into ack AcknowledgementDAO.insertIntoAcknowledgement(ackResponse); }
public static void Parse(HL7Message hl7Message, string hl7Input) { try { List <string> delimitedResult = hl7Input.Split(Convert.ToChar(CR)).ToList(); foreach (string segment in delimitedResult) { Segment s = new Segment(); s.Parse(segment); hl7Message.segments.Add(s); } // get the message type after you've processed the message hl7Message.messageType = HL7MessageUtility.getMessageType(hl7Message, hl7Input); } catch (Exception e) { ErrorLogger.LogError(e, "HL7Message.Parse(HL7Message hl7Message, string hl7Input)", hl7Input); } }
public static void handleOutgoingHL7MessageToBrokerV1(string hl7Input, Communication databaseCommunication, HL7Broker.Model.Socket socket) { Dictionary <int, int> databaseTableRelationDictionary = new Dictionary <int, int>(); // get all database table relations List <DatabaseTableRelation> relations = DatabaseTableRelationDAO.Get(); // this identity is used for multiple inserts int identityNo = -1; // text string baseCommandText = BLANK; string tableName = BLANK; // these will help build the custom query List <string> columns = new List <string>(); List <string> columnValues = new List <string>(); // get message HL7Message hl7Message = socket.getHL7Message(); // get configurations for the database comminucation List <Configuration> configurations = ConfigurationDAO.GetDatabaseConfiguration(databaseCommunication); // get the credential Credential credential = configurations[ZERO_ELEMENT].credential; // get the database instance DatabaseInstance databaseInstance = configurations[ZERO_ELEMENT].databaseInstance; // build the connection string string connectionString = DAOUtility.GetConnectionString(credential, databaseInstance, true); // build database query to insert data into tables based on configuration using (SqlConnection connection = new SqlConnection(connectionString)) { try { // get a list of databses tables List <Configuration> configDatabaseTables = ConfigurationDAO.GetDatabaseTables(databaseInstance); // pick up all the tables for the config configDatabaseTables.ForEach(delegate(Configuration tableConfig) { // empty the db value string dbValue = BLANK; // reset variables baseCommandText = BLANK; // empty the stores columns.Clear(); columnValues.Clear(); SqlCommand command = new SqlCommand(); // set the database table DatabaseTable table = tableConfig.databaseTable; // init database table relation DatabaseTableRelation databaseTableRelation = tableConfig.databaseTableRelation; // based on the table instance id , get the column set List <Configuration> configDatabaseColumns = ConfigurationDAO.GetDatabaseColumns(table); // set the table name tableName = table.name; // for each column, get the column name configDatabaseColumns.ForEach(delegate(Configuration configColumn) { // set the column ColumnSet column = configColumn.columnSet; // get the data type to use SqlDbType sqlDbType = DAOUtility.GetSqlDataType(column.columnDataType); // if it's 0, there must be some special condition here, such as a primary key or handling a specific data type if (column.messageGroupInstanceId == ZERO && column.columnDataType == INTEGER_TYPE) { // if the source table does have a relationship, then we need to get it if (relations.Count(x => x.sourceDatabaseTableId == table.id) > ZERO) { if (column.isPrimaryKey) { // do something here int keyValue = -1; // get the target table based on the source table int targetTableId = relations.Find(r => r.sourceDatabaseTableId == table.id).targetDatabaseTableId; // get the identity databaseTableRelationDictionary.TryGetValue(targetTableId, out keyValue); // set the keyvalue to the db value dbValue = keyValue.ToString(); } else { // Throw Error - there is an issue if the column value is of interger type but no // key is assoicated it it. } } } // if this isn't bound to a column and it's of type text - then it should ALWAYS be an HL7 Message else if (column.messageGroupInstanceId == ZERO && column.columnDataType == TEXT_TYPE) { // apply hl7 message dbValue = hl7Input; } // database column is of current date type, so we set the value to the current date time else if (column.messageGroupInstanceId == ZERO && column.columnDataType == DATE_TYPE) { // set the value to the current date time dbValue = DateTime.Now.ToString(); } // search for it by hl7 position else { // init a message group instance MessageGroupInstance messageGroupInstance = new MessageGroupInstance() { id = column.messageGroupInstanceId }; // reset the message group instance configColumn.messageGroupInstance = messageGroupInstance; // get the message position for this specific column List <Configuration> configMessagePoisition = ConfigurationDAO.GetMessagePosition(configColumn.messageGroupInstance); // get the coordinates for the message item string messageCoordinates = HL7MessageUtility.getItemCoordinates(configMessagePoisition); // get segment string type string columnSegment = configMessagePoisition[ZERO_ELEMENT].segmentType.name; // get the value for the database inside of the value position string hl7Value = HL7MessageUtility.getValueByPosition( hl7Message, HL7MessageUtility.getSegmentType(columnSegment), messageCoordinates); // generate the value dbValue = (!String.IsNullOrEmpty(hl7Value) ? hl7Value : DBNull.Value.ToString()); } // initialize for each new table baseCommandText = DAOUtility.GetBaseQuery(DAOUtility.SERVICE_QUERY_TYPE.INSERT); // add to columns statement columns.Add(column.name); // add to values statement columnValues.Add(AT_SIGN + column.name); // set the command string command.Parameters.Add(AT_SIGN + column.name, sqlDbType); // set the values command.Parameters[AT_SIGN + column.name].Value = dbValue; }); // open the connection connection.Open(); // grab command text command.CommandText = DAOUtility.GetStatement(DAOUtility.SERVICE_QUERY_TYPE.INSERT, baseCommandText, tableName, columns, columnValues); // make new transaction to allow roll back SqlTransaction transaction = connection.BeginTransaction(); // initialize the connection command.Connection = connection; // initialize the transaction command.Transaction = transaction; // handle the database insert for message header instance handleDatabaseTableCaller(connection, command, transaction, hl7Message, table, hl7Input, socket, out identityNo); // if the "database table has dependencies" - store the relation id w/ the table id if (databaseTableRelation.id != ZERO) { // or in better terms - has a dependency that this ide requires if (databaseTableRelation.requiresIdentity) { // add to the dictionary if it does require depdents databaseTableRelationDictionary.Add(table.id, identityNo); } else { // reset if it doesn't need it identityNo = NEG_ONE; } } }); } catch (SqlException sqlex) { ErrorLogger.LogError(sqlex, "handleOutgoingHL7MessageToBroker()", hl7Input); connection.Close(); } } }
public static MessageLogDAO.MessageLogType handleAcknowledgement(HL7Message hl7Message, string hl7Input, int messageIdentity, HL7Broker.Model.Socket socket) { string ackResponseMessage = BLANK; AcknowledgementDAO.AcknowledgementType ackType = AcknowledgementDAO.AcknowledgementType.UNKNOWN; MessageLogDAO.MessageLogType logType = MessageLogDAO.MessageLogType.UNKNOWN; if (messageIdentity == NEG_ONE) { // swap it to 9999 so we don't insert a neg value messageIdentity = ERROR_CODE_NINE; ackType = AcknowledgementDAO.AcknowledgementType.AE; ackResponseMessage = ERROR_MESSAGE_FROM_BROKER; } else if (messageIdentity == ZERO) { ackType = AcknowledgementDAO.AcknowledgementType.AR; ackResponseMessage = ERROR_MESSAGE_REJECTED; } else { ackType = AcknowledgementDAO.AcknowledgementType.AA; ackResponseMessage = MESSAGE_NO_ERROR; } // get the message control id to build the ack string messageControlId = HL7MessageUtility.getValueByPosition(hl7Message, SegmentType.MSH, MESSAGE_HEADER_CONTROL_ID); string messageDateStamp = HL7MessageUtility.getValueByPosition(hl7Message, SegmentType.MSH, MESSAGE_DATE_STAMP_POSITION); // get ack response string strAckResponse = HL7MessageUtility.getAck(ackType.ToString(), messageControlId, messageDateStamp, MESSAGE_HEADER_APPLICATION_NAME, MESSAGE_HEADER_FACILITY_NAME, ackResponseMessage); try { // build ack response Acknowledgement ackResponse = new Acknowledgement() { id = NEG_ONE, acknowledgementTypeId = (int)ackType, messageId = messageIdentity, raw = strAckResponse, createdDttm = DateTime.Now }; // insert into the acknowledgement ackResponse = AcknowledgementDAO.insertIntoAcknowledgement(ackResponse); logType = (ackResponse.id != NEG_ONE) ? MessageLogDAO.MessageLogType.ORIGINAL : MessageLogDAO.MessageLogType.ERRORED; // get the network stream to send the ack back NetworkStream stream = socket.getNetworkStream(); // pad the hl7 msesage for transfer strAckResponse = HL7MessageUtility.padHL7MessageForTransfer(strAckResponse); stream.Write(Encoding.UTF8.GetBytes(strAckResponse), 0, strAckResponse.Length); } catch (Exception e) { ErrorLogger.LogError(e, "handleAcknowledgement()", messageControlId); } // send the ack message // return the type of log we are submitting return(logType); }
public static void handleProcessingForOutboundHandler(Configuration masterConfig, OutboundHandler outboundHandler) { // to control some basic CPU handling settings Config outboundConfig = new Config(); // load each of the configurations into their own objects List <Application> applications = masterConfig.applications; List <Communication> communications = masterConfig.communications; List <WebserviceObject> webserviceObjects = masterConfig.webserviceObjects; List <WebserviceInstance> webserviceInstances = masterConfig.webserviceInstances; List <WebservicePropertySet> webserviceProperties = masterConfig.webservicePropertySets; List <MessageGroup> messageGroups = masterConfig.messageGroups; List <MessageGroupInstance> messageGroupInstances = masterConfig.messageGroupInstances; // continue to read the table while (true) { applications.ForEach(delegate(Application app) { if (app.name == outboundHandler.getApplicationName()) { // get the unprocessed message count for the application List <MessageBucket> brokerInformation = MessageBucketDAO.GetUnprocessedMessageHeaderInstancesByApplication(app); // set the MOD from config file. var options = new ParallelOptions { MaxDegreeOfParallelism = outboundConfig.MaxDegreeOfParallelism }; // parallel For each Parallel.ForEach(brokerInformation, options, broker => { // get the message header and message MessageHeaderInstance messageHeaderInstance = broker.messageHeaderInstance; Message message = broker.message; // srub the input of bad stuff string hl7Scrubbed = HL7MessageUtility.scrubHL7MessageForParse(message.hl7Raw); // make the hl7 message HL7Message hl7Message = HL7MessageDAO.getMessage(hl7Scrubbed); // locally retrieve the communication object from memory Communication communication = ConfigurationUtility.GetIncomingWebserviceCommunication(app, communications); // locally retrieve the webservice instance object from memory WebserviceInstance webserviceInstance = ConfigurationUtility.GetIncomingWebserviceInstance(communication, webserviceInstances); // locally retrieve the web service objects from memory List <WebserviceObject> wsObjects = ConfigurationUtility.GetIncomingWebserviceObjects(webserviceInstance, webserviceObjects); // determine the message type Generic.MessageType messageType = HL7MessageUtility.getMessageType(hl7Message, hl7Scrubbed); switch (messageType) { // to handle a new message add message type then its own handler case Generic.MessageType.ADT: break; case Generic.MessageType.ORM: handleProcessingForORM(wsObjects, webserviceProperties, hl7Message, messageGroupInstances, messageGroups, app, message); break; case Generic.MessageType.ORU: handleProcessingForORU(wsObjects, webserviceProperties, hl7Message, messageGroupInstances, messageGroups, app, message); break; case Generic.MessageType.SIU: break; case Generic.MessageType.UNKNOWN: break; default: break; } // update the table to processed MessageBucketDAO.UpdateProcessedFlagAndMessageLog(messageHeaderInstance, message, true); // update broker stats handleBrokerStatUpdate(message, communication); }); } }); // provide blocking if there is no data to process. Thread.Sleep(1000); } }
private void run() { // create bye buffer the size of the input Byte[] buffer = new Byte[MAX_MESSAGE_SIZE]; // set connected here TcpClient tcpClient = this.tcpListener.AcceptTcpClient(); if (tcpClient.Connected) { if (this.broker.interfaceStatusId != BrokerDAO.CONNECTED) { // update interface broker status to connected since we are connected this.broker.interfaceStatusId = BrokerDAO.CONNECTED; // set worklist to waiting BrokerDAO.UpdateAppBrokerProperty(this.broker, BrokerDAO.Property.Status); } } else { startWaiting(); } // get the data String data = null; // get the network stream this.networkStream = tcpClient.GetStream(); // define stream byte index int byteIndex = 0; try { // define stream byte index // Loop to receive all the data sent by the client. while ((byteIndex = this.networkStream.Read(buffer, 0, buffer.Length)) != 0) { // Translate data bytes to a ASCII string. data = System.Text.Encoding.UTF8.GetString(buffer, 0, byteIndex); // if for some reason we can't process the message, we'll reject it (hopefully) try { // pass it over to inbound delegate delegate this.incomingHandler(data.ToString(), this.incomingCommunication, this); } catch (Exception e) { // this means we had trouble parsing the message when it came in. string ackRejected = HL7MessageUtility.getAck(AcknowledgementDAO.AcknowledgementType.AR.ToString(), ERROR_CONTROL_ID, DateTime.Now.ToString(), MESSAGE_HEADER_APPLICATION_NAME, MESSAGE_HEADER_FACILITY_NAME, ERROR_MESSAGE_REJECTED); // build ack response AcknowledgementDAO.insertIntoAcknowledgement(new Acknowledgement() { id = NEG_ONE, acknowledgementTypeId = (int)AcknowledgementDAO.AcknowledgementType.AE, messageId = 0, raw = ERROR_MESSAGE_REJECTED, createdDttm = DateTime.Now }); // pad the hl7 msesage for transfer ackRejected = HL7MessageUtility.padHL7MessageForTransfer(ackRejected); // write back this.networkStream.Write(Encoding.UTF8.GetBytes(ackRejected), 0, ackRejected.Length); // move on, don't stop continue; } // pass it over to the outbound delegate this.outgoingdHandler(data.ToString(), this.outgoingCommunication, this); } } catch (Exception ex) { ErrorLogger.LogError(ex, "run()"); } finally { // Shutdown and end connection tcpClient.Close(); // if the user is disconnected - set to waiting startWaiting(); } // Shutdown and end connection tcpClient.Close(); }