void SendRuleTSM(bool serviceOnly) { string engine = TheCommonUtils.CStr(GetProperty("TSMEngine", false)); string text = TheCommonUtils.CStr(GetProperty("TSMText", false)); string payload = TheCommonUtils.CStr(GetProperty("TSMPayload", false)); //payload = payload.Replace("%DTO%", TheCommonUtils.CStr(DateTimeOffset.Now)); //text = text.Replace("%DTO%", TheCommonUtils.CStr(DateTimeOffset.Now)); ICDEThing triggerThing = TheThingRegistry.GetThingByMID("*", TheCommonUtils.CGuid(TriggerObject)) as ICDEThing; string escPayload = TheCommonUtils.GenerateFinalStr(payload, triggerThing); escPayload = TheCommonUtils.GenerateFinalStr(escPayload, MyBaseThing); string escText = TheCommonUtils.GenerateFinalStr(text, triggerThing); escText = TheCommonUtils.GenerateFinalStr(escText, MyBaseThing); if (!string.IsNullOrEmpty(engine) && !string.IsNullOrEmpty(text)) { TSM customTSM = new TSM(engine, escText, escPayload); if (serviceOnly) { customTSM.SetToServiceOnly(true); } TheCommCore.PublishCentral(customTSM, true); } if (IsRuleLogged) { LogEvent(escPayload); } if (TheThing.GetSafePropertyBool(MyBaseThing, "IsEVTLogged")) { TheLoggerFactory.LogEvent(eLoggerCategory.RuleEvent, TheCommonUtils.GenerateFinalStr(MyBaseThing.FriendlyName, MyBaseThing), eMsgLevel.l4_Message, TheBaseAssets.MyServiceHostInfo.GetPrimaryStationURL(false), escText, escPayload); } }
/// <summary> /// Handles Messages sent from a host sub-engine to its clients /// </summary> public void HandleMessage(ICDEThing sender, object pIncoming) { if (!(pIncoming is TheProcessMessage pMsg)) { return; } switch (pMsg.Message.TXT) { case "CDE_INITIALIZED": TheBaseAssets.MySYSLOG.WriteToLog(888, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM("MiniRelayService", $"BackChannel Updated - ORG:{TheCommonUtils.GetDeviceIDML(pMsg.Message.GetLastRelay())}", eMsgLevel.l3_ImportantMessage)); break; default: if (pMsg.Message.TXT.Equals("CDE_INITIALIZE")) { TSM tRelayMsg = new TSM(MyBaseEngine.GetEngineName(), "CDE_INITIALIZED") { QDX = 3, SID = pMsg.Message.SID }; tRelayMsg.SetNoDuplicates(true); TheBaseAssets.MySYSLOG.WriteToLog(888, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM("MiniRelayService", $"Message Text {tRelayMsg.TXT} relayed - ORG:{TheCommonUtils.GetDeviceIDML(tRelayMsg.ORG)}", eMsgLevel.l3_ImportantMessage)); //ORG-OK TheCommCore.PublishCentral(MyBaseEngine.GetEngineName() + pMsg.Message?.AddScopeIDFromTSM(), tRelayMsg); } break; } }
public void IncomingMessageEventTest() { var contentServiceThing = TheThingRegistry.GetBaseEngineAsThing(eEngineName.ContentService); var contentServiceEng = contentServiceThing.GetBaseEngine(); int numberOfMessages = 0; string txt = "TEST_TXT"; string payload = "TestPayload"; TSM testMsg = new TSM(eEngineName.ContentService, txt, payload); contentServiceEng?.RegisterEvent(eEngineEvents.IncomingMessage, (t, o) => { numberOfMessages++; if (o is TheProcessMessage msg) { Assert.AreEqual(msg.Message.TXT, txt); Assert.AreEqual(msg.Message.PLS, payload); Assert.AreEqual(msg.Message.ENG, contentServiceEng.GetEngineName()); testMsg.PLS = "TestPayload2"; //Assert.AreNotEqual(msg.Message.PLS, testMsg.PLS); // This fails } if (t is ICDEThing thing) { Assert.AreEqual(thing.GetBaseThing().cdeMID, contentServiceThing.cdeMID); } }); TheCommCore.PublishCentral(testMsg, true); TheCommonUtils.SleepOneEye(5000, 1000); Assert.AreEqual(numberOfMessages, 1); }
private static void SendGlobalThings(Guid targetNodeId) { // Do not send more often than every 60 seconds if (lastGlobalThingSendPerNode.TryGetValue(targetNodeId, out thingSendStatus timeAndPending)) { if (DateTimeOffset.Now.Subtract(timeAndPending.lastSend).TotalSeconds < 59) // && !timeAndPending.Pending) { return; } } var globalThings = TheThingRegistry.GetThingsByFunc("*", (t) => TheThing.GetSafePropertyBool(t, "IsRegisteredGlobally") && t.IsOnLocalNode()); if (globalThings != null) { TSM tTSM = new TSM(eEngineName.ContentService, "CDE_SYNC_THINGS", TheCommonUtils.SerializeObjectToJSONString(globalThings)); tTSM.SetToServiceOnly(true); if (targetNodeId == Guid.Empty) { TheCommCore.PublishCentral(tTSM); } else { TheCommCore.PublishToNode(targetNodeId, tTSM); } lastGlobalThingSendPerNode[targetNodeId] = new thingSendStatus { lastSend = DateTimeOffset.Now, Pending = false }; } }
public bool LogEvent(TheEventLogData pItem) { if (pItem == null) { return(false); } bool bRet = false; List <TheThing> tDevList = TheThingRegistry.GetThingsOfEngine(MyBaseThing.EngineName); if (tDevList?.Count > 0) { foreach (TheThing tDev in tDevList) { var tTwin = tDev.GetObject() as ICDELoggerEngine; var tRes = tTwin?.LogEvent(pItem); if (!bRet && tRes == true) { bRet = true; } } } if (PublishEvents) //This allows to have a logger on a different node { TheCommCore.PublishCentral(new TSM(eEngineName.ContentService, eEngineEvents.NewEventLogEntry, pItem.EventLevel, TheCommonUtils.SerializeObjectToJSONString(pItem)), true); } return(bRet); }
private void BtnSend_Click(object sender, RoutedEventArgs e) { MsgChatHello tMsg = new MsgChatHello { SenderName = "Chris", Message = txtMsgText.Text }; TheCommCore.PublishCentral(new TSM("CHATSTER", $"MsgChatHello:{Guid.NewGuid()}", TheCommonUtils.SerializeObjectToJSONString(tMsg)), true); }
public void SendChartData(TheDataBase pTarget) { string tStr = SerializeChart2JSON(); if (pTarget.cdeN == Guid.Empty) { TheCommCore.PublishCentral(new TSM("CDMyC3.TheC3Service", $"CHART_MODEL:{pTarget.cdeMID}", tStr)); } else { TheCommCore.PublishToNode(pTarget.cdeN, new TSM("CDMyC3.TheC3Service", $"CHART_MODEL:{pTarget.cdeMID}", tStr)); } }
/******************************************************** * BASIC MESSAGING EXAMPLE (without plugins) * Uncomment the "SinkTimer" method in MyTestHost to enable. *******************************************************/ private static void HandleMessage(ICDEThing arg1, object arg2) { if (!(arg2 is TheProcessMessage pMsg)) { return; } if (pMsg?.Message != null) { string[] cmd = pMsg.Message.TXT.Split(':'); switch (cmd[0]) { case "HELLO": Console.WriteLine("MyTestEngine2 received HELLO " + (cmd.Length > 1 ? cmd[1] : "")); TheCommCore.PublishCentral(new TSM("MyTestEngine", "HELLO_REPLY:" + (cmd.Length > 1 ? cmd[1] : ""), "MyTestPayload")); // Send reply back break; } } }
public void SendCPUInfo(Guid pOrg) { GetCPUInfo(TheBaseAssets.MyServiceHostInfo.GetPrimaryStationURL(false)); TSM tMsg = new TSM(MyEngineName, "CPUINFO", TheCommonUtils.SerializeObjectToJSONString <TheCPUInfo>(MyCPUInfoData)); tMsg.SetNoDuplicates(true); if (!TheBaseAssets.MyServiceHostInfo.IsCloudService) //Cloud would send unscoped Message going nowhere! { if (pOrg == Guid.Empty) { TheCommCore.PublishCentral(MyEngineName, tMsg); } else { TheCommCore.PublishToNode(pOrg, tMsg); } } TheBaseAssets.MySYSLOG.WriteToLog(8003, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : tMsg); }
public void IncomingMessage2EventTest() { var contentServiceThing = TheThingRegistry.GetBaseEngineAsThing(eEngineName.ContentService); var contentServiceEng = contentServiceThing.GetBaseEngine(); int numberOfMessages = 0; string txt = "CDE_GET_SERVICEINFO"; string payload = "CHNL"; TSM testMsg = new TSM(eEngineName.ContentService, txt, payload); contentServiceThing?.RegisterEvent(eEngineEvents.IncomingEngineMessage, (t, o) => { // Two messages should be received here - The first intercepts the CDE_GET_SERVICEINFO // The second intercepts the CDE_SERVICEINFO response (since originator Thing was set to ContentService) numberOfMessages++; }); testMsg.SetOriginatorThing(contentServiceThing); TheCommCore.PublishCentral(testMsg, true); TheCommonUtils.SleepOneEye(5000, 1000); Assert.AreEqual(numberOfMessages, 2); }
public void SendHealthInfo(Guid pOrg) { GetISMHealthData(); TSM tMsg = new TSM(MyEngineName, "ISMHEALTH", TheCommonUtils.SerializeObjectToJSONString <TheServiceHealthData>(MyHealthData)); if (!TheBaseAssets.MyServiceHostInfo.IsCloudService) //Cloud would send unscoped Message going nowhere! { tMsg.SetNoDuplicates(true); if (pOrg == Guid.Empty) { TheCommCore.PublishCentral(MyEngineName, tMsg); } else { TheCommCore.PublishToNode(pOrg, tMsg); } } eventNewHealthData?.Invoke(MyHealthData); TheBaseAssets.MySYSLOG.WriteToLog(8004, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : tMsg); }
private bool ProcessMessage(string correlationToken, string eventConverterName, DateTimeOffset messageTime, string messagePayload, string originator, bool bIsTargetedMessage, out string error, out bool bSendAck) { bool bSuccess = false; bSendAck = true; if (bIsTargetedMessage) { if (_nodeOwnerManager.RegisterOwnerCandidate(correlationToken, originator, TheBaseAssets.MyServiceHostInfo.MyDeviceInfo.DeviceID.ToString(), true)) { var notification = new TSM(MyBaseEngine.GetEngineName(), $"MESHRECEIVER_ACK_NOTIFY:;:{correlationToken}:;:{originator}:;:{bIsTargetedMessage}"); TheCommCore.PublishCentral(notification, false); } } else { if (_nodeOwnerManager.CheckOwner(originator, TheBaseAssets.MyServiceHostInfo.MyDeviceInfo.DeviceID.ToString()) != true) { _nodeOwnerManager.RequestOwnership(correlationToken, originator, TheBaseAssets.MyServiceHostInfo.MyDeviceInfo.DeviceID.ToString()); } } IEventConverter eventConverter = null; if (!string.IsNullOrEmpty(eventConverterName)) { eventConverter = TheEventConverters.GetEventConverter(eventConverterName); if (eventConverter == null) { TheBaseAssets.MySYSLOG.WriteToLog(180001, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("Mesh Receiver", $"Unknown event converter in incoming MESHSENDER_DATA {this.MyBaseThing.FriendlyName}: {eventConverterName}", eMsgLevel.l1_Error, TSM.L(eDEBUG_LEVELS.OFF) ? null : messagePayload)); } } else { eventConverter = TheEventConverters.GetEventConverter(ReceiverEventConverter); if (eventConverter == null) { TheBaseAssets.MySYSLOG.WriteToLog(180002, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("Mesh Receiver", $"Unknown default event converter {this.MyBaseThing.FriendlyName}: {ReceiverEventConverter}", eMsgLevel.l1_Error)); } } //if (EnableDataLogging) //{ // try // { // lock (dataLoggerLock) // { // System.IO.File.AppendAllText("meshreceiverdata.log", $"{{\"TimeReceived\":\"{DateTimeOffset.Now:O}\", \"PLS\": {pMsg.Message.PLS},\"TXT\":{pMsg.Message.TXT}}},\r\n"); // } // } // catch (Exception e) // { // TheBaseAssets.MySYSLOG.WriteToLog(180003, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("Mongo Writer", $"Unable to log data to file: {this.MyBaseThing.FriendlyName}", eMsgLevel.l3_ImportantMessage, e.ToString())); // } //} if (eventConverter == null) { error = "Unknown event converter"; } else { if (IsConnected) { try { var now = DateTimeOffset.Now; if (!string.IsNullOrEmpty(TimeDriftPropertyName)) { // Calculate time difference (in minutes) between the sender and this node var timeDrift = now - messageTime; timeDrift = TimeSpan.FromMinutes(timeDrift.TotalMinutes > 0 ? Math.Floor(timeDrift.TotalMinutes) : Math.Ceiling(timeDrift.TotalMinutes)); if (eventConverter.StaticPropsToAdd == null) { eventConverter.StaticPropsToAdd = new Dictionary <string, object>(); } eventConverter.StaticPropsToAdd[TimeDriftPropertyName] = System.Xml.XmlConvert.ToString(timeDrift); } if (!string.IsNullOrEmpty(SenderTimePropertyName)) { if (eventConverter.StaticPropsToAdd == null) { eventConverter.StaticPropsToAdd = new Dictionary <string, object>(); } eventConverter.StaticPropsToAdd[SenderTimePropertyName] = messageTime; } bool bDetectedOtherOwner = false; // TODO Support picking a thing for formats that don't carry a thing id eventConverter.NewThingCallback = async(t) => { if (await _nodeOwnerManager.CheckOwnerAsync(correlationToken, originator, TheBaseAssets.MyServiceHostInfo.MyDeviceInfo.DeviceID.ToString()).ConfigureAwait(false) == false) { bDetectedOtherOwner = true; return(false); } return(true); }; error = eventConverter.ProcessEventData(null, messagePayload, now); if (bDetectedOtherOwner) { error = "Detected other receiver"; bSendAck = false; bSuccess = false; } else { if (String.IsNullOrEmpty(error)) { ReceiveCount++; bSuccess = true; } else { TheBaseAssets.MySYSLOG.WriteToLog(180004, new TSM("Mesh Receiver", "Error processing data", eMsgLevel.l1_Error, error)); ReceiveErrorCount++; } LastReceiveTime = now; } } catch (Exception e) { error = "Error parsing data: " + e.Message; TheBaseAssets.MySYSLOG.WriteToLog(180005, new TSM("Mesh Receiver", "Error processing data", eMsgLevel.l1_Error, e.ToString())); bSuccess = false; ReceiveErrorCount++; } if (bSuccess) { MyBaseThing.StatusLevel = 1; } } else { error = "Not connected"; } } return(bSuccess); }
void SendSMS(string pText) { try { MailMessage mail = new MailMessage(); SmtpClient SmtpServer = new SmtpClient(MyBaseThing.Address); mail.From = new MailAddress(FromAddress); string receipt = Recipient; string credentials = Credentials; if (TheCommonUtils.IsNullOrWhiteSpace(receipt)) { receipt = "*****@*****.**"; } string carrier = Carrier; // Code to handle carrier //TODO: Set Server name and SSL/Server and Port per Carrier #region Handle Carrier switch (carrier.ToLower()) { case "t-mobile": receipt += "@tmomail.net"; break; case "at&t": receipt += "@txt.att.net"; break; case "sprint": receipt += "@messaging.sprintpcs.com"; break; case "verizon": receipt += "@vtext.com"; break; case "virgin mobile": receipt += "@vmobl.com"; break; case "metro pcs": receipt += "@MyMetroPcs"; break; case "alltel": receipt += "@message.alltel.com"; break; case "powertel": receipt += "@ptel.net"; break; case "suncom": receipt += "@tms.suncom.com"; break; case "nextel": receipt += "@messaging.nextel.com"; break; case "us cellular": receipt += "@email.uscc.net"; break; case "boost mobile": receipt += "@myboostmobile.com"; break; case "cingular": receipt += "@cingularme.com"; break; } #endregion mail.To.Add(receipt); if (string.IsNullOrEmpty(SubjectText)) { mail.Subject = TheBaseAssets.MyServiceHostInfo.ApplicationName + " Message"; } else { mail.Subject = SubjectText; } if (!TheCommonUtils.IsNullOrWhiteSpace(pText)) { mail.Body = pText; } else { mail.Body = MessageText; } if (credentials.Equals("Admin")) { string AdminUsername = MyBaseEngine.GetBaseThing().GetProperty("AdminUsername", false).ToString(); string AdminServer = MyBaseEngine.GetBaseThing().GetProperty("AdminServer", false).ToString(); string AdminPassword = MyBaseEngine.GetBaseThing().GetProperty("AdminPassword", false).GetValue().ToString(); int AdminPort = int.Parse(MyBaseEngine.GetBaseThing().GetProperty("AdminPort", false).ToString()); SmtpServer.Credentials = new System.Net.NetworkCredential(AdminUsername, AdminPassword); SmtpServer.Host = AdminServer; SmtpServer.Port = AdminPort; string AdminSsl = MyBaseEngine.GetBaseThing().GetProperty("AdminSsl", false).ToString(); if (AdminSsl.Equals("True")) { SmtpServer.EnableSsl = true; } } else { SmtpServer.Credentials = new System.Net.NetworkCredential(UserName, Password); SmtpServer.Port = Port; if (UseSsl) { SmtpServer.EnableSsl = true; } } SmtpServer.Send(mail); ResultText = "SMS Sent to " + Recipient; TSM tTSM = new TSM(MyBaseEngine.GetEngineName(), "SET_LAST_MSG", string.Format("SMS: Subject:{2} Body:{3} From {0} at {1}", TheBaseAssets.MyServiceHostInfo.MyStationName, DateTimeOffset.Now, SubjectText, mail.Body)); MyBaseEngine.ProcessMessage(new TheProcessMessage(tTSM)); TheCommCore.PublishCentral(tTSM); } catch (Exception ex) { ResultText = ex.ToString(); } }
static void sinkReady() { Debug.WriteLine("Registering events for engine... "); TheCDEngines.MyContentEngine.RegisterEvent(eEngineEvents.IncomingMessage, sinkIncoming); if (TheCDEngines.MyNMIService != null) { TheCDEngines.MyNMIService.RegisterEvent(eEngineEvents.IncomingMessage, sinkIncoming); //TheCDEngines.MyContentEngine.RegisterEvent(eEngineEvents.ChannelConnected, sinkEstablished); } TheCommonUtils.cdeRunAsync("LoopDiDoop", true, (o) => { TheThing tTimer = null; TheThing GoogleDNS = null; TheThing ThingBar = null; while (TheBaseAssets.MasterSwitch) { TheCommonUtils.SleepOneEye(5000, 100); if (ThingBar == null) { ThingBar = TheThingRegistry.GetThingByProperty("*", Guid.Empty, "FriendlyName", "ThingBar"); if (ThingBar != null) { TheThingRegistry.RegisterEventOfThing(ThingBar, eThingEvents.ValueChanged, (sender, para) => { TSM tTSM2 = new TSM(eEngineName.ContentService, "UNITY:GAUGE", para.ToString()); TheCommCore.PublishCentral(tTSM2); }); } } if (tTimer == null) { tTimer = TheThingRegistry.GetThingByProperty("*", Guid.Empty, "DeviceType", "Timer"); if (tTimer != null) { TheThingRegistry.RegisterEventOfThing(tTimer, eThingEvents.ValueChanged, (sender, para) => { TSM tTSM2 = new TSM(eEngineName.ContentService, "UNITY:TIMER", para.ToString()); TheCommCore.PublishCentral(tTSM2); }); } } if (GoogleDNS == null) { GoogleDNS = TheThingRegistry.GetThingByProperty("*", Guid.Empty, "FriendlyName", "Google DNS"); if (GoogleDNS != null) { TheThingRegistry.RegisterEventOfThing(GoogleDNS, eThingEvents.PropertyChanged, (sender, para) => { cdeP tP = para as cdeP; if (tP != null && tP.Name == "RoundTripTime") { TSM tTSM2 = new TSM(eEngineName.ContentService, "UNITY:HEART", para.ToString()); TheCommCore.PublishCentral(tTSM2); } }); } } if (GoogleDNS != null && tTimer != null && ThingBar != null) { break; } } }); }
private void sinkHeartBeatTimer(long NOTUSED) { try { TheDiagnostics.SetThreadName("HeartbeatTimer", true); mHeartBeatTicker++; TheBaseAssets.MySYSLOG.WriteToLog(2803, TSM.L(eDEBUG_LEVELS.EVERYTHING) ? null : new TSM("QSender", $"Enter HearbeatTimer for ORG:{MyTargetNodeChannel}", eMsgLevel.l7_HostDebugMessage)); TheTimeouts tTO = TheBaseAssets.MyServiceHostInfo.TO; if (!IsHeartBeatAlive(tTO.DeviceCleanSweepTimeout * 2) && TheCommonUtils.IsDeviceSenderType(MyTargetNodeChannel?.SenderType ?? cdeSenderType.NOTSET) && MyTargetNodeChannel?.IsWebSocket == false) //IDST-OK: Remove dead devices that might have hard disconnected (no correct disconnect) i.e. http browsers were just closed { TheBaseAssets.MySYSLOG.WriteToLog(2820, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("QSender", $"Forced Removal of QSender {MyTargetNodeChannel.ToMLString()} due to DeviceCleanSweep", eMsgLevel.l4_Message)); Guid?tTarget = MyTargetNodeChannel?.cdeMID; DisposeSender(true); if (tTarget.HasValue) { TheQueuedSenderRegistry.RemoveOrphan(tTarget.Value); TheCommCore.PublishCentral(new TSM(eEngineName.ContentService, "CDE_DELETEORPHAN", tTarget.ToString())); } return; } if (!IsAlive && !MyTargetNodeChannel?.IsWebSocket == true) { return; //NEW:V3 2013/12/13 allow for cloud reconnect if WebSockets } if ((mHeartBeatTicker % (tTO.HeartBeatRate * 2)) == 0) { if (MyTargetNodeChannel?.SenderType != cdeSenderType.CDE_LOCALHOST) { timerMyHeartbeatTimer(); } if (MyTargetNodeChannel?.SenderType == cdeSenderType.CDE_CLOUDROUTE && ((!IsConnected && !IsConnecting) || !IsAlive) && (mHeartBeatTicker % (tTO.HeartBeatRate * 10)) == 0) //tQ.MyTargetNodeChannel.IsWebSocket && NOW ALWAYS RECONNECT { TheCommonUtils.cdeRunAsync("ReconnectCloud", true, (o) => ReconnectCloud()); } if (MyTargetNodeChannel?.SenderType != cdeSenderType.CDE_LOCALHOST && IsAlive && IsConnected) //!TheBaseAssets.MyServiceHostInfo.IsCloudService && !tQ.MyTargetNodeChannel.IsWebSocket && { if (MyTargetNodeChannel?.IsWebSocket != true) { if (GetQueLength() == 0) { TheBaseAssets.MyServiceHostInfo.TO.MakeHeartPump(); // CODE REVIEW Markus: Isn't this backwards: we should pump faster while we have more work to do? SendPickupMessage(); //Pickup } else { TheBaseAssets.MyServiceHostInfo.TO.MakeHeartNormal(); } } else { SendPickupMessage(); //Pickup } } } } catch (Exception e) { TheBaseAssets.MySYSLOG.WriteToLog(2821, new TSM("QSRegistry", $"Fatal Error in HealthTimer for QS:{this.cdeMID} and MTNC:{MyTargetNodeChannel?.ToMLString()}", eMsgLevel.l1_Error, e.ToString())); } }
internal static void DoExecuteCommand(string pInTopicBatch, TheQueuedSender pQSender, bool DoSendBackBuffer, TheRequestData pRequestData, List <TheDeviceMessage> pDevMessageList) { bool SendPulse = false; if (pDevMessageList != null && pDevMessageList.Count > 0) { foreach (TheDeviceMessage pDevMessage in pDevMessageList) { TSM recvMessage = null; string tTopic = ""; try { var tTargetNodeChannel = pQSender?.MyTargetNodeChannel; string pInTopic = pInTopicBatch; if (string.IsNullOrEmpty(pInTopic)) { pInTopic = pDevMessage.TOP; } recvMessage = pDevMessage.MSG; if (pQSender != null && tTargetNodeChannel != null && tTargetNodeChannel.SenderType == cdeSenderType.CDE_JAVAJASON && recvMessage != null && string.IsNullOrEmpty(recvMessage.ORG)) { recvMessage.ORG = tTargetNodeChannel.cdeMID.ToString(); } #region ChunkResassembly string[] CommandParts = null; if (!string.IsNullOrEmpty(pInTopic)) { CommandParts = TheCommonUtils.cdeSplit(pInTopic, ":,:", false, false); tTopic = CommandParts[0]; } TheCDEKPIs.IncrementKPI(eKPINames.CCTSMsReceived); if (CommandParts != null && CommandParts.Length == 4 && !CommandParts[2].Equals("1")) { if (!TheCommonUtils.ProcessChunkedMessage(CommandParts, recvMessage)) { SendPulse = true; continue; } } #endregion if (recvMessage != null) { if (((TheBaseAssets.MyServiceHostInfo.RejectIncomingSETP && recvMessage.TXT?.StartsWith("SETP:") == true) || TheBaseAssets.MyServiceHostInfo.DisableNMIMessages) && recvMessage.ENG?.StartsWith(eEngineName.NMIService) == true) { TheCDEKPIs.IncrementKPI(eKPINames.QSSETPRejected); continue; } var tTopicSens = tTopic.Split('@')[0]; //only topic - no ScopeID var tTopicParts = tTopic.Split(';'); if (tTargetNodeChannel.SenderType == cdeSenderType.CDE_JAVAJASON) { //4.209: JavaJason does no longer get the scope ID - hence telegrams coming from the browser have to be ammmended with SID here if (string.IsNullOrEmpty(recvMessage.SID) && !string.IsNullOrEmpty(pRequestData?.SessionState?.SScopeID)) { recvMessage.SID = pRequestData?.SessionState?.SScopeID; //Set the ScopeID in the SID of the message if (tTopic.StartsWith("CDE_SYSTEMWIDE")) { tTopic = $"{tTopicParts[0]}@{recvMessage.SID}"; if (tTopicParts.Length > 1) { tTopic += $";{tTopicParts[1]}"; //if a direct address is added use this too } } else if (!tTopic.Contains('@')) { tTopic += $"@{recvMessage.SID}"; } if (recvMessage.TXT == "CDE_SUBSCRIBE" || recvMessage.TXT == "CDE_INITIALIZE") { string MsgNoSID = null; recvMessage.PLS = TheBaseAssets.MyScopeManager.AddScopeID(recvMessage.PLS, recvMessage.SID, ref MsgNoSID, false, false); } } } if (tTopicParts.Length > 1) { tTopicSens += $";{tTopicParts[1]}"; //if a direct address is added use this too } if (TheQueuedSenderRegistry.WasTSMSeenBefore(recvMessage, pRequestData.SessionState.cdeMID, tTopicSens, tTargetNodeChannel?.RealScopeID)) //ATTENTION: RScope should come from pDevMessage { TheBaseAssets.MySYSLOG.WriteToLog(285, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM("CoreComm", $"EnterExecuteCommand: Message was seen before ORG:{TheCommonUtils.GetDeviceIDML(recvMessage?.ORG)} Topic:{tTopicSens}", eMsgLevel.l2_Warning)); //ORG-OK TheCDEKPIs.IncrementKPI(eKPINames.QSRejected); continue; } if (tTargetNodeChannel.cdeMID == Guid.Empty) { tTargetNodeChannel.cdeMID = recvMessage.GetLastRelay(); } if (tTargetNodeChannel.SenderType == cdeSenderType.NOTSET) { TheBaseAssets.MySYSLOG.WriteToLog(285, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("CoreComm", "Sender Type for the QSender is not set! WE SHOULD NEVER GET HERE", eMsgLevel.l1_Error));//ORG-OK //3.218: Processing no longer allowed!!! return; } // Enable upper layers to do RSA decryption. Force overwrite for Browser even if SEID already set (may have been initialized to some other value) if (tTargetNodeChannel.SenderType == cdeSenderType.CDE_JAVAJASON || String.IsNullOrEmpty(recvMessage.SEID)) { recvMessage.SEID = pRequestData.SessionState.cdeMID.ToString(); } if (pRequestData.SessionState != null && string.IsNullOrEmpty(pRequestData.SessionState.RemoteAddress)) { pRequestData.SessionState.RemoteAddress = tTargetNodeChannel.cdeMID.ToString(); } //NEW: User ID Management in Message after first node if (string.IsNullOrEmpty(recvMessage.UID) && pRequestData.SessionState != null && pRequestData.SessionState.CID != Guid.Empty) { recvMessage.UID = TheCommonUtils.cdeEncrypt(pRequestData.SessionState.CID.ToByteArray(), TheBaseAssets.MySecrets.GetAI()); //3.083: Must be cdeAI } } } catch (Exception ee) { TheBaseAssets.MySYSLOG.WriteToLog(319, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("CoreComm", "Execute Command Pre-Parsing Error", eMsgLevel.l1_Error, ee.ToString())); } if (recvMessage == null) { TheBaseAssets.MySYSLOG.WriteToLog(286, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM("CoreComm", $"No Message for Parsing: Topic:{tTopic} - {pRequestData.ResponseBufferStr}", eMsgLevel.l7_HostDebugMessage)); } else { if (recvMessage.PLB != null && recvMessage.PLB.Length > 0 && string.IsNullOrEmpty(recvMessage.PLS)) { try { recvMessage.PLS = TheCommonUtils.cdeDecompressToString(recvMessage.PLB); recvMessage.PLB = null; } catch (Exception) { TheBaseAssets.MySYSLOG.WriteToLog(286, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM("CoreComm", $"PLB to PLS decompress failed - Topic:{tTopic} Node:{pQSender?.MyTargetNodeChannel?.ToMLString()} ORG:{TheCommonUtils.GetDeviceIDML(recvMessage?.ORG)}", eMsgLevel.l7_HostDebugMessage, $"TXT:{recvMessage.TXT}"));//ORG-OK } } TheBaseAssets.MySYSLOG.WriteToLog(286, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM("CoreComm", $"PLB to PLS parsing done - Topic:{tTopic} Node:{pQSender?.MyTargetNodeChannel?.ToMLString()} ORG:{TheCommonUtils.GetDeviceIDML(recvMessage?.ORG)}", eMsgLevel.l7_HostDebugMessage, $"TXT:{recvMessage.TXT}"));//ORG-OK if (!SendPulse) { SendPulse = recvMessage.SendPulse(); } TheCDEKPIs.IncrementKPI(eKPINames.CCTSMsEvaluated); } try { if (recvMessage != null && !string.IsNullOrEmpty(tTopic)) // tTopic != null) { if (!ParseSimplex(tTopic, recvMessage, pQSender)) //NEW:2.06 - No More Local Host processing here { if (TheBaseAssets.MyServiceHostInfo.MaximumHops == 0 || recvMessage.HobCount() < TheBaseAssets.MyServiceHostInfo.MaximumHops) { if (!tTopic.StartsWith("CDE_CONNECT") || !TheBaseAssets.MyServiceHostInfo.AllowMessagesInConnect) // Should never get here if AllowMessagesInConnect is false, but avoid global publish just in case... { TheCDEKPIs.IncrementKPI(eKPINames.CCTSMsRelayed); TheCommCore.PublishCentral(tTopic, recvMessage, false, null, false, pQSender?.MyTargetNodeChannel?.IsTrustedSender ?? false); } else { // Message is part of a CDE_CONNECT: Republish it to enable single-post message sending (i.e. MSB/Service Gateway scenario) TheCDEKPIs.IncrementKPI(eKPINames.CCTSMsRelayed); // TODO SHould we have a separate KPI for this TheCommCore.PublishCentral(recvMessage, true, pQSender.MyTargetNodeChannel.IsTrustedSender); } } } else { if (pQSender?.MyTargetNodeChannel != null && pQSender?.MyTargetNodeChannel?.SenderType != cdeSenderType.CDE_JAVAJASON) { SendPulse = true; } } } } catch (Exception ee) { TheBaseAssets.MySYSLOG.WriteToLog(319, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("CoreComm", "Execute Command Parsing Error", eMsgLevel.l1_Error, ee.ToString())); } TheBaseAssets.MySYSLOG.WriteToLog(286, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM("CoreComm", $"Done with Do Execute Command for Topic:{tTopic}", eMsgLevel.l7_HostDebugMessage)); } } if (pRequestData.WebSocket == null) { if (DoSendBackBuffer) { SetResponseBuffer(pRequestData, pQSender.MyTargetNodeChannel, SendPulse, ""); } else if (SendPulse) { pQSender.SendPickupMessage(); //Pickup next message right away if pulse mode is on } } TheBaseAssets.MySYSLOG.WriteToLog(286, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM("CoreComm", "Leave Do Execute Command", eMsgLevel.l7_HostDebugMessage)); }
private void ReadHttpPage(TheRequestData pRequest, Guid MyAppGuid, string tMagixc, Action <TheRequestData> pSinkProcessResponse) //TheRelayAppInfo MyApp, { TheRelayAppInfo MyApp = TheThingRegistry.GetThingObjectByMID(MyBaseEngine.GetEngineName(), MyAppGuid) as TheRelayAppInfo; // MyRelayApps.MyMirrorCache.GetEntryByFunc(s => s.cdeMID.Equals(MyAppGuid)); if (MyApp == null) { if (pRequest.cdeN.Equals(TheBaseAssets.MyServiceHostInfo.MyDeviceInfo.DeviceID)) { TSM tTSM = new TSM(MyBaseEngine.GetEngineName(), "WEBRELAY_REQUEST") { PLB = pRequest.PostData }; pRequest.PostData = null; pRequest.ResponseBuffer = null; if (!string.IsNullOrEmpty(pRequest.CookieString)) { pRequest.CookieString += ";"; } else { pRequest.CookieString = ""; } pRequest.CookieString += tMagixc; if (string.IsNullOrEmpty(TheBaseAssets.MyServiceHostInfo.RootDir)) { pRequest.RequestUriString = pRequest.RequestUri.ToString(); } else { pRequest.RequestUriString = pRequest.RequestUri.Scheme + "://" + pRequest.RequestUri.Host + ":" + pRequest.RequestUri.Port + pRequest.cdeRealPage; if (!string.IsNullOrEmpty(pRequest.RequestUri.Query)) { pRequest.RequestUriString += "?" + pRequest.RequestUri.Query; } } TheBaseAssets.MySYSLOG.WriteToLog(400, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM(MyBaseEngine.GetEngineName(), string.Format("Requesting Page:{0}", pRequest.RequestUriString), eMsgLevel.l6_Debug)); tTSM.PLS = TheCommonUtils.SerializeObjectToJSONString(pRequest); tTSM.SID = pRequest.SessionState.GetSID(); TheCommCore.PublishCentral(tTSM); // .PublishToNode(MyApp.HostUrl, pRequest.SessionState.SScopeID, tTSM); } return; } if (TheCommonUtils.IsUrlLocalhost(MyApp.GetBaseThing().Address)) { TheCommonUtils.GetAnyFile(pRequest); if (tMagixc != null) { pRequest.CookieString = tMagixc; } pSinkProcessResponse(pRequest); } else { int relPathIndex = pRequest.RequestUri.AbsolutePath.IndexOf('/', 1); string relPath = relPathIndex == -1 ? "" : pRequest.RequestUri.AbsolutePath.Substring(relPathIndex + 1) + pRequest.RequestUri.Query; var tUri = pRequest.RequestUri.AbsolutePath.StartsWith("/CDEWRA") ? new Uri(MyApp.GetBaseThing().Address + MyApp.HomePage + relPath) : new Uri(MyApp.GetBaseThing().Address.TrimEnd('/') + pRequest.RequestUri.AbsolutePath + pRequest.RequestUri.Query); if (!string.IsNullOrEmpty(tMagixc)) { if (!string.IsNullOrEmpty(pRequest.CookieString)) { pRequest.CookieString += ";"; } else { pRequest.CookieString = ""; } pRequest.CookieString += tMagixc; } pRequest.RequestUri = tUri; pRequest.ErrorDescription = ""; pRequest.RequestCookies = pRequest.SessionState.StateCookies; if (!string.IsNullOrEmpty(MyApp.SUID) && !string.IsNullOrEmpty(MyApp.SPWD)) { pRequest.UID = MyApp.SUID; pRequest.PWD = MyApp.SPWD; } if (MyApp.IsHTTP10) { pRequest.HttpVersion = 1.0; } if (string.IsNullOrEmpty(MyApp.CloudUrl)) { MyApp.CloudUrl = TheBaseAssets.MyServiceHostInfo.GetPrimaryStationURL(false); } pRequest.Header = null; if (pRequest.PostData != null && pRequest.PostData.Length > 0) //MONO Relay might not work right! { TheREST MyRest = new TheREST(); MyRest.PostRESTAsync(pRequest, pSinkProcessResponse, pSinkProcessResponse); } else { TheREST.GetRESTAsync(pRequest, pSinkProcessResponse, pSinkProcessResponse); } TheBaseAssets.MySYSLOG.WriteToLog(400, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM(MyBaseEngine.GetEngineName(), string.Format("Requesting Page:{0} Sent", pRequest.RequestUri), eMsgLevel.l3_ImportantMessage)); } }
// KPIs in UI //public long PropertiesSent //{ // get { return (long) TheThing.GetSafePropertyNumber(MyBaseThing, "PropertiesSent"); } // set { TheThing.SetSafePropertyNumber(MyBaseThing, "PropertiesSent", value); } //} //public long PropertiesSentSinceStart //{ // get { return (long)TheThing.GetSafePropertyNumber(MyBaseThing, "PropertiesSentSinceStart"); } // set { TheThing.SetSafePropertyNumber(MyBaseThing, "PropertiesSentSinceStart", value); } //} //public double PropertiesPerSecond //{ // get { return TheThing.GetSafePropertyNumber(MyBaseThing, "PropertiesPerSecond"); } // set { TheThing.SetSafePropertyNumber(MyBaseThing, "PropertiesPerSecond", value); } //} //public double DataSentKBytesPerSecond //{ // get { return TheThing.GetSafePropertyNumber(MyBaseThing, "DataSentKBytesPerSecond"); } // set { TheThing.SetSafePropertyNumber(MyBaseThing, "DataSentKBytesPerSecond", value); } //} //public double DataSentKBytesSinceStart //{ // get { return TheThing.GetSafePropertyNumber(MyBaseThing, "DataSentKBytesSinceStart"); } // set { TheThing.SetSafePropertyNumber(MyBaseThing, "DataSentKBytesSinceStart", value); } //} //public double EventsPerSecond //{ // get { return TheThing.GetSafePropertyNumber(MyBaseThing, "EventsPerSecond"); } // set { TheThing.SetSafePropertyNumber(MyBaseThing, "EventsPerSecond", value); } //} //public long EventsSent //{ // get { return (long)TheThing.GetSafePropertyNumber(MyBaseThing, "EventsSent"); } // set { TheThing.SetSafePropertyNumber(MyBaseThing, "EventsSent", value); } //} //public long EventsSentSinceStart //{ // get { return (long)TheThing.GetSafePropertyNumber(MyBaseThing, "EventsSentSinceStart"); } // set { TheThing.SetSafePropertyNumber(MyBaseThing, "EventsSentSinceStart", value); } //} //public long PendingEvents //{ // get { return (long) TheThing.GetSafePropertyNumber(MyBaseThing, "PendingEvents"); } // set { TheThing.SetSafePropertyNumber(MyBaseThing, "PendingEvents", value); } //} //public DateTimeOffset KPITime //{ // get { return TheThing.GetSafePropertyDate(MyBaseThing, "KPITime"); } // set { TheThing.SetSafePropertyDate(MyBaseThing, "KPITime", value); } //} //public DateTimeOffset LastReceiveTime //{ // get { return TheThing.GetSafePropertyDate(MyBaseThing, nameof(LastReceiveTime)); } // set { TheThing.SetSafePropertyDate(MyBaseThing, nameof(LastReceiveTime), value); } //} #endregion public override void HandleMessage(ICDEThing sender, object pIncoming) { TheProcessMessage pMsg = pIncoming as TheProcessMessage; if (pMsg == null || pMsg.Message == null) { return; } var cmd = pMsg.Message.TXT.Split(':'); switch (cmd[0]) { case "MESHSENDER_DATA": if (IsConnected || AutoConnect) { //TheBaseAssets.MySYSLOG.WriteToLog(180001, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("Mesh Receiver", $"Received TSM with TXT MESHSENDER_DATA {this.MyBaseThing.FriendlyName}: {pMsg.Message.ToString()}", eMsgLevel.l6_Debug)); bool bSuccess = false; //bool bSendAck = true; string error = ""; bool bIsTargeted = pMsg.Topic.StartsWith("CDE_SYSTEMWIDE"); string correlationToken = null; if (cmd.Length >= 2) { correlationToken = cmd[1]; } string eventConverterName = null; if (cmd.Length >= 3) { eventConverterName = cmd[2]; } //if (EnableDataLogging) //{ // try // { // lock (dataLoggerLock) // { // System.IO.File.AppendAllText("meshreceiverdata.log", $"{{\"TimeReceived\":\"{DateTimeOffset.Now:O}\", \"PLS\": {pMsg.Message.PLS},\"TXT\":{pMsg.Message.TXT}}},\r\n"); // } // } // catch (Exception e) // { // TheBaseAssets.MySYSLOG.WriteToLog(180003, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("Mongo Writer", $"Unable to log data to file: {this.MyBaseThing.FriendlyName}", eMsgLevel.l3_ImportantMessage, e.ToString())); // } //} bSuccess = ProcessMessage(correlationToken, eventConverterName, pMsg.Message.TIM, pMsg.Message.PLS, pMsg.Message.ORG, bIsTargeted, out error, out var bSendAck); if (bSendAck) { TSM response = new TSM(MyBaseEngine.GetEngineName(), $"MESHSENDER_DATA_ACK:{correlationToken}:{bSuccess}:{error}"); response.QDX = pMsg.Message.QDX; TheBaseAssets.MySYSLOG.WriteToLog(180001, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM("Mesh Receiver", $"Sending ACK for {this.MyBaseThing.FriendlyName} to ORG '{pMsg.Message.ORG}'", eMsgLevel.l1_Error, response.TXT)); TheCommCore.PublishToOriginator(pMsg.Message, response, true); if (!bIsTargeted) { var notification = new TSM(MyBaseEngine.GetEngineName(), $"MESHRECEIVER_ACK_NOTIFY:;:{correlationToken}:;:{pMsg.Message.ORG}:;:{bIsTargeted}"); TheCommCore.PublishCentral(notification, false); } } } break; case "MESHRECEIVER_ACK_NOTIFY": { var ackNotifyParts = TheCommonUtils.cdeSplit(pMsg.Message.TXT, ":;:", false, false); if (ackNotifyParts.Length >= 4) { string correlationToken = ackNotifyParts[1]; string sourceORG = ackNotifyParts[2]; bool bIsTargeted = TheCommonUtils.CBool(ackNotifyParts[3]); _nodeOwnerManager.RegisterOwnerCandidate(correlationToken, sourceORG, pMsg.Message.ORG, bIsTargeted); } break; } case "MESHSENDER_PING": case "MESHSENDER_PING_ALL": { string correlationToken = "nocorrelationtoken"; if (cmd.Length > 1) { correlationToken = cmd[1]; } // MyBaseThing.LastMessage = DateTimeOffset.Now + String.Format(": {0} from {1}. Token {2}", cmd[0], TheCommonUtils.cdeGuidToString(pMsg.Message.GetOriginator()), correlationToken); MyBaseThing.LastMessage = $"{DateTimeOffset.Now}: {cmd[0]} from {TheCommonUtils.cdeGuidToString(pMsg.Message.GetOriginator())}. Token {correlationToken}"; //TSM response = new TSM(MyBaseEngine.GetEngineName(), String.Format("{0}_ACK:{1}", cmd[0], correlationToken), // String.Format("{0}:{1}:{2}:{3}", TheCommonUtils.cdeGuidToString(MyBaseThing.cdeMID), ++PingCounter, MyBaseThing.FriendlyName, IsConnected)); TSM response = new TSM(MyBaseEngine.GetEngineName(), $"{cmd[0]}_ACK:{correlationToken}", $"{TheCommonUtils.cdeGuidToString(MyBaseThing.cdeMID)}:{++PingCounter}:{MyBaseThing.FriendlyName}:{IsConnected}"); TheCommCore.PublishToOriginator(pMsg.Message, response, true); } break; default: base.HandleMessage(sender, pIncoming); break; } }
static readonly TimeSpan defaultRequestTimeout = new TimeSpan(0, 1, 0); // TODO make this configurable? /// <summary> /// Sends a TSM message to the targetThing and return the matching response message /// </summary> /// <param name="originator">Thing or engine to use for response messages. If NULL defaults to ContentService.</param> /// <param name="target">Thing or engine to which the message is to be sent.</param> /// <param name="messageName">Name of the message, as defined by the target thing. The response message will be messageName_RESPONSE.</param> /// <param name="txtParameters">Array of simple string parameters, to be attached to the message's TXT field, as defined by the target thing. txtParameters must not contain ":" characters.</param> /// <param name="PLS">String payload to be set as the message's PLS field, as defined by the target thing.</param> /// <param name="PLB">Binary pauload to be set as the message's PLB field, as defined by the target thing.</param> /// <param name="timeout">Time to wait for the response message. Can not exceed TheBaseAsset.MaxMessageResponseTimeout (default: 1 hour).</param> /// <returns>The response message as defined by the target thing. The response parameters and correlation token can be parsed using ParseRequestOrResponseMessage, if the target thing used the PublishResponseMessage or an equivalent message format. /// If the message times out or an error occured while sending the message, the return value will be null. /// </returns> public static Task <TSM> PublishRequestAsync(TheMessageAddress originator, TheMessageAddress target, string messageName, TimeSpan timeout, string[] txtParameters = null, string PLS = null, byte[] PLB = null) { Guid correlationToken = Guid.NewGuid(); if (originator == null) { originator = TheThingRegistry.GetBaseEngineAsThing(eEngineName.ContentService); } var msg = PrepareRequestMessage(originator, target, messageName, correlationToken, txtParameters, PLS, PLB); if (msg == null) { return(null); } if (timeout > MaxTimeOut) { timeout = MaxTimeOut; } if (timeout == TimeSpan.Zero) { timeout = defaultRequestTimeout; } var tcsResponse = new TaskCompletionSource <TSM>(); var callback = new Action <ICDEThing, object>((tSenderThing, responseMsgObj) => { var responseMsg = CheckResponseMessage(messageName, correlationToken, responseMsgObj); if (responseMsg != null) { var bReceived = tcsResponse.TrySetResult(responseMsg); if (bReceived) { TheSystemMessageLog.WriteLog(1000, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM("Thing Registry", $"Processed response message for {messageName}", eMsgLevel.l2_Warning, $"{correlationToken}: {responseMsg?.TXT}"), false); } else { TheSystemMessageLog.WriteLog(1000, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM("Thing Registry", $"Failed to process response message for {messageName}: timed out or double response", eMsgLevel.l2_Warning, $"{correlationToken}: {responseMsg?.TXT}"), false); } } else { responseMsg = (responseMsgObj as TheProcessMessage)?.Message; TheSystemMessageLog.WriteLog(1000, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM("Thing Registry", $"Ignoring response message for {messageName}", eMsgLevel.l2_Warning, $"{correlationToken}: {responseMsg?.TXT}"), false); } }); var originatorThingOrEngine = RegisterRequestCallback(originator, callback); if (originatorThingOrEngine == null) { return(null); } if (target.SendToProvisioningService) { TheISMManager.SendToProvisioningService(msg); } else if (target.Node != Guid.Empty) { TheCommCore.PublishToNode(target.Node, msg); } else { TheCommCore.PublishCentral(msg, true); } TheCommonUtils.TaskWaitTimeout(tcsResponse.Task, timeout).ContinueWith((t) => { UnregisterRequestCallback(originatorThingOrEngine, callback); var timedOut = tcsResponse.TrySetResult(null); // Will preserve value if actual result has already been set if (timedOut) { TheSystemMessageLog.WriteLog(1000, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM("Thing Registry", $"Timeout waiting for response message for {messageName}", eMsgLevel.l2_Warning, $"{correlationToken}"), false); } }); return(tcsResponse.Task); }
private void InterceptHttpRequest(TheRequestData pRequest, Guid MyApp, IBaseEngine MyBaseEngine, int pRequestTimeout) // TheRelayAppInfo MyApp) { if (MyApp == Guid.Empty) { return; } TheRequestData tOutBuffer = null; //NEW BY CM string tMagixc = Guid.NewGuid().ToString(); ReqBuffer.AddOrUpdateItem(TheCommonUtils.CGuid(tMagixc), null, null); if (!MyBaseEngine.GetEngineState().IsService) // || string.IsNullOrEmpty(MyApp.TargetUrl) || !TheCommonUtils.IsLocalhost(MyApp.HostUrl)) // !MyApp.HostUrl.Equals(TheBaseAssets.MyServiceHostInfo.MyStation URL)) { TSM tTSM = new TSM(MyBaseEngine.GetEngineName(), "WEBRELAY_REQUEST") { PLB = pRequest.PostData }; pRequest.PostData = null; pRequest.ResponseBuffer = null; if (!string.IsNullOrEmpty(pRequest.CookieString)) { pRequest.CookieString += ";"; } else { pRequest.CookieString = ""; } pRequest.CookieString += tMagixc; //if (string.IsNullOrEmpty(MyApp.CloudUrl)) MyApp.CloudUrl = TheBaseAssets.MyServiceHostInfo.GetPrimaryStationURL(false); if (string.IsNullOrEmpty(TheBaseAssets.MyServiceHostInfo.RootDir)) { pRequest.RequestUriString = pRequest.RequestUri.ToString(); } else { pRequest.RequestUriString = pRequest.RequestUri.Scheme + "://" + pRequest.RequestUri.Host + ":" + pRequest.RequestUri.Port + pRequest.cdeRealPage; if (!string.IsNullOrEmpty(pRequest.RequestUri.Query)) { pRequest.RequestUriString += "?" + pRequest.RequestUri.Query; } } TheBaseAssets.MySYSLOG.WriteToLog(400, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM(MyBaseEngine.GetEngineName(), string.Format("Requesting Page:{0}", pRequest.RequestUriString), eMsgLevel.l6_Debug)); tTSM.PLS = TheCommonUtils.SerializeObjectToJSONString(pRequest); tTSM.SID = pRequest.SessionState.GetSID(); //.SScopeID; TheCommCore.PublishCentral(tTSM); // .PublishToNode(MyApp.HostUrl, pRequest.SessionState.SScopeID, tTSM); } else { TheBaseAssets.MySYSLOG.WriteToLog(400, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM(MyBaseEngine.GetEngineName(), string.Format("AppID:{1} Requesting Page:{0}", pRequest.cdeRealPage, MyApp))); ReadHttpPage(pRequest, MyApp, tMagixc, sinkResults); } int SyncFailCount = 0; ManualResetEvent MyMRE = new ManualResetEvent(false); do { try { tOutBuffer = ReqBuffer.GetEntryByID(TheCommonUtils.CGuid(tMagixc)); if (tOutBuffer != null) { pRequest.ResponseBuffer = tOutBuffer.ResponseBuffer; pRequest.ResponseMimeType = tOutBuffer.ResponseMimeType; if (pRequest.SessionState.StateCookies == null) { pRequest.SessionState.StateCookies = new cdeConcurrentDictionary <string, string>(); } if (tOutBuffer.SessionState != null && tOutBuffer.SessionState.StateCookies != null && tOutBuffer != pRequest) { foreach (KeyValuePair <String, String> kvp in tOutBuffer.SessionState.StateCookies.GetDynamicEnumerable()) { string value; if (!pRequest.SessionState.StateCookies.TryGetValue(kvp.Key, out value)) { pRequest.SessionState.StateCookies.TryAdd(kvp.Key, kvp.Value); } else { pRequest.SessionState.StateCookies[kvp.Key] = kvp.Value; } } } if (!string.IsNullOrEmpty(tOutBuffer.ResponseBufferStr)) { pRequest.ResponseBufferStr = tOutBuffer.ResponseBufferStr; } else { if (pRequest.ResponseMimeType.StartsWith("text/html") || pRequest.ResponseMimeType.Contains("javascript")) //OK { pRequest.ResponseBufferStr = TheCommonUtils.CArray2UTF8String(tOutBuffer.ResponseBuffer); } } string tReqUri = pRequest.RequestUri.Host; if (pRequest.RequestUri.Port != 80) { tReqUri += ":" + pRequest.RequestUri.Port; } TheBaseAssets.MySYSLOG.WriteToLog(400, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM(MyBaseEngine.GetEngineName(), string.Format("Got Response Page:{0}", tReqUri), eMsgLevel.l6_Debug)); if (!string.IsNullOrEmpty(pRequest.ResponseBufferStr) && (pRequest.ResponseMimeType.StartsWith("text/html") || pRequest.ResponseMimeType.Contains("javascript")) && pRequest.ResponseBufferStr.IndexOf(tReqUri, StringComparison.CurrentCultureIgnoreCase) >= 0) { if (pRequest.SessionState.ARApp != null && pRequest.SessionState.ARApp != Guid.Empty) { TheRelayAppInfo tMyApp = TheThingRegistry.GetThingObjectByMID(MyBaseEngine.GetEngineName(), pRequest.SessionState.ARApp) as TheRelayAppInfo; //MyRelayApps.MyMirrorCache.GetEntryByFunc(s => s.cdeMID.Equals(pRequest.SessionState.ARApp)); if (tMyApp != null && tMyApp.CloudUrl != null) { Uri tCloudUri = TheCommonUtils.CUri(tMyApp.CloudUrl, false); if (!string.IsNullOrEmpty(pRequest.NewLocation)) { pRequest.NewLocation = pRequest.NewLocation.Replace(pRequest.RequestUri.Scheme + "://" + tReqUri, tCloudUri.Scheme + "://" + tCloudUri.Host + ":" + tCloudUri.Port); } TheBaseAssets.MySYSLOG.WriteToLog(400, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM(MyBaseEngine.GetEngineName(), string.Format("Patching Uri from:{0} to:{1}", tReqUri, tCloudUri), eMsgLevel.l6_Debug)); pRequest.ResponseBufferStr = pRequest.ResponseBufferStr.Replace(pRequest.RequestUri.Scheme + "://" + tReqUri, tCloudUri.Scheme + "://" + tCloudUri.Host + ":" + tCloudUri.Port); pRequest.ResponseBuffer = TheCommonUtils.CUTF8String2Array(pRequest.ResponseBufferStr); } } } break; } MyMRE.WaitOne(50); SyncFailCount++; if (SyncFailCount > (pRequestTimeout * 20)) { if (TheCommonUtils.IsMono()) { TheBaseAssets.MySYSLOG.WriteToLog(400, new TSM(MyBaseEngine.GetEngineName(), string.Format("Requesting Page:{0} FAILED", pRequest.cdeRealPage), eMsgLevel.l1_Error)); } else { TheBaseAssets.MySYSLOG.WriteToLog(400, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM(MyBaseEngine.GetEngineName(), string.Format("Requesting Page:{0} FAILED", pRequest.cdeRealPage), eMsgLevel.l1_Error)); } break; } } catch (Exception ee) { TheBaseAssets.MySYSLOG.WriteToLog(400, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(MyBaseEngine.GetEngineName(), string.Format("Error during HttpIntercept for Page:{0}", pRequest.cdeRealPage), eMsgLevel.l1_Error, ee.ToString())); } } while (tOutBuffer == null); if (MyMRE != null) { MyMRE = null; //.Dispose(); } if ((pRequest.ResponseBuffer == null && string.IsNullOrEmpty(pRequest.ResponseBufferStr)) || pRequest.StatusCode != 0) { if (pRequest.StatusCode == 0) { pRequest.StatusCode = 404; } } else { pRequest.AllowStatePush = true; pRequest.StatusCode = 200; } ReqBuffer.RemoveAnItemByID(TheCommonUtils.CGuid(tMagixc), null); }
void SendEmail(string pText) { try { MailMessage mail = new MailMessage(); SmtpClient SmtpServer = new SmtpClient(MyBaseThing.Address); mail.From = new MailAddress(FromAddress); string receipt = Recipient; string credentials = Credentials; if (TheCommonUtils.IsNullOrWhiteSpace(receipt)) { receipt = "*****@*****.**"; } mail.To.Add(receipt); if (string.IsNullOrEmpty(SubjectText)) { mail.Subject = TheBaseAssets.MyServiceHostInfo.ApplicationName + " Message"; } else { mail.Subject = SubjectText; } if (!TheCommonUtils.IsNullOrWhiteSpace(pText)) { mail.Body = pText; } else { mail.Body = MessageText; } if (credentials.Equals("Admin")) { string AdminUsername = MyBaseEngine.GetBaseThing().GetProperty("AdminUsername", false).ToString(); string AdminServer = MyBaseEngine.GetBaseThing().GetProperty("AdminServer", false).ToString(); string AdminPassword = MyBaseEngine.GetBaseThing().GetProperty("AdminPassword", false).GetValue().ToString(); int AdminPort = int.Parse(MyBaseEngine.GetBaseThing().GetProperty("AdminPort", false).ToString()); SmtpServer.Credentials = new System.Net.NetworkCredential(AdminUsername, AdminPassword); SmtpServer.Host = AdminServer; SmtpServer.Port = AdminPort; string AdminSsl = MyBaseEngine.GetBaseThing().GetProperty("AdminSsl", false).ToString(); if (AdminSsl.Equals("True")) { SmtpServer.EnableSsl = true; } } else { SmtpServer.Port = Port; SmtpServer.Credentials = new System.Net.NetworkCredential(UserName, Password); if (UseSsl) { SmtpServer.EnableSsl = true; } } SmtpServer.Send(mail); ResultText = "Mail Sent to " + Recipient; TSM tTSM = new TSM(MyBaseEngine.GetEngineName(), "SET_LAST_MSG", string.Format("eMail: Subject:{2} Body:{3} From {0} at {1}", TheBaseAssets.MyServiceHostInfo.MyStationName, DateTimeOffset.Now, SubjectText, mail.Body)); MyBaseEngine.ProcessMessage(new TheProcessMessage(tTSM)); TheCommCore.PublishCentral(tTSM); } catch (Exception ex) { ResultText = ex.ToString(); } }