示例#1
0
        public async Task Leave(string groupId)
        {
            var existingGroup = chatGroups.FirstOrDefault(x => x.PublicId == groupId);

            if (existingGroup == null)
            {
                await Clients.Caller.SendAsync(receiveMethodName, MessageConstructor.SystemMessage(ErrorMessages.GroupDoesNotExist(groupId)));

                return;
            }

            if (existingGroup.ClientsConnected.FirstOrDefault(x => x == Context.ConnectionId) == null)
            {
                await Clients.Caller.SendAsync(receiveMethodName, MessageConstructor.SystemMessage(ErrorMessages.NotAGroupMember(existingGroup.Name)));

                return;
            }

            existingGroup.ClientsConnected.Remove(Context.ConnectionId);
            if (existingGroup.ClientsConnected.Count == 0)
            {
                chatGroups.Remove(existingGroup);
            }

            var clientName = await _processor.OnGroupLeave(groupId, Context.ConnectionId);

            Task.WaitAll(
                Groups.RemoveFromGroupAsync(Context.ConnectionId, existingGroup.Name),
                Clients.Caller
                .SendAsync(receiveMethodName, MessageConstructor.SystemMessage(InformationMessages.SuccessfullyLeftGroup(existingGroup.Name))),
                Clients.Group(existingGroup.Name)
                .SendAsync(receiveMethodName, MessageConstructor.SystemMessage(InformationMessages.ClientHasLeftGroup(clientName))));
        }
示例#2
0
        TgMessage MapMessage(MessageConstructor message)
        {
            var handler = _mediaHandlersFactory.GetMediaHandler(message.Media.GetType());

            var tgMedia = handler?.Map(message.Media);

            //var image = (Bitmap)new ImageConverter().ConvertFrom(cachedPhoto.bytes);

            var tgMessage = new TgMessage
            {
                Flags       = message.Flags.ToString(),
                Sender      = GetSender(message.FromId),
                Receiver    = GetReceiver(message.ToId),
                Id          = message.Id,
                Date        = TgDateConverter.GetDateTime(message.Date),
                Text        = message.Message,
                ContentType = handler?.TypeHandled.Name,
                Unread      = message.Unread,
                Output      = message.Output
            };


            if (handler == null)
            {
                _logger.Error($"Unable to find handler for media type: {message.Media.GetType()}");
            }

            tgMessage.Media = tgMedia;

            return(tgMessage);
        }
 //*************************************************************
 private void ConnectToServer()
 {
     _Sock               = new TcpClient(Config._Ip, Config._Port.Nvl(0));
     _NetStream          = _Sock.GetStream();
     _MessageConstructor = new MessageConstructor(Config._Ip, _UserName,
                                                  _Password, _SenderCompID, _SenderSubID, _TargetCompID);
 }
示例#4
0
        public void ADTA01Message(string PatientId, string PatientName, string PatientMiddleName, string PatientLastName)
        {
            Message = Leadtools.Medical.HL7.V2x.Models.MessageFactory.New("ADT_A01", "V26");

            {
                ADT_A01 msg = (ADT_A01)Message;
                Leadtools.Medical.HL7.V2x.Models.MessageConstructor.CreateSegments(msg);

                msg.MSH.Field_Separator.Value           = "|";
                msg.MSH.Encoding_Characters.Value       = "^~\\&";
                msg.MSH.Sending_Application.Value       = "LTHL7Demo";
                msg.MSH.Sending_Facility.Value          = "Leadtools";
                msg.MSH.Receiving_Application.Value     = "LTHL7Demo";
                msg.MSH.Receiving_Facility.Value        = "Leadtools";
                msg.MSH.Date_Time_of_Message.Value      = MessageConstructor.CurTime();
                msg.MSH.Message_Type.MessageCode.Value  = "ADT";
                msg.MSH.Message_Type.TriggerEvent.Value = "A01";
                msg.MSH.Message_Control_ID.Value        = UniqueId.New;
                msg.MSH.Processing_ID.Value             = "1";
                msg.MSH.Version_ID.VersionID.Value      = "2.6";

                msg.PID.Patient_ID.IDNumber.Value        = PatientId;
                msg.PID.Patient_Name[0].FamilyName.Value = PatientLastName;
                msg.PID.Patient_Name[0].GivenName.Value  = PatientName;
                msg.PID.Patient_Name[0].SecondAndFurtherGivenNamesOrInitialsThereof.Value = PatientMiddleName;
            }

            Fire(MessageChanged);
        }
示例#5
0
        public State(Socket client)
        {
            WorkSocket   = client;
            OutterBuffer = new List <byte>();

            m_messageManager = new MessageConstructor();
            m_messageManager.LoadDefinitions();
            messageLength = -1;
            TSAP          = -1;
        }
示例#6
0
 public frmFIXAPISample()
 {
     InitializeComponent();
     _priceClient        = new TcpClient(_host, _pricePort);
     _priceStream        = _priceClient.GetStream();
     _tradeClient        = new TcpClient(_host, _tradePort);
     _tradeStream        = _tradeClient.GetStream();
     _messageConstructor = new MessageConstructor(_host, _username,
                                                  _password, _senderCompID, _senderSubID, _targetCompID);
 }
示例#7
0
 /// <summary>
 /// Initializes a new instance of <see cref="BaseNetworkConnector"/> class.
 /// </summary>
 /// <remarks>
 /// Also loads the <see cref="MessageTypeCache"/> on the first <see cref="BaseNetworkConnector"/> instance creation.
 /// </remarks>
 /// <exception cref="ArgumentNullException">If the messageProcessor is null; an argument exception is thrown.</exception>
 /// <param name="messageTypeCache">The message type cache.</param>
 /// <param name="messageSerializer">The message serializer.</param>
 /// <param name="messageProcessor">The message processor.</param>
 /// <param name="logger">The logger.</param>
 protected BaseNetworkConnector(
     IMessageTypeCache messageTypeCache,
     IMessageSerializer messageSerializer,
     IMessageProcessor messageProcessor,
     ILogger <BaseNetworkConnector> logger)
 {
     _messageConstructor = new MessageConstructor(messageSerializer);
     _messageProcessor   = messageProcessor ?? throw new ArgumentNullException(nameof(messageProcessor));
     _messageTypeCache   = messageTypeCache ?? throw new ArgumentNullException(nameof(messageTypeCache));
     Logger = logger;
 }
 public frmFIXAPISample()
 {
     InitializeComponent();
     _priceClient    = new TcpClient(_host, _pricePort);
     _priceStreamSSL = new SslStream(_priceClient.GetStream(), false,
                                     new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
     _priceStreamSSL.AuthenticateAsClient(_host);
     _tradeClient    = new TcpClient(_host, _tradePort);
     _tradeStreamSSL = new SslStream(_tradeClient.GetStream(), false,
                                     new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
     _tradeStreamSSL.AuthenticateAsClient(_host);
     _messageConstructor = new MessageConstructor(_host, _username,
                                                  _password, _senderCompID, _senderSubID, _targetCompID);
 }
示例#9
0
        /// <summary>Helper method to send given appt to the unscheduled list.
        /// Creates SecurityLogs and considers HL7.</summary>
        public static void SetApptUnschedHelper(Appointment appt, Patient pat = null, bool doFireApptEvent = true)
        {
            DateTime datePrevious = appt.DateTStamp;

            Appointments.SetAptStatus(appt, ApptStatus.UnschedList); //Appointments S-Class handles Signalods
            #region SecurityLogs
            if (appt.AptStatus != ApptStatus.Complete)               //seperate log entry for editing completed appts.
            {
                SecurityLogs.MakeLogEntry(Permissions.AppointmentMove, appt.PatNum,
                                          appt.ProcDescript + ", " + appt.AptDateTime.ToString() + ", Sent to Unscheduled List",
                                          appt.AptNum, datePrevious);
            }
            else
            {
                SecurityLogs.MakeLogEntry(Permissions.AppointmentCompleteEdit, appt.PatNum,
                                          appt.ProcDescript + ", " + appt.AptDateTime.ToString() + ", Sent to Unscheduled List",
                                          appt.AptNum, datePrevious);
            }
            #endregion
            #region HL7
            //If there is an existing HL7 def enabled, send a SIU message if there is an outbound SIU message defined
            if (HL7Defs.IsExistingHL7Enabled())
            {
                if (pat == null)
                {
                    pat = Patients.GetPat(appt.PatNum);
                }
                //S15 - Appt Cancellation event
                MessageHL7 messageHL7 = MessageConstructor.GenerateSIU(pat, Patients.GetPat(pat.Guarantor), EventTypeHL7.S15, appt);
                //Will be null if there is no outbound SIU message defined, so do nothing
                if (messageHL7 != null)
                {
                    HL7Msg hl7Msg = new HL7Msg();
                    hl7Msg.AptNum    = appt.AptNum;
                    hl7Msg.HL7Status = HL7MessageStatus.OutPending;                  //it will be marked outSent by the HL7 service.
                    hl7Msg.MsgText   = messageHL7.ToString();
                    hl7Msg.PatNum    = pat.PatNum;
                    HL7Msgs.Insert(hl7Msg);
#if DEBUG
                    MessageBox.Show("Appointments", messageHL7.ToString());
#endif
                }
            }
            #endregion
            if (doFireApptEvent)
            {
                AppointmentEvent.Fire(ODEventType.AppointmentEdited, appt);
            }
            Recalls.SynchScheduledApptFull(appt.PatNum);
        }
示例#10
0
        public async Task Join(string groupId)
        {
            var existingGroup = chatGroups.FirstOrDefault(x => x.PublicId == groupId);

            if (existingGroup == null)
            {
                await Clients.Caller.SendAsync(receiveMethodName, MessageConstructor.SystemMessage(ErrorMessages.GroupDoesNotExist(groupId)));

                return;
            }

            var groupName = existingGroup.Name;

            if (existingGroup.CurrentClientsAmount == existingGroup.MaximumClientsAmount)
            {
                await Clients.Caller.SendAsync(receiveMethodName, MessageConstructor.SystemMessage(InformationMessages.ClientsInGroupLimitReached(groupName, _appConfig.MaximumGroupSize)));

                return;
            }

            if (existingGroup.ClientsConnected.FirstOrDefault(x => x == Context.ConnectionId) != null)
            {
                await Clients.Caller.SendAsync(receiveMethodName, MessageConstructor.SystemMessage(ErrorMessages.AlreadyAGroupMember(groupName)));

                return;
            }
            var groupHistoryToClientDto = await _processor.OnGroupJoin(existingGroup.PublicId, Context.ConnectionId);

            var groupMessage = new GroupMessage
            {
                GroupName = groupName,
                GroupId   = existingGroup.PublicId
            };

            existingGroup.ClientsConnected.Add(Context.ConnectionId);
            var exclutionList = new List <string> {
                Context.ConnectionId
            };

            Task.WaitAll(
                Groups.AddToGroupAsync(Context.ConnectionId, groupName),
                Clients.Caller.SendAsync(receiveMethodName, MessageConstructor.SystemMessage(InformationMessages.SuccessfullyJoinedGroup(groupName))),
                Clients.Caller.SendAsync(GroupMethodNames.OnGroupJoined, groupMessage),
                Clients.Caller.SendAsync(GroupMethodNames.ReceiveGroupHistory, MessageConstructor.GroupMessageHistory(groupHistoryToClientDto)),
                Clients.GroupExcept(groupName, exclutionList)
                .SendAsync(receiveMethodName, MessageConstructor.SystemMessage(InformationMessages.ClientHasJoinedGroup(groupHistoryToClientDto.Client.PublicName))));
        }
示例#11
0
文件: MainForm.cs 项目: PC-Pedia/T2XL
        private async Task AddMessagesToExcel()
        {
            for (int i = 1; i <= Iterations; i++)
            {
                lblWorking.Text = String.Format("Adding messages...x{0}{1}", i, i > 5 ? "\n holy shiit :P" : "");
                var history = await mClient.GetMessages(Enumerable.Range(mStartId, MsgCount).ToList());

                if (history.Count <= 0)
                {
                    break;
                }

                foreach (var msg in history)
                {
                    Type t = msg.GetType();
                    if (t == typeof(MessageServiceConstructor))
                    {
                        continue;
                    }
                    else if (t == typeof(MessageForwardedConstructor))
                    {
                        MessageForwardedConstructor m = (MessageForwardedConstructor)msg;
                        var def           = new SimpleUser(m.fwd_from_id);
                        int fwd_from_user = mUsers.BinarySearch(def);

                        var sm = await ToSimpleMessage(m.id, m.to_id, m.from_id, m.date, m.output,
                                                       Utils.Combine(Utils.Forwarded(m.message, m.fwd_date, fwd_from_user >= 0 ? mUsers[fwd_from_user] : def), m.media));

                        xl.AddMessage(sm);
                    }
                    else if (t == typeof(MessageEmptyConstructor))
                    {
                        continue;
                    }
                    else if (t == typeof(MessageConstructor))
                    {
                        MessageConstructor m = (MessageConstructor)msg;
                        var sm = await ToSimpleMessage(m.id, m.to_id, m.from_id, m.date, m.output, Utils.Combine(m.message, m.media));

                        xl.AddMessage(sm);
                    }
                }
                UpdateStartIdFromExcel();
            }
            xl.Close();
            Close();
        }
示例#12
0
        public override MessageDeliveryState GetMessageDeliveryState()
        {
            if (message.Constructor == Constructor.message)
            {
                MessageConstructor messageConstructor = (MessageConstructor)message;
                return(messageConstructor.unread ? MessageDeliveryState.Delivered : MessageDeliveryState.Read);
            }
            else if (message.Constructor == Constructor.messageForwarded)
            {
                return(((MessageForwardedConstructor)message).unread ? MessageDeliveryState.Delivered : MessageDeliveryState.Read);
            }
            else if (message.Constructor == Constructor.messageService)
            {
                return(((MessageServiceConstructor)message).unread ? MessageDeliveryState.Delivered : MessageDeliveryState.Read);
            }

            return(MessageDeliveryState.Delivered);
        }
示例#13
0
        public void SetReadState()
        {
            if (message.Constructor == Constructor.message)
            {
                MessageConstructor messageConstructor = (MessageConstructor)message;
                messageConstructor.unread = false;
            }
            else if (message.Constructor == Constructor.messageForwarded)
            {
                ((MessageForwardedConstructor)message).unread = false;
            }
            else if (message.Constructor == Constructor.messageService)
            {
                ((MessageServiceConstructor)message).unread = false;
            }

            OnPropertyChanged("MessageDeliveryStateProperty");
        }
示例#14
0
        /// <summary>
        /// Start listening for CloudEvents and handle them using the specified callback function.
        /// <para>
        /// The <typeparamref name="TCloudEvent"/> type <em>must</em> define a constructor with the
        /// exact parameters <c>(<see cref="IReceiverMessage"/>, <see cref="IProtocolBinding"/>)
        /// </c>. A <see cref="MissingMemberException"/> is immediately thrown if the class does
        /// not define such a constructor.
        /// </para>
        /// </summary>
        /// <param name="receiver">The receiver to start.</param>
        /// <param name="onEventReceivedAsync">
        /// A function that is invoked when a CloudEvent is received.
        /// </param>
        /// <param name="protocolBinding">
        /// The <see cref="IProtocolBinding"/> used to map <see cref="IReceiverMessage"/> headers to
        /// CloudEvent attributes.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="receiver"/> or <paramref name="onEventReceivedAsync"/> is <see
        /// langword="null"/>.
        /// </exception>
        /// <exception cref="MissingMemberException">
        /// If the <typeparamref name="TCloudEvent"/> class does not define a public constructor
        /// with the exact parameters <c>(<see cref="IReceiverMessage"/>, <see cref=
        /// "IProtocolBinding"/>)</c>.
        /// </exception>
        public static void Start <TCloudEvent>(this IReceiver receiver,
                                               Func <TCloudEvent, IReceiverMessage, Task> onEventReceivedAsync, IProtocolBinding protocolBinding = null)
            where TCloudEvent : CloudEvent
        {
            if (receiver is null)
            {
                throw new ArgumentNullException(nameof(receiver));
            }
            if (onEventReceivedAsync is null)
            {
                throw new ArgumentNullException(nameof(onEventReceivedAsync));
            }

            if (!MessageConstructor.Exists(typeof(TCloudEvent)))
            {
                throw MissingReceiverConstructor(typeof(TCloudEvent));
            }

            receiver.Start(message => onEventReceivedAsync(message.To <TCloudEvent>(protocolBinding), message));
        }
        public frmFIXAPISample()
        {
            InitializeComponent();
            try{
                Thread Looper = new Thread(new ThreadStart(SendFromQueueTrade));
                Looper.Start();

                Thread Looper1 = new Thread(new ThreadStart(SendFromQueuePrice));
                Looper1.Start();

                _priceClient    = new TcpClient(_host, _pricePort);
                _priceStreamSSL = new SslStream(_priceClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
                _priceStreamSSL.AuthenticateAsClient(_host);
                _tradeClient    = new TcpClient(_host, _tradePort);
                _tradeStreamSSL = new SslStream(_tradeClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
                _tradeStreamSSL.AuthenticateAsClient(_host);
                _messageConstructor = new MessageConstructor(_host, _username, _password, _senderCompID, _senderSubID, _targetCompID);
            }catch (Exception e) {
                MessageBox.Show(e.ToString());
            }
        }
示例#16
0
        public async Task Create(string groupName)
        {
            if (chatGroups.FirstOrDefault(x => x.Name == groupName) != null)
            {
                await Clients.Caller.SendAsync(receiveMethodName, MessageConstructor.SystemMessage(ErrorMessages.GroupAlreadyExists(groupName)));

                return;
            }
            var groupDto = new GroupDto
            {
                Name = groupName,
                CurrentClientsAmount = 1,
                MaximumClientsAmount = _appConfig.MaximumGroupSize,
                CreatorConnectionId  = Context.ConnectionId,
                ClientsConnected     = new List <string>
                {
                    Context.ConnectionId
                }
            };
            var publicId = await _processor.OnGroupCreation(groupDto);

            groupDto.PublicId = publicId;
            chatGroups.Add(groupDto);

            await Groups.AddToGroupAsync(Context.ConnectionId, groupName);

            var message      = MessageConstructor.SystemMessage(InformationMessages.GroupSuccessfullyCreated(groupName));
            var groupMessage = new GroupMessage
            {
                GroupName  = groupName,
                GroupId    = groupDto.PublicId,
                Body       = message.Body,
                SenderName = message.SenderName,
                Time       = message.Time
            };

            await Clients.Caller.SendAsync(receiveMethodName, message);

            await Clients.Caller.SendAsync(GroupMethodNames.OnGroupJoined, groupMessage);
        }
示例#17
0
        ///<summary>Sets given appt.AptStatus to broken.
        ///Provide procCode that should be charted, can be null but will not chart a broken procedure.
        ///Also considers various broken procedure based prefs.
        ///Makes its own securitylog entries.</summary>
        public static void BreakApptHelper(Appointment appt, Patient pat, ProcedureCode procCode)
        {
            //suppressHistory is true due to below logic creating a log with a specific HistAppointmentAction instead of the generic changed.
            DateTime datePrevious    = appt.DateTStamp;
            bool     suppressHistory = false;

            if (procCode != null)
            {
                suppressHistory = (procCode.ProcCode.In("D9986", "D9987"));
            }
            Appointments.SetAptStatus(appt, ApptStatus.Broken, suppressHistory); //Appointments S-Class handles Signalods
            if (appt.AptStatus != ApptStatus.Complete)                           //seperate log entry for completed appointments.
            {
                SecurityLogs.MakeLogEntry(Permissions.AppointmentEdit, pat.PatNum,
                                          appt.ProcDescript + ", " + appt.AptDateTime.ToString()
                                          + ", Broken from the Appts module.", appt.AptNum, datePrevious);
            }
            else
            {
                SecurityLogs.MakeLogEntry(Permissions.AppointmentCompleteEdit, pat.PatNum,
                                          appt.ProcDescript + ", " + appt.AptDateTime.ToString()
                                          + ", Broken from the Appts module.", appt.AptNum, datePrevious);
            }
            #region HL7
            //If there is an existing HL7 def enabled, send a SIU message if there is an outbound SIU message defined
            if (HL7Defs.IsExistingHL7Enabled())
            {
                //S15 - Appt Cancellation event
                MessageHL7 messageHL7 = MessageConstructor.GenerateSIU(pat, Patients.GetPat(pat.Guarantor), EventTypeHL7.S15, appt);
                //Will be null if there is no outbound SIU message defined, so do nothing
                if (messageHL7 != null)
                {
                    HL7Msg hl7Msg = new HL7Msg();
                    hl7Msg.AptNum    = appt.AptNum;
                    hl7Msg.HL7Status = HL7MessageStatus.OutPending;                  //it will be marked outSent by the HL7 service.
                    hl7Msg.MsgText   = messageHL7.ToString();
                    hl7Msg.PatNum    = pat.PatNum;
                    HL7Msgs.Insert(hl7Msg);
#if DEBUG
                    MessageBox.Show("Appointments", messageHL7.ToString());
#endif
                }
            }
            #endregion
            #region Charting the proc
            if (procCode != null)
            {
                switch (procCode.ProcCode)
                {
                case "D9986":                        //Missed
                    HistAppointments.CreateHistoryEntry(appt.AptNum, HistAppointmentAction.Missed);
                    break;

                case "D9987":                        //Cancelled
                    HistAppointments.CreateHistoryEntry(appt.AptNum, HistAppointmentAction.Cancelled);
                    break;
                }
                Procedure procedureCur = new Procedure();
                procedureCur.PatNum       = pat.PatNum;
                procedureCur.ProvNum      = (procCode.ProvNumDefault > 0 ? procCode.ProvNumDefault : appt.ProvNum);
                procedureCur.CodeNum      = procCode.CodeNum;
                procedureCur.ProcDate     = DateTime.Today;
                procedureCur.DateEntryC   = DateTime.Now;
                procedureCur.ProcStatus   = ProcStat.C;
                procedureCur.ClinicNum    = appt.ClinicNum;
                procedureCur.UserNum      = Security.CurUser.UserNum;
                procedureCur.Note         = Lans.g("AppointmentEdit", "Appt BROKEN for") + " " + appt.ProcDescript + "  " + appt.AptDateTime.ToString();
                procedureCur.PlaceService = (PlaceOfService)PrefC.GetInt(PrefName.DefaultProcedurePlaceService);              //Default proc place of service for the Practice is used.
                List <InsSub>  listInsSubs    = InsSubs.RefreshForFam(Patients.GetFamily(pat.PatNum));
                List <InsPlan> listInsPlans   = InsPlans.RefreshForSubList(listInsSubs);
                List <PatPlan> listPatPlans   = PatPlans.Refresh(pat.PatNum);
                InsPlan        insPlanPrimary = null;
                InsSub         insSubPrimary  = null;
                if (listPatPlans.Count > 0)
                {
                    insSubPrimary  = InsSubs.GetSub(listPatPlans[0].InsSubNum, listInsSubs);
                    insPlanPrimary = InsPlans.GetPlan(insSubPrimary.PlanNum, listInsPlans);
                }
                double procFee;
                long   feeSch;
                if (insPlanPrimary == null || procCode.NoBillIns)
                {
                    feeSch = FeeScheds.GetFeeSched(0, pat.FeeSched, procedureCur.ProvNum);
                }
                else                  //Only take into account the patient's insurance fee schedule if the D9986 procedure is not marked as NoBillIns
                {
                    feeSch = FeeScheds.GetFeeSched(insPlanPrimary.FeeSched, pat.FeeSched, procedureCur.ProvNum);
                }
                procFee = Fees.GetAmount0(procedureCur.CodeNum, feeSch, procedureCur.ClinicNum, procedureCur.ProvNum);
                if (insPlanPrimary != null && insPlanPrimary.PlanType == "p" && !insPlanPrimary.IsMedical)         //PPO
                {
                    double provFee = Fees.GetAmount0(procedureCur.CodeNum, Providers.GetProv(procedureCur.ProvNum).FeeSched, procedureCur.ClinicNum,
                                                     procedureCur.ProvNum);
                    procedureCur.ProcFee = Math.Max(provFee, procFee);
                }
                else
                {
                    procedureCur.ProcFee = procFee;
                }
                if (!PrefC.GetBool(PrefName.EasyHidePublicHealth))
                {
                    procedureCur.SiteNum = pat.SiteNum;
                }
                Procedures.Insert(procedureCur);
                //Now make a claimproc if the patient has insurance.  We do this now for consistency because a claimproc could get created in the future.
                List <Benefit>   listBenefits          = Benefits.Refresh(listPatPlans, listInsSubs);
                List <ClaimProc> listClaimProcsForProc = ClaimProcs.RefreshForProc(procedureCur.ProcNum);
                Procedures.ComputeEstimates(procedureCur, pat.PatNum, listClaimProcsForProc, false, listInsPlans, listPatPlans, listBenefits, pat.Age, listInsSubs);
                FormProcBroken FormPB = new FormProcBroken(procedureCur);
                FormPB.IsNew = true;
                FormPB.ShowDialog();
            }
            #endregion
            #region BrokenApptAdjustment
            if (PrefC.GetBool(PrefName.BrokenApptAdjustment))
            {
                Adjustment AdjustmentCur = new Adjustment();
                AdjustmentCur.DateEntry = DateTime.Today;
                AdjustmentCur.AdjDate   = DateTime.Today;
                AdjustmentCur.ProcDate  = DateTime.Today;
                AdjustmentCur.ProvNum   = appt.ProvNum;
                AdjustmentCur.PatNum    = pat.PatNum;
                AdjustmentCur.AdjType   = PrefC.GetLong(PrefName.BrokenAppointmentAdjustmentType);
                AdjustmentCur.ClinicNum = appt.ClinicNum;
                FormAdjust FormA = new FormAdjust(pat, AdjustmentCur);
                FormA.IsNew = true;
                FormA.ShowDialog();
            }
            #endregion
            #region BrokenApptCommLog
            if (PrefC.GetBool(PrefName.BrokenApptCommLog))
            {
                Commlog CommlogCur = new Commlog();
                CommlogCur.PatNum       = pat.PatNum;
                CommlogCur.CommDateTime = DateTime.Now;
                CommlogCur.CommType     = Commlogs.GetTypeAuto(CommItemTypeAuto.APPT);
                CommlogCur.Note         = Lan.g("Appointment", "Appt BROKEN for") + " " + appt.ProcDescript + "  " + appt.AptDateTime.ToString();
                CommlogCur.Mode_        = CommItemMode.None;
                CommlogCur.UserNum      = Security.CurUser.UserNum;
                FormCommItem FormCI = new FormCommItem();
                FormCI.ShowDialog(new CommItemModel()
                {
                    CommlogCur = CommlogCur
                }, new CommItemController(FormCI)
                {
                    IsNew = true
                });
            }
            #endregion
            AutomationL.Trigger(AutomationTrigger.BreakAppointment, null, pat.PatNum);
            Recalls.SynchScheduledApptFull(appt.PatNum);
        }
示例#18
0
        ///<summary>Sets given appt.AptStatus to broken.
        ///Provide procCode that should be charted, can be null but will not chart a broken procedure.
        ///Also considers various broken procedure based prefs.
        ///Makes its own securitylog entries.</summary>
        public static void BreakApptHelper(Appointment appt, Patient pat, ProcedureCode procCode)
        {
            //suppressHistory is true due to below logic creating a log with a specific HistAppointmentAction instead of the generic changed.
            DateTime datePrevious    = appt.DateTStamp;
            bool     suppressHistory = false;

            if (procCode != null)
            {
                suppressHistory = (procCode.ProcCode.In("D9986", "D9987"));
            }
            Appointments.SetAptStatus(appt, ApptStatus.Broken, suppressHistory); //Appointments S-Class handles Signalods
            if (appt.AptStatus != ApptStatus.Complete)                           //seperate log entry for completed appointments.
            {
                SecurityLogs.MakeLogEntry(Permissions.AppointmentEdit, pat.PatNum,
                                          appt.ProcDescript + ", " + appt.AptDateTime.ToString()
                                          + ", Broken from the Appts module.", appt.AptNum, datePrevious);
            }
            else
            {
                SecurityLogs.MakeLogEntry(Permissions.AppointmentCompleteEdit, pat.PatNum,
                                          appt.ProcDescript + ", " + appt.AptDateTime.ToString()
                                          + ", Broken from the Appts module.", appt.AptNum, datePrevious);
            }
            #region HL7
            //If there is an existing HL7 def enabled, send a SIU message if there is an outbound SIU message defined
            if (HL7Defs.IsExistingHL7Enabled())
            {
                //S15 - Appt Cancellation event
                MessageHL7 messageHL7 = MessageConstructor.GenerateSIU(pat, Patients.GetPat(pat.Guarantor), EventTypeHL7.S15, appt);
                //Will be null if there is no outbound SIU message defined, so do nothing
                if (messageHL7 != null)
                {
                    HL7Msg hl7Msg = new HL7Msg();
                    hl7Msg.AptNum    = appt.AptNum;
                    hl7Msg.HL7Status = HL7MessageStatus.OutPending;                  //it will be marked outSent by the HL7 service.
                    hl7Msg.MsgText   = messageHL7.ToString();
                    hl7Msg.PatNum    = pat.PatNum;
                    HL7Msgs.Insert(hl7Msg);
#if DEBUG
                    MessageBox.Show("Appointments", messageHL7.ToString());
#endif
                }
            }
            #endregion
            List <Procedure> listProcedures = new List <Procedure>();
            //splits should only exist on procs if they are using tp pre-payments
            List <PaySplit> listSplitsForApptProcs = new List <PaySplit>();
            bool            isNonRefundable        = false;
            double          brokenProcAmount       = 0;
            Procedure       brokenProcedure        = new Procedure();
            bool            wasBrokenProcDeleted   = false;
            if (PrefC.GetYN(PrefName.PrePayAllowedForTpProcs))
            {
                listProcedures = Procedures.GetProcsForSingle(appt.AptNum, false);
                if (listProcedures.Count > 0)
                {
                    listSplitsForApptProcs = PaySplits.GetPaySplitsFromProcs(listProcedures.Select(x => x.ProcNum).ToList());
                }
            }
            #region Charting the proc
            if (procCode != null)
            {
                switch (procCode.ProcCode)
                {
                case "D9986":                        //Missed
                    HistAppointments.CreateHistoryEntry(appt.AptNum, HistAppointmentAction.Missed);
                    break;

                case "D9987":                        //Cancelled
                    HistAppointments.CreateHistoryEntry(appt.AptNum, HistAppointmentAction.Cancelled);
                    break;
                }
                brokenProcedure.PatNum       = pat.PatNum;
                brokenProcedure.ProvNum      = (procCode.ProvNumDefault > 0 ? procCode.ProvNumDefault : appt.ProvNum);
                brokenProcedure.CodeNum      = procCode.CodeNum;
                brokenProcedure.ProcDate     = DateTime.Today;
                brokenProcedure.DateEntryC   = DateTime.Now;
                brokenProcedure.ProcStatus   = ProcStat.C;
                brokenProcedure.ClinicNum    = appt.ClinicNum;
                brokenProcedure.UserNum      = Security.CurUser.UserNum;
                brokenProcedure.Note         = Lans.g("AppointmentEdit", "Appt BROKEN for") + " " + appt.ProcDescript + "  " + appt.AptDateTime.ToString();
                brokenProcedure.PlaceService = (PlaceOfService)PrefC.GetInt(PrefName.DefaultProcedurePlaceService);              //Default proc place of service for the Practice is used.
                List <InsSub>  listInsSubs    = InsSubs.RefreshForFam(Patients.GetFamily(pat.PatNum));
                List <InsPlan> listInsPlans   = InsPlans.RefreshForSubList(listInsSubs);
                List <PatPlan> listPatPlans   = PatPlans.Refresh(pat.PatNum);
                InsPlan        insPlanPrimary = null;
                InsSub         insSubPrimary  = null;
                if (listPatPlans.Count > 0)
                {
                    insSubPrimary  = InsSubs.GetSub(listPatPlans[0].InsSubNum, listInsSubs);
                    insPlanPrimary = InsPlans.GetPlan(insSubPrimary.PlanNum, listInsPlans);
                }
                double procFee;
                long   feeSch;
                if (insPlanPrimary == null || procCode.NoBillIns)
                {
                    feeSch = FeeScheds.GetFeeSched(0, pat.FeeSched, brokenProcedure.ProvNum);
                }
                else                  //Only take into account the patient's insurance fee schedule if the D9986 procedure is not marked as NoBillIns
                {
                    feeSch = FeeScheds.GetFeeSched(insPlanPrimary.FeeSched, pat.FeeSched, brokenProcedure.ProvNum);
                }
                procFee = Fees.GetAmount0(brokenProcedure.CodeNum, feeSch, brokenProcedure.ClinicNum, brokenProcedure.ProvNum);
                if (insPlanPrimary != null && insPlanPrimary.PlanType == "p" && !insPlanPrimary.IsMedical)         //PPO
                {
                    double provFee = Fees.GetAmount0(brokenProcedure.CodeNum, Providers.GetProv(brokenProcedure.ProvNum).FeeSched, brokenProcedure.ClinicNum,
                                                     brokenProcedure.ProvNum);
                    brokenProcedure.ProcFee = Math.Max(provFee, procFee);
                }
                else if (listSplitsForApptProcs.Count > 0 && PrefC.GetBool(PrefName.TpPrePayIsNonRefundable) && procCode.ProcCode == "D9986")
                {
                    //if there are pre-payments, non-refundable pre-payments is turned on, and the broken appointment is a missed code then auto-fill
                    //the window with the sum of the procs for the appointment. Transfer money below after broken procedure is confirmed by the user.
                    brokenProcedure.ProcFee = listSplitsForApptProcs.Sum(x => x.SplitAmt);
                    isNonRefundable         = true;
                }
                else
                {
                    brokenProcedure.ProcFee = procFee;
                }
                if (!PrefC.GetBool(PrefName.EasyHidePublicHealth))
                {
                    brokenProcedure.SiteNum = pat.SiteNum;
                }
                Procedures.Insert(brokenProcedure);
                //Now make a claimproc if the patient has insurance.  We do this now for consistency because a claimproc could get created in the future.
                List <Benefit>   listBenefits          = Benefits.Refresh(listPatPlans, listInsSubs);
                List <ClaimProc> listClaimProcsForProc = ClaimProcs.RefreshForProc(brokenProcedure.ProcNum);
                Procedures.ComputeEstimates(brokenProcedure, pat.PatNum, listClaimProcsForProc, false, listInsPlans, listPatPlans, listBenefits, pat.Age, listInsSubs);
                FormProcBroken FormPB = new FormProcBroken(brokenProcedure, isNonRefundable);
                FormPB.IsNew = true;
                FormPB.ShowDialog();
                brokenProcAmount     = FormPB.AmountTotal;
                wasBrokenProcDeleted = FormPB.IsProcDeleted;
            }
            #endregion
            #region BrokenApptAdjustment
            if (PrefC.GetBool(PrefName.BrokenApptAdjustment))
            {
                Adjustment AdjustmentCur = new Adjustment();
                AdjustmentCur.DateEntry = DateTime.Today;
                AdjustmentCur.AdjDate   = DateTime.Today;
                AdjustmentCur.ProcDate  = DateTime.Today;
                AdjustmentCur.ProvNum   = appt.ProvNum;
                AdjustmentCur.PatNum    = pat.PatNum;
                AdjustmentCur.AdjType   = PrefC.GetLong(PrefName.BrokenAppointmentAdjustmentType);
                AdjustmentCur.ClinicNum = appt.ClinicNum;
                FormAdjust FormA = new FormAdjust(pat, AdjustmentCur);
                FormA.IsNew = true;
                FormA.ShowDialog();
            }
            #endregion
            #region BrokenApptCommLog
            if (PrefC.GetBool(PrefName.BrokenApptCommLog))
            {
                Commlog commlogCur = new Commlog();
                commlogCur.PatNum       = pat.PatNum;
                commlogCur.CommDateTime = DateTime.Now;
                commlogCur.CommType     = Commlogs.GetTypeAuto(CommItemTypeAuto.APPT);
                commlogCur.Note         = Lan.g("Appointment", "Appt BROKEN for") + " " + appt.ProcDescript + "  " + appt.AptDateTime.ToString();
                commlogCur.Mode_        = CommItemMode.None;
                commlogCur.UserNum      = Security.CurUser.UserNum;
                commlogCur.IsNew        = true;
                FormCommItem FormCI = new FormCommItem(commlogCur);
                FormCI.ShowDialog();
            }
            #endregion
            #region Transfer money from TP Procedures if necessary
            //Note this MUST come after FormProcBroken since clicking cancel in that window will delete the procedure.
            if (isNonRefundable && !wasBrokenProcDeleted && listSplitsForApptProcs.Count > 0)
            {
                //transfer what the user specified in the broken appointment window.
                //transfer up to the amount specified by the user
                foreach (Procedure proc in listProcedures)
                {
                    if (brokenProcAmount == 0)
                    {
                        break;
                    }
                    List <PaySplit> listSplitsForAppointmentProcedure = listSplitsForApptProcs.FindAll(x => x.ProcNum == proc.ProcNum);
                    foreach (PaySplit split in listSplitsForAppointmentProcedure)
                    {
                        if (brokenProcAmount == 0)
                        {
                            break;
                        }
                        double amt = Math.Min(brokenProcAmount, split.SplitAmt);
                        Payments.CreateTransferForTpProcs(proc, new List <PaySplit> {
                            split
                        }, brokenProcedure, amt);
                        double amtPaidOnApt = listSplitsForApptProcs.Sum(x => x.SplitAmt);
                        if (amtPaidOnApt > amt)
                        {
                            //If the original prepayment amount is greater than the amt being specified for the appointment break, transfer
                            //the difference to an Unallocated Unearned Paysplit on the account.
                            double remainingAmt = amtPaidOnApt - amt;
                            //We have to create a new transfer payment here to correlate to the split.
                            Payment txfrPayment = new Payment();
                            txfrPayment.PayAmt    = 0;
                            txfrPayment.PayDate   = DateTime.Today;
                            txfrPayment.ClinicNum = split.ClinicNum;
                            txfrPayment.PayNote   = "Automatic transfer from treatment planned procedure prepayment.";
                            txfrPayment.PatNum    = split.PatNum;                       //ultimately where the payment ends up.
                            txfrPayment.PayType   = 0;
                            Payments.Insert(txfrPayment);
                            PaymentEdit.IncomeTransferData transferData = PaymentEdit.IncomeTransferData.CreateTransfer(split, txfrPayment.PayNum, true, remainingAmt);
                            PaySplit offset         = transferData.ListSplitsCur.FirstOrDefault(x => x.FSplitNum != 0);
                            long     offsetSplitNum = PaySplits.Insert(offset);                      //Get the FSplitNum from the offset
                            PaySplit allocation     = transferData.ListSplitsCur.FirstOrDefault(x => x.FSplitNum == 0);
                            allocation.FSplitNum = offsetSplitNum;
                            PaySplits.Insert(allocation);                            //Insert so the split is now up to date
                            SecurityLogs.MakeLogEntry(Permissions.PaymentCreate, txfrPayment.PatNum, "Automatic transfer of funds for treatment plan procedure pre-payments.");
                        }
                        brokenProcAmount -= amt;
                    }
                }
            }
            //if broken appointment procedure was deleted (user cancelled out of the window) just keep money on the original procedure.
            #endregion
            AppointmentEvent.Fire(ODEventType.AppointmentEdited, appt);
            AutomationL.Trigger(AutomationTrigger.BreakAppointment, null, pat.PatNum);
            Recalls.SynchScheduledApptFull(appt.PatNum);
        }
示例#19
0
 private static Peer GetPeer(MessageConstructor message)
 {
     return(null);
 }
示例#20
0
        public static async Task <Msg> BuildMessage(MessageConstructor msg)
        {
            var id = msg.id;

            LC s = msg.from_id.HasValue ? await Telestat.GetContact(msg.from_id.Value) : null;

            var sender = s != null ? s.FullName : string.Empty;

            var content = msg.message;

            var forwarded = string.Empty;

            if (msg.fwd_from_id != null)
            {
                var contact = await Telestat.GetContact(msg.fwd_from_id);

                forwarded = contact == null ? "Unknown" : contact.FullName;
            }

            var replyTo = msg.reply_to_msg_id.HasValue ?
                          msg.reply_to_msg_id.Value : -1;

            var date = msg.date;

            var mediaType = "";
            var mediaName = "";
            InputFileLocation mediaIfl = null;


            if (msg.media is MessageMediaEmptyConstructor)
            {
                var m = (MessageMediaEmptyConstructor)msg.media;
            }
            else if (msg.media is MessageMediaPhotoConstructor)
            {
                var m = (MessageMediaPhotoConstructor)msg.media;
                content = m.caption;
                if (m.photo is PhotoConstructor)
                {
                    var p = (PhotoConstructor)m.photo;
                    //                                       Should be largest
                    var loc = ((PhotoSizeConstructor)p.sizes[p.sizes.Count - 1]).location;
                    if (loc is FileLocationConstructor)
                    {
                        var l = (FileLocationConstructor)loc;
                        mediaType = "photo";
                        mediaName = l.local_id + ".jpg";
                        mediaIfl  = new InputFileLocationConstructor(l.volume_id, l.local_id, l.secret);
                    }
                }
            }
            else if (msg.media is MessageMediaVideoConstructor)
            {
                var m = (MessageMediaVideoConstructor)msg.media;
                content = m.caption;
                if (m.video is VideoConstructor)
                {
                    var v = (VideoConstructor)m.video;
                    mediaType = "video";
                    mediaName = v.id + ".mp4"; // i guess, may not be mp4
                    mediaIfl  = new InputVideoFileLocationConstructor(v.id, v.access_hash);
                }
            }
            else if (msg.media is MessageMediaGeoConstructor)
            {
                var m = (MessageMediaGeoConstructor)msg.media;
                // TODO implement
            }
            else if (msg.media is MessageMediaContactConstructor)
            {
                var m = (MessageMediaContactConstructor)msg.media;
                // TODO implement
            }
            else if (msg.media is MessageMediaUnsupportedConstructor)
            {
                var m = (MessageMediaUnsupportedConstructor)msg.media;
                // TODO implement
            }
            else if (msg.media is MessageMediaDocumentConstructor)
            {
                var m = (MessageMediaDocumentConstructor)msg.media;
                if (m.document is DocumentConstructor)
                {
                    var d = (DocumentConstructor)m.document;
                    mediaType = "document";

                    foreach (var atr in d.attributes)
                    {
                        if (atr is DocumentAttributeFilenameConstructor)
                        {
                            var a = (DocumentAttributeFilenameConstructor)atr;
                            mediaName = d.id.ToString() + "_" + a.file_name;
                            break;
                        }
                    }
                    if (string.IsNullOrEmpty(mediaName))
                    {
                        mediaName = d.id.ToString();
                    }

                    mediaIfl = new InputDocumentFileLocationConstructor(d.id, d.access_hash);
                }
            }
            else if (msg.media is MessageMediaAudioConstructor)
            {
                var m = (MessageMediaAudioConstructor)msg.media;
                if (m.audio is AudioConstructor)
                {
                    var a = (AudioConstructor)m.audio;
                    mediaType = "audio";

                    var spl = a.mime_type.Split('/');
                    if (spl.Length > 1)
                    {
                        mediaName = a.id.ToString() + "." + spl[1];
                    }
                    else
                    {
                        mediaName = a.id.ToString() + ".mp3";  // TODO it probs isn't mp3, but well!
                    }
                    mediaIfl = new InputAudioFileLocationConstructor(a.id, a.access_hash);
                }
            }
            else if (msg.media is MessageMediaWebPageConstructor)
            {
                var m = (MessageMediaWebPageConstructor)msg.media;
                // TODO implement
            }
            else if (msg.media is MessageMediaVenueConstructor)
            {
                var m = (MessageMediaVenueConstructor)msg.media;
                // TODO implement
            }

            var self = s != null ? s.Self : false;

            return(new Msg(
                       id, sender, content, date, self,
                       string.Empty, forwarded, replyTo,
                       mediaType, mediaName, mediaIfl));
        }
示例#21
0
        ///<summary>Runs in a separate thread</summary>
        private void OnDataReceived(IAsyncResult asyncResult)
        {
            int byteCountReceived = socketIncomingWorker.EndReceive(asyncResult);          //blocks until data is recieved.

            char[]  chars   = new char[byteCountReceived];
            Decoder decoder = Encoding.UTF8.GetDecoder();

            decoder.GetChars(dataBufferIncoming, 0, byteCountReceived, chars, 0); //doesn't necessarily get all bytes from the buffer because buffer could be half full.
            strbFullMsg.Append(chars);                                            //strbFullMsg might already have partial data
            //I think we are guaranteed to have received at least one char.
            bool isFullMsg   = false;
            bool isMalformed = false;

            if (strbFullMsg.Length == 1 && strbFullMsg[0] == MLLP_ENDMSG_CHAR) //the only char in the message is the end char
            {
                strbFullMsg.Clear();                                           //this must be the very end of a previously processed message.  Discard.
                isFullMsg = false;
            }
            //else if(strbFullMsg[0]!=MLLP_START_CHAR) {
            else if (strbFullMsg.Length > 0 && strbFullMsg[0] != MLLP_START_CHAR)
            {
                //Malformed message.
                isFullMsg   = true;            //we're going to do this so that the error gets saved in the database further down.
                isMalformed = true;
            }
            else if (strbFullMsg.Length >= 3 &&      //so that the next two lines won't crash
                     strbFullMsg[strbFullMsg.Length - 1] == MLLP_ENDMSG_CHAR &&       //last char is the endmsg char.
                     strbFullMsg[strbFullMsg.Length - 2] == MLLP_END_CHAR)          //the second-to-the-last char is the end char.
            {
                //we have a complete message
                strbFullMsg.Remove(0, 1);                      //strip off the start char
                strbFullMsg.Remove(strbFullMsg.Length - 2, 2); //strip off the end chars
                isFullMsg = true;
            }
            else if (strbFullMsg.Length >= 2 &&      //so that the next line won't crash
                     strbFullMsg[strbFullMsg.Length - 1] == MLLP_END_CHAR)          //the last char is the end char.
            {
                //we will treat this as a complete message, because the endmsg char is optional.
                //if the endmsg char gets sent in a subsequent block, the code above will discard it.
                strbFullMsg.Remove(0, 1);                      //strip off the start char
                strbFullMsg.Remove(strbFullMsg.Length - 1, 1); //strip off the end char
                isFullMsg = true;
            }
            else
            {
                isFullMsg = false;              //this is an incomplete message.  Continue to receive more blocks.
            }
            //end of big if statement-------------------------------------------------
            if (!isFullMsg)
            {
                dataBufferIncoming = new byte[8]; //clear the buffer
                socketIncomingWorker.BeginReceive(dataBufferIncoming, 0, dataBufferIncoming.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), null);
                return;                           //get another block
            }
            //Prepare to save message to database if malformed and not processed
            HL7Msg hl7Msg = new HL7Msg();

            hl7Msg.MsgText = strbFullMsg.ToString();
            strbFullMsg.Clear();            //ready for the next message
            bool   isProcessed      = true;
            string messageControlId = "";
            string ackEvent         = "";

            if (isMalformed)
            {
                hl7Msg.HL7Status = HL7MessageStatus.InFailed;
                hl7Msg.Note      = "This message is malformed so it was not processed.";
                HL7Msgs.Insert(hl7Msg);
                isProcessed = false;
            }
            else
            {
                MessageHL7 messageHl7Object = new MessageHL7(hl7Msg.MsgText);              //this creates an entire heirarchy of objects.
                try {
                    MessageParser.Process(messageHl7Object, IsVerboseLogging);             //also saves the message to the db
                    messageControlId = messageHl7Object.ControlId;
                    ackEvent         = messageHl7Object.AckEvent;
                }
                catch (Exception ex) {
                    EventLog.WriteEntry("OpenDentHL7", "Error in OnDataRecieved when processing message:\r\n" + ex.Message + "\r\n" + ex.StackTrace, EventLogEntryType.Error);
                    isProcessed = false;
                }
            }
            MessageHL7 hl7Ack = MessageConstructor.GenerateACK(messageControlId, isProcessed, ackEvent);

            if (hl7Ack == null)
            {
                EventLog.WriteEntry("OpenDentHL7", "No ACK defined for the enabled HL7 definition or no HL7 definition enabled.", EventLogEntryType.Information);
                return;
            }
            byte[] ackByteOutgoing = Encoding.ASCII.GetBytes(MLLP_START_CHAR + hl7Ack.ToString() + MLLP_END_CHAR + MLLP_ENDMSG_CHAR);
            if (IsVerboseLogging)
            {
                EventLog.WriteEntry("OpenDentHL7", "Beginning to send ACK.\r\n" + MLLP_START_CHAR + hl7Ack.ToString() + MLLP_END_CHAR + MLLP_ENDMSG_CHAR, EventLogEntryType.Information);
            }
            socketIncomingWorker.Send(ackByteOutgoing);            //this is a locking call
            //eCW uses the same worker socket to send the next message. Without this call to BeginReceive, they would attempt to send again
            //and the send would fail since we were no longer listening in this thread. eCW would timeout after 30 seconds of waiting for their
            //acknowledgement, then they would close their end and create a new socket for the next message. With this call, we can accept message
            //after message without waiting for a new connection.
            dataBufferIncoming = new byte[8];          //clear the buffer
            socketIncomingWorker.BeginReceive(dataBufferIncoming, 0, dataBufferIncoming.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), null);
        }
示例#22
0
 /// <summary>
 /// Initializes a new instance of <see cref="BaseNetworkConnector"/> class.
 /// </summary>
 /// <remarks>
 /// Also loads the <see cref="MessageTypeCache"/> on the first <see cref="BaseNetworkConnector"/> instance creation.
 /// </remarks>
 /// <exception cref="ArgumentNullException">If the messageProcessor is null; an argument exception is thrown.</exception>
 /// <param name="messageSerializer">The message serializer.</param>
 /// <param name="messageProcessor">The message processor.</param>
 protected BaseNetworkConnector(IMessageSerializer messageSerializer, IMessageProcessor messageProcessor)
 {
     _messageConstructor = new MessageConstructor(messageSerializer);
     _messageProcessor   = messageProcessor ?? throw new ArgumentNullException(nameof(messageProcessor));
     MessageTypeCache.LoadMessageTypeCache();
 }
示例#23
0
        /// <summary>
        /// </summary>
        private Patient CreatePatient(String LastName, String FirstName, DateTime birthDate, WebSheets.SheetAndSheetField sAnds)
        {
            Patient newPat = new Patient();

            newPat.LName     = LastName;
            newPat.FName     = FirstName;
            newPat.Birthdate = birthDate;
            newPat.ClinicNum = sAnds.web_sheet.ClinicNum;
            if (PrefC.GetBool(PrefName.EasyNoClinics))
            {
                //Set the patients primary provider to the practice default provider.
                newPat.PriProv = Providers.GetDefaultProvider().ProvNum;
            }
            else              //Using clinics.
                              //Set the patients primary provider to the clinic default provider.
            {
                newPat.PriProv = Providers.GetDefaultProvider(Clinics.ClinicNum).ProvNum;
            }
            Type t = newPat.GetType();

            FieldInfo[] fi = t.GetFields();
            foreach (FieldInfo field in fi)
            {
                // find match for fields in Patients in the web_sheetfieldlist
                var WebSheetFieldList = sAnds.web_sheetfieldlist.Where(sf => sf.FieldName.ToLower() == field.Name.ToLower());
                if (WebSheetFieldList.Count() > 0)
                {
                    // this loop is used to fill a field that may generate mutiple values for a single field in the patient.
                    //for example the field gender has 2 eqivalent sheet fields in the web_sheetfieldlist
                    for (int i = 0; i < WebSheetFieldList.Count(); i++)
                    {
                        WebSheets.webforms_sheetfield sf = WebSheetFieldList.ElementAt(i);
                        String SheetWebFieldValue        = sf.FieldValue;
                        String RadioButtonValue          = sf.RadioButtonValue;
                        FillPatientFields(newPat, field, SheetWebFieldValue, RadioButtonValue);
                    }
                }
            }
            try{
                Patients.Insert(newPat, false);
                SecurityLogs.MakeLogEntry(Permissions.PatientCreate, newPat.PatNum, "Created from Web Forms.");
                //set Guarantor field the same as PatNum
                Patient patOld = newPat.Copy();
                newPat.Guarantor = newPat.PatNum;
                Patients.Update(newPat, patOld);
                //If there is an existing HL7 def enabled, send an ADT message if there is an outbound ADT message defined
                if (HL7Defs.IsExistingHL7Enabled())
                {
                    MessageHL7 messageHL7 = MessageConstructor.GenerateADT(newPat, newPat, EventTypeHL7.A04);                //patient is guarantor
                    //Will be null if there is no outbound ADT message defined, so do nothing
                    if (messageHL7 != null)
                    {
                        HL7Msg hl7Msg = new HL7Msg();
                        hl7Msg.AptNum    = 0;
                        hl7Msg.HL7Status = HL7MessageStatus.OutPending;                      //it will be marked outSent by the HL7 service.
                        hl7Msg.MsgText   = messageHL7.ToString();
                        hl7Msg.PatNum    = newPat.PatNum;
                        HL7Msgs.Insert(hl7Msg);
#if DEBUG
                        MessageBox.Show(this, messageHL7.ToString());
#endif
                    }
                }
            }
            catch (Exception e) {
                gridMain.EndUpdate();
                MessageBox.Show(e.Message);
            }
            return(newPat);
        }
示例#24
0
        ///<summary>Creates a single recall appointment. If it's from a double click, then it will end up on that spot in the Appts module.  If not, it will end up on the pinboard with StringDateJumpTo as due date to jump to.  ListAptNumsSelected will contain the AptNum of the new appointment.</summary>
        public void MakeRecallAppointment()
        {
            List <InsSub>  listInsSubs  = InsSubs.RefreshForFam(_famCur);
            List <InsPlan> listInsPlans = InsPlans.RefreshForSubList(listInsSubs);
            Appointment    apt          = null;
            DateTime       dateTimeApt  = DateTime.MinValue;

            if (this.IsInitialDoubleClick)
            {
                dateTimeApt = DateTimeClicked;
            }
            try{
                apt = AppointmentL.CreateRecallApt(_patCur, listInsPlans, -1, listInsSubs, dateTimeApt);
            }
            catch (Exception ex) {
                MessageBox.Show(ex.Message);
                return;
            }
            DateTime datePrevious = apt.DateTStamp;

            ListAptNumsSelected.Add(apt.AptNum);
            if (IsInitialDoubleClick)
            {
                Appointment oldApt = apt.Copy();
                if (_patCur.AskToArriveEarly > 0)
                {
                    apt.DateTimeAskedToArrive = apt.AptDateTime.AddMinutes(-_patCur.AskToArriveEarly);
                    MessageBox.Show(Lan.g(this, "Ask patient to arrive") + " " + _patCur.AskToArriveEarly
                                    + " " + Lan.g(this, "minutes early at") + " " + apt.DateTimeAskedToArrive.ToShortTimeString() + ".");
                }
                apt.AptStatus = ApptStatus.Scheduled;
                apt.ClinicNum = _patCur.ClinicNum;
                apt.Op        = OpNumClicked;
                apt           = Appointments.AssignFieldsForOperatory(apt);
                //Use apt.ClinicNum because it was just set based on Op.ClinicNum in AssignFieldsForOperatory().
                if (!AppointmentL.IsSpecialtyMismatchAllowed(_patCur.PatNum, apt.ClinicNum))
                {
                    return;
                }
                Appointments.Update(apt, oldApt);
                _otherResult = OtherResult.CreateNew;
                SecurityLogs.MakeLogEntry(Permissions.AppointmentCreate, apt.PatNum, apt.AptDateTime.ToString(), apt.AptNum, datePrevious);
                //If there is an existing HL7 def enabled, send a SIU message if there is an outbound SIU message defined
                if (HL7Defs.IsExistingHL7Enabled())
                {
                    //S12 - New Appt Booking event
                    MessageHL7 messageHL7 = MessageConstructor.GenerateSIU(_patCur, _famCur.GetPatient(_patCur.Guarantor), EventTypeHL7.S12, apt);
                    //Will be null if there is no outbound SIU message defined, so do nothing
                    if (messageHL7 != null)
                    {
                        HL7Msg hl7Msg = new HL7Msg();
                        hl7Msg.AptNum    = apt.AptNum;
                        hl7Msg.HL7Status = HL7MessageStatus.OutPending;                      //it will be marked outSent by the HL7 service.
                        hl7Msg.MsgText   = messageHL7.ToString();
                        hl7Msg.PatNum    = _patCur.PatNum;
                        HL7Msgs.Insert(hl7Msg);
#if DEBUG
                        MessageBox.Show(this, messageHL7.ToString());
#endif
                    }
                }
                DialogResult = DialogResult.OK;
                return;
            }
            //not initialClick
            _otherResult = OtherResult.PinboardAndSearch;
            Recall recall = Recalls.GetRecallProphyOrPerio(_patCur.PatNum);          //shouldn't return null.
            if (recall.DateDue < DateTime.Today)
            {
                StringDateJumpTo = DateTime.Today.ToShortDateString();              //they are overdue
            }
            else
            {
                StringDateJumpTo = recall.DateDue.ToShortDateString();
            }
            //no securitylog entry needed here.  That will happen when it's dragged off pinboard.
            DialogResult = DialogResult.OK;
        }
示例#25
0
 public async Task List()
 {
     var body = JsonConvert.SerializeObject(chatGroups);
     await Clients.Caller.SendAsync(receiveMethodName, MessageConstructor.SystemMessage(body));
 }
 private static Peer GetPeer(MessageConstructor message) {
     return null;
 }
示例#27
0
        /// <summary>
        private static Patient CreatePatient(String LastName, String FirstName, DateTime birthDate, WebForms_Sheet webFormSheet, Sheet sheet, string cultureName)
        {
            bool    isWebForm = webFormSheet != null;
            Patient newPat    = new Patient();

            newPat.LName     = LastName;
            newPat.FName     = FirstName;
            newPat.Birthdate = birthDate;
            if (isWebForm)
            {
                newPat.ClinicNum = webFormSheet.ClinicNum;
            }
            else
            {
                newPat.ClinicNum = sheet.ClinicNum;
            }
            if (!PrefC.HasClinicsEnabled)
            {
                //Set the patients primary provider to the practice default provider.
                newPat.PriProv = Providers.GetDefaultProvider().ProvNum;
            }
            else              //Using clinics.
            //Set the patients primary provider to the clinic default provider.
            {
                newPat.PriProv = Providers.GetDefaultProvider(Clinics.ClinicNum).ProvNum;
            }
            Type t = newPat.GetType();

            FieldInfo[] fi = t.GetFields();
            foreach (FieldInfo field in fi)
            {
                // find match for fields in Patients in the SheetFields
                if (isWebForm)
                {
                    List <WebForms_SheetField> listWebFormsSheetFields = webFormSheet.SheetFields.FindAll(x => x.FieldName.ToLower() == field.Name.ToLower());
                    if (listWebFormsSheetFields.Count() > 0)
                    {
                        // this loop is used to fill a field that may generate mutiple values for a single field in the patient.
                        //for example the field gender has 2 eqivalent sheet fields in the SheetFields
                        foreach (WebForms_SheetField webFormsSheetField in listWebFormsSheetFields)
                        {
                            FillPatientFields(newPat, field, webFormsSheetField.FieldValue, webFormsSheetField.RadioButtonValue, cultureName, isWebForm, false);
                        }
                    }
                }
                else
                {
                    List <SheetField> listSheetFields = sheet.SheetFields.FindAll(x => x.FieldName.ToLower() == field.Name.ToLower());
                    if (listSheetFields.Count() > 0)
                    {
                        // this loop is used to fill a field that may generate mutiple values for a single field in the patient.
                        //for example the field gender has 2 eqivalent sheet fields in the SheetFields
                        foreach (SheetField sheetField in listSheetFields)
                        {
                            FillPatientFields(newPat, field, sheetField.FieldValue, sheetField.RadioButtonValue, "", isWebForm, sheet.IsCemtTransfer);
                        }
                    }
                }
            }
            try {
                Patients.Insert(newPat, false);
                SecurityLogs.MakeLogEntry(Permissions.PatientCreate, newPat.PatNum, isWebForm ? "Created from Web Forms." : "Created from CEMT transfer.");
                //set Guarantor field the same as PatNum
                Patient patOld = newPat.Copy();
                newPat.Guarantor = newPat.PatNum;
                Patients.Update(newPat, patOld);
                //If there is an existing HL7 def enabled, send an ADT message if there is an outbound ADT message defined
                if (HL7Defs.IsExistingHL7Enabled())
                {
                    MessageHL7 messageHL7 = MessageConstructor.GenerateADT(newPat, newPat, EventTypeHL7.A04);                //patient is guarantor
                    //Will be null if there is no outbound ADT message defined, so do nothing
                    if (messageHL7 != null)
                    {
                        HL7Msg hl7Msg = new HL7Msg();
                        hl7Msg.AptNum    = 0;
                        hl7Msg.HL7Status = HL7MessageStatus.OutPending;                      //it will be marked outSent by the HL7 service.
                        hl7Msg.MsgText   = messageHL7.ToString();
                        hl7Msg.PatNum    = newPat.PatNum;
                        HL7Msgs.Insert(hl7Msg);
#if DEBUG
                        MessageBox.Show("FormWebForms", messageHL7.ToString());
#endif
                    }
                }
            }
            catch (Exception e) {
                MessageBox.Show(e.Message);
            }
            return(newPat);
        }