示例#1
0
 /// <summary>
 /// Main call to store values in the StorageService
 /// </summary>
 /// <typeparam name="T">Type of class to be stored</typeparam>
 /// <param name="MyValue">Dictionary of Values of the class to be stored</param>
 /// <param name="pCMD">Command for the store process</param>
 /// <param name="pMagicID">MagicID to be used for back-publish</param>
 /// <param name="pCallBack">If set, and the call came from a local service, the sevices calls back without using the communication system</param>
 public void EdgeDataStore <T>(Dictionary <string, T> MyValue, eSCMD pCMD, string pMagicID, Action <TSM> pCallBack, string pTableName)
 {
     if (TheCDEngines.MyIStorageService != null)
     {
         string serializedXML = TheStorageUtilities.SerializeDataToStore(MyValue, pMagicID, pCMD, typeof(T).Equals(typeof(cdeP)) ? null : pTableName);
         string post          = "CDE_EDGESTORE";
         post += ":";
         if (!string.IsNullOrEmpty(pMagicID) && pCallBack != null)
         {
             MyTimedCallbacks.AddAnItem(new TheTimedCallback()
             {
                 cdeMID = TheCommonUtils.CGuid(pMagicID), MyCallback = pCallBack
             });
             post += pMagicID;
         }
         if (typeof(T).Equals(typeof(cdeP)))
         {
             post += ":" + TheStorageUtilities.GenerateUniqueIDFromType(typeof(TheThing), pTableName);
         }
         TSM tTSM = new TSM(MyBaseEngine.GetEngineName(), post, serializedXML);
         if (TheCDEngines.MyIStorageService.GetBaseEngine().GetEngineState().IsService)
         {
             ProcessStorageServiceCommands(tTSM, pCallBack, true);
         }
         //else //Later for Remote Storage
         //{
         //    tTSM.SetToServiceOnly(true);
         //    TheCommCore.PublishCentral(tTSM);
         //}
     }
 }
示例#2
0
        /// <summary>
        /// Handles Messages sent from a host sub-engine to its clients
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="pIncoming"></param>
        public override void HandleMessage(ICDEThing sender, object pIncoming)
        {
            TheProcessMessage pMsg = pIncoming as TheProcessMessage;

            if (pMsg == null)
            {
                return;
            }

            string[] cmd = pMsg.Message.TXT.Split(':');
            switch (cmd[0])
            {
            case "CDE_INITIALIZED":
                MyBaseEngine.SetInitialized(pMsg.Message);
                break;

            case "GET_CHARTDATA":
                Type td = typeof(CDMyC3.TheC3ChartsFactory);
                TheChartFactory.PushChartsData(TheCommonUtils.CGuid(pMsg.Message.PLS), pMsg.Message.GetOriginator(), td.AssemblyQualifiedName);
                break;

            default:
                break;
            }
        }
示例#3
0
        private void UpdateUx()
        {
            ThePropertyBag.MergeUXBagFromProperties(CountBar?.PropertyBag, MyBaseThing);
            SetCtrlType();

            if (TimestampField != null)
            {
                TimestampField?.SetUXProperty(Guid.Empty, $"Visibility={ShowTimestamp}");
                ChangeTimestampField?.SetUXProperty(Guid.Empty, $"Visibility={ShowChangeTimestamp}");
            }

            TheThingRegistry.UnmapPropertyMapper(MapperGuid);
            if (!string.IsNullOrEmpty(MyBaseThing.Address))
            {
                MapperGuid = TheThingRegistry.PropertyMapper(TheCommonUtils.CGuid(MyBaseThing.Address), TheThing.GetSafePropertyString(MyBaseThing, "SourceProp"), MyBaseThing.cdeMID, "Value", true);
                if (MapperGuid != Guid.Empty)
                {
                    MyBaseThing.StatusLevel = 1;
                    MyBaseThing.LastMessage = "Mapper engaged";
                }
                else
                {
                    MyBaseThing.StatusLevel = 2;
                    MyBaseThing.LastMessage = "Mapper failed to engaged";
                }
            }
            else
            {
                MyBaseThing.StatusLevel = 0;
                MyBaseThing.LastMessage = "Mapper not engaged";
            }
        }
示例#4
0
        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);
            }
        }
示例#5
0
        private void UpdateUx(TheThing pThing)
        {
            ThePropertyBag.MergeUXBagFromProperties(MySampleControl?.PropertyBag, pThing);
            SetCtrlType();

            TheThingRegistry.UnmapPropertyMapper(MapperGuid);
            if (!string.IsNullOrEmpty(pThing.Address))
            {
                MapperGuid = TheThingRegistry.PropertyMapper(TheCommonUtils.CGuid(pThing.Address), TheThing.GetSafePropertyString(pThing, "SourceProp"), pThing.cdeMID, "Value", true);
                if (MapperGuid != Guid.Empty)
                {
                    pThing.StatusLevel = 1;
                    pThing.LastMessage = "Mapper engaged";
                }
                else
                {
                    pThing.StatusLevel = 2;
                    pThing.LastMessage = "Mapper failed to engaged";
                }
            }
            else
            {
                pThing.StatusLevel = 0;
                pThing.LastMessage = "Mapper not engaged";
            }
        }
示例#6
0
        public static bool Init(string strGuid, string strUserScopeID, string strAppID)
        {
            TheScopeManager.SetApplicationID(strAppID); // SDK Non-Commercial ID. FOR COMMERCIAL APP GET THIS ID FROM C-LABS!

            TheBaseAssets.MyServiceHostInfo = new TheServiceHostInfo(cdeHostType.Application)
            {
                ApplicationName  = "$safeprojectname$",                            // Friendly Name of Application
                cdeMID           = TheCommonUtils.CGuid(strGuid),
                Title            = "My-Relay (C) $registeredorganization$ $year$", // Title of this Host Service
                ApplicationTitle = "$safeprojectname$",                            // Title visible in the NMI Portal
                CurrentVersion   = 1.0001,                                         // Version of this Service, increase this number when you publish a new version that the store displays the correct update icon
                DebugLevel       = eDEBUG_LEVELS.OFF,                              // Define a DebugLevel for the SystemLog output.
                SiteName         = "http://cloud.c-labs.com",                      // Link to the main Cloud Node of this host. this is not required and for documentation only

                ISMMainExecutable = "$safeprojectname$",                           // Name of the executable (without .exe)
                IgnoreAdminCheck  = true,                                          // if set to true, the host will not start if launched without admin priviledges.

                LocalServiceRoute = "LOCALHOST",                                   // Will be replaced by the full DNS name of the host during startup.
                MyStationPort     = 8700,                                          // Port for REST access to this Host node. If your PC already uses port 80 for another webserver, change this port. We recommend using Port 8700 and higher for UPnP to work properly.
                MyStationWSPort   = 8701,                                          // Enables WebSockets on the station port. If UseRandomDeviceID is false, this Value cannot be changed here once the App runs for the first time. On Windows 8 and higher running under "Adminitrator" you can use the same port
            };

            if (strUserScopeID.Length > 0)
            {
                strScopeID = strUserScopeID;
            }
            else
            {
                strScopeID = TheScopeManager.GenerateNewScopeID();  // TIP: instead of creating a new random ID every time your host starts, you can put a breakpoint in the next line, record the ID and feed it in the "SetScopeIDFromEasyID". Or even set a fixed ScopeID here. (FOR TESTING ONLY!!)
            }
            return(true);
        }
示例#7
0
        private void OnDownloadClick(ICDEThing pThing, object pPara)
        {
            TheProcessMessage pMSG = pPara as TheProcessMessage;

            if (pMSG == null || pMSG.Message == null)
            {
                return;
            }

            string[] cmd = pMSG.Message.PLS.Split(':');
            if (cmd.Length > 2)
            {
                TheThing tThing = TheThingRegistry.GetThingByMID("*", TheCommonUtils.CGuid(cmd[2]), true);
                if (tThing == null)
                {
                    return;
                }

                TSM tFilePush = new TSM(eEngineName.ContentService, string.Format("CDE_FILE:{0}.JSON:application/zip", tThing.FriendlyName))
                {
                    SID = pMSG.Message.SID,
                    PLS = "bin",
                    PLB = TheCommonUtils.CUTF8String2Array(TheCommonUtils.SerializeObjectToJSONString(tThing))
                };
                TheCommCore.PublishToOriginator(pMSG.Message, tFilePush);
            }
        }
示例#8
0
        public static bool IsTokenValid(Dictionary <string, string> aParameters)
        {
            bool bSuccess = false;

            CleanupOldTokens();

            if (aParameters.TryGetValue("key", out string strToken))
            {
                if (!String.IsNullOrEmpty(strToken))
                {
                    Guid     guidToken = TheCommonUtils.CGuid(strToken);
                    DateTime dt;

                    if (dictValidAccessTokens != null)
                    {
                        if (dictValidAccessTokens.TryGetValue(guidToken, out dt))
                        {
                            bSuccess = true;
                        }
                    }
                }
            }


            return(bSuccess);
        }
        IEnumerable <JSonOpcArrayElement> GetJSONArray(TheThingStore thingEvent)
        {
            // TODO Replace with linkid some identifier that represents the activated instance/customer, and make this more efficient (avoid or cache thing registry lookup)
            string linkid;
            var    tThing = TheThingRegistry.GetThingByMID("*", TheCommonUtils.CGuid(thingEvent.cdeMID), true);

            if (tThing != null && !String.IsNullOrEmpty(tThing.FriendlyName))
            {
                linkid = tThing.FriendlyName;
            }
            else
            {
                if (thingEvent.PB.ContainsKey("Address"))
                {
                    linkid = TheCommonUtils.CStr(thingEvent.PB["Address"]);
                }
                else
                {
                    if (tThing != null)
                    {
                        linkid = tThing.Address;
                    }
                    else
                    {
                        linkid = TheCommonUtils.cdeGuidToString(thingEvent.cdeMID);
                    }
                }
            }

            var jsonArray = new List <JSonOpcArrayElement>();

            jsonArray.AddRange(thingEvent.PB.Select(propKV => GetJSONArrayElement(linkid, propKV.Key, thingEvent.cdeCTIM, propKV.Value)));
            return(jsonArray.OrderBy(ev => ev.sourcetimestamp));
        }
示例#10
0
        /// <summary>
        /// Requests the capabilities of the Server
        /// </summary>
        /// <param name="pMagicID">MagicID to be used for back-publish</param>
        /// <param name="pCallBack">If set, and the call came from a local service, the sevices calls back without using the communication system</param>
        public void EdgeStorageServerRequestCaps(string pMagicID, Action <TSM> pCallBack)
        {
            if (TheCDEngines.MyIStorageService == null || TheCDEngines.MyIStorageService.GetBaseEngine().GetEngineState().IsService)
            {
                return;
            }
            string serializedXML = TheCommonUtils.SerializeObjectToJSONString(TheCDEngines.MyIStorageService.GetStorageCaps());
            string post          = "CDE_GETEDGECAPS";

            if (pMagicID.Length > 0 && pCallBack != null)
            {
                MyTimedCallbacks.AddAnItem(new TheTimedCallback()
                {
                    cdeMID = TheCommonUtils.CGuid(pMagicID), MyCallback = pCallBack
                });
                post += ":" + pMagicID;
            }
            TSM tTSM = new TSM(MyBaseEngine.GetEngineName(), post, serializedXML);

            if (TheCDEngines.MyIStorageService.GetBaseEngine().GetEngineState().IsService)
            {
                ProcessStorageServiceCommands(tTSM, pCallBack, true);
            }
            //else //Later for Remote Storage
            //{
            //    tTSM.SetToServiceOnly(true);
            //    TheCommCore.PublishCentral(tTSM);
            //}
        }
示例#11
0
 // Override if new properties in a derived class need to be considered in the comparison
 internal virtual bool IsEqual(TheSenderThing senderThingToAdd)
 {
     return
         (senderThingToAdd != null
          //&& cdeMID == senderThingToAdd.cdeMID
          && ChangeBufferLatency == senderThingToAdd.ChangeBufferLatency &&
          ChangeBufferTimeBucketSize == senderThingToAdd.ChangeBufferTimeBucketSize &&
          ChangeNaNToNull == senderThingToAdd.ChangeNaNToNull &&
          Disable == senderThingToAdd.Disable &&
          PartitionKey == senderThingToAdd.PartitionKey &&
          EventFormat == senderThingToAdd.EventFormat &&
          StaticProperties == senderThingToAdd.StaticProperties &&
          AddThingIdentity == senderThingToAdd.AddThingIdentity &&
          TheCommonUtils.CGuid(ThingMID) == TheCommonUtils.CGuid(senderThingToAdd.ThingMID) &&
          PropertiesIncluded == senderThingToAdd.PropertiesIncluded &&
          PropertiesExcluded == senderThingToAdd.PropertiesExcluded &&
          (ForceAllProperties ?? false) == (senderThingToAdd.ForceAllProperties ?? false) &&
          (ForceConfigProperties ?? false) == (senderThingToAdd.ForceConfigProperties ?? false) &&
          PreserveOrder == senderThingToAdd.PreserveOrder &&
          SendUnchangedValue == senderThingToAdd.SendUnchangedValue &&
          (SendInitialValues ?? false) == (senderThingToAdd.SendInitialValues ?? false) &&
          (IgnoreExistingHistory ?? false) == (senderThingToAdd.IgnoreExistingHistory ?? false) &&
          TokenExpirationInHours == senderThingToAdd.TokenExpirationInHours &&
          KeepDurableHistory == senderThingToAdd.KeepDurableHistory &&
          MaxHistoryCount == senderThingToAdd.MaxHistoryCount &&
          MaxHistoryTime == senderThingToAdd.MaxHistoryTime &&
          IgnorePartialFailure == senderThingToAdd.IgnorePartialFailure &&
          EngineName == senderThingToAdd.EngineName &&
          FriendlyName == senderThingToAdd.FriendlyName &&
          DeviceType == senderThingToAdd.DeviceType &&
          PropertiesToMatch == senderThingToAdd.PropertiesToMatch &&
          ContinueMatching == senderThingToAdd.ContinueMatching
         );
 }
示例#12
0
 public TheThing GetThing()
 {
     if (_pThing == null)
     {
         _pThing = TheThingRegistry.GetThingByMID("*", TheCommonUtils.CGuid(this.ThingMID), true);
     }
     return(_pThing);
 }
示例#13
0
        virtual internal TheThing.TheThingSubscription GetSubscriptionInfo(bool?bGeneralize)
        {
            TheThingReference thingReference;
            var tThing = GetThing();

            if (tThing != null)
            {
                thingReference = new TheThingReference(tThing);
                if (bGeneralize == true)
                {
                    thingReference.ThingMID = null;
                }
            }
            else
            {
                thingReference = new TheThingReference()
                {
                    ThingMID          = (bGeneralize == false && TheCommonUtils.CGuid(this.ThingMID) != Guid.Empty) ? (Guid?)TheCommonUtils.CGuid(this.ThingMID) : null,
                    EngineName        = this.EngineName,
                    DeviceType        = this.DeviceType,
                    FriendlyName      = this.FriendlyName,
                    PropertiesToMatch = TheSenderThing.CStringToDict(this.PropertiesToMatch),
                };
            }

            var sub = new TheThing.TheThingSubscription
            {
                SubscriptionId   = this.cdeMID,
                AddThingIdentity = this.AddThingIdentity,
                SamplingWindow   = this.ChangeBufferTimeBucketSize,
                ContinueMatching = this.ContinueMatching,
                CooldownPeriod   = this.ChangeBufferLatency,
                ThingReference   = thingReference,

                EventFormat            = this.EventFormat,
                ForceAllProperties     = this.ForceAllProperties,
                ForceConfigProperties  = this.ForceConfigProperties,
                IgnoreExistingHistory  = this.IgnoreExistingHistory,
                IgnorePartialFailure   = this.IgnorePartialFailure,
                KeepDurableHistory     = this.KeepDurableHistory,
                MaxHistoryCount        = this.MaxHistoryCount,
                MaxHistoryTime         = this.MaxHistoryTime,
                PartitionKey           = this.PartitionKey,
                PreserveOrder          = this.PreserveOrder,
                PropertiesExcluded     = TheCommonUtils.CStringToList(this.PropertiesExcluded, ','),
                PropertiesIncluded     = TheCommonUtils.CStringToList(this.PropertiesIncluded, ','),
                SendInitialValues      = this.SendInitialValues,
                SendUnchangedValue     = this.SendUnchangedValue,
                StaticProperties       = TheSenderThing.CStringToDict(this.StaticProperties),
                TargetName             = this.TargetName,
                TargetType             = this.TargetType,
                TargetUnit             = this.TargetUnit,
                TokenExpirationInHours = this.TokenExpirationInHours,
            };

            return(sub);
        }
示例#14
0
 private void sinkNewConnection(TheSessionState arg1)
 {
     VisitorCount++;
     if (arg1?.SiteName == null || TheCommonUtils.CGuid(arg1.SiteName) != Guid.Empty || arg1.SiteName == "::1")
     {
         return;
     }
     MyVisitorLog?.LogVisitor(arg1.SiteName, arg1.InitReferer);
 }
        /// <summary>
        /// If this is a service the SimplexProc event will be called when the C-DEngine receives a new event sent by a subscriber to this service
        /// </summary>
        /// <param name="pMsg">The Message to be Processed</param>
        private void ProcessServiceMessage(TheProcessMessage pMsg)
        {
            string[] cmd = pMsg.Message.TXT.Split(':');
            switch (cmd[0]) //string 2 cases
            {
            case "WEBRELAY_RESPONSE":
                TheRequestData tState = TheCommonUtils.DeserializeJSONStringToObject <TheRequestData>(pMsg.Message.PLS);
                if (pMsg.Message.PLB != null && pMsg.Message.PLB.Length > 0)
                {
                    tState.ResponseBuffer = pMsg.Message.PLB;
                }
                tState.RequestUri = new Uri(tState.RequestUriString);
                //tState.SessionState = new TheSessionState() { SScopeID = pMsg.SID };
                sinkResults(tState);
                break;

            case "WEBRELAY_REQUEST":
                TheRequestData tData = TheCommonUtils.DeserializeJSONStringToObject <TheRequestData>(pMsg.Message.PLS);
                if (tData != null)
                {
                    tData.RequestUri = new Uri(tData.RequestUriString);
                    //tData.SessionState = new TheSessionState() { SScopeID = pMsg.SID };
                    if (pMsg.Message.PLB != null && pMsg.Message.PLB.Length > 0)
                    {
                        tData.PostData = pMsg.Message.PLB;
                    }
                    tData.CookieObject = pMsg.Message;
                    ReadHttpPage(tData, tData.SessionState.ARApp, null, sinkProcessResponse);
                    //InterceptHttpRequest(tData,tData.SessionState.ARApp);
                }
                break;

            case "WEBRELAY_REQUESTWRA":
                TSM             tTSM    = new TSM();
                List <TheThing> webApps = TheThingRegistry.GetThingsOfEngine(MyBaseEngine.GetEngineName());
                foreach (TheThing tApp in webApps)
                {
                    if (tApp.Address.Equals(pMsg.Message.PLS))
                    {
                        tTSM.PLS = $"/CDEWRA{tApp.cdeMID}" + TheThing.GetSafePropertyString(tApp, "HomePage");
                        break;
                    }
                }
                if (!string.IsNullOrEmpty(tTSM.PLS))
                {
                    string[]    org          = pMsg.Message.ORG.Split(':');
                    TheThing    senderThing  = TheThingRegistry.GetThingByMID(TheCommonUtils.CGuid(org[1]), true);
                    IBaseEngine senderEngine = TheThingRegistry.GetBaseEngine(senderThing, true);
                    tTSM.ENG = senderEngine.GetEngineName();
                    tTSM.TXT = "RESPONSEWRA";
                    TheCommCore.PublishToOriginator(pMsg.Message, tTSM, true);
                }
                break;
            }
        }
示例#16
0
        void CreateScriptEditTemplate()
        {
            MSE = new TheFormInfo(new Guid("{00000000-6AD1-45AE-BE61-96AF02329613}"), eEngineName.NMIService, "Script Editor", null)
            {
                DefaultView = eDefaultView.Form, IsNotAutoLoading = true, PropertyBag = new nmiCtrlFormTemplate {
                    TableReference = $"{TheThing.GetSafeThingGuid(MyBaseThing, "SCRIPT_TABLE")}", TileWidth = 12
                }
            };
            TheNMIEngine.AddFormToThingUX(MyBaseThing, MSE, "CMyForm", "Script Editor", 100, 3, 0xF0, null, null, new ThePropertyBag()
            {
                "Visibility=false"
            });

            TheNMIEngine.AddSmartControl(MyBaseThing, MSE, eFieldType.SingleEnded, 50, 0, 0, "Script Name", "ScriptName", new nmiCtrlSingleEnded()
            {
                TileWidth = 12
            });
            TheNMIEngine.AddSmartControl(MyBaseThing, MSE, eFieldType.TextArea, 60, 2, 0, null, "ScriptRaw", new nmiCtrlTextArea()
            {
                NoTE = true, TileWidth = 12, TileHeight = 12
            });
            TheNMIEngine.AddSmartControl(MyBaseThing, MSE, eFieldType.TextArea, 110, 0, 0, "Last Error", "ScriptError", new nmiCtrlTextArea()
            {
                TileWidth = 12, TileHeight = 3
            });
            var but = TheNMIEngine.AddSmartControl(MyBaseThing, MSE, eFieldType.TileButton, 100, 2, 0, "Save Script", null, new nmiCtrlTileButton()
            {
                TileWidth = 6, NoTE = true, TileHeight = 1, ClassName = "cdeGoodActionButton"
            });

            but.RegisterUXEvent(MyBaseThing, eUXEvents.OnClick, "SaveScript", (sender, pPara) =>
            {
                if (!(pPara is TheProcessMessage pMSG) || pMSG.Message == null)
                {
                    return;
                }
                var tP = pMSG.Message.PLS.Split(':');
                var t  = MyScriptTableStorage.MyMirrorCache.GetEntryByID(TheCommonUtils.CGuid(tP[2]));
                try
                {
                    var Res       = TheCommonUtils.DeserializeJSONStringToObject <TheScript>(t.ScriptRaw);
                    t.ScriptError = "ok";
                    MSE.Reload(pMSG, true);
                }
                catch (Exception ee)
                {
                    t.ScriptError = ee.ToString();
                    MSE.Reload(pMSG, true);
                    return;
                }
                File.WriteAllText(t.FileName, t.ScriptRaw);
                TheCommCore.PublishToOriginator(pMSG.Message, new TSM(eEngineName.NMIService, "NMI_TTS", TheThing.GetSafeThingGuid(MyBaseThing, "SCRIPT_TABLE").ToString()));  //This is the same as the TTS:.. from above...but with an additional roundtrip to the Relay
            });
 private void InterceptHttpRequest(TheRequestData pRequest)
 {
     if (pRequest == null || pRequest.SessionState == null)
     {
         return;
     }
     if (pRequest.cdeRealPage.StartsWith("/CDEWRA"))
     {
         pRequest.SessionState.ARApp = TheCommonUtils.CGuid(pRequest.cdeRealPage.Substring(7, Guid.Empty.ToString().Length));
     }
     InterceptHttpRequest(pRequest, pRequest.SessionState.ARApp, MyBaseEngine, RequestTimeout);
 }
示例#18
0
 private void sinkRequestMeshInfo(TheRequestData request)
 {
     if (request != null)
     {
         request.ResponseMimeType = "application/json";
         string errorText = "";
         Dictionary <string, string> tQ = TheCommonUtils.ParseQueryString(request.RequestUri?.Query);
         if (tQ != null)
         {
             tQ.TryGetValue("MESHINFOTOKEN", out string meshInfoToken);
             if (tQ.TryGetValue("ORG", out string tOrg))
             {
                 Guid requestorMID = TheCommonUtils.CGuid(tOrg);
                 if (requestorMID != Guid.Empty)
                 {
                     TheMeshInfoStatus meshInfoStatus = TheQueuedSenderRegistry.GetMeshInfoForNodeID(requestorMID, meshInfoToken);
                     if (string.IsNullOrEmpty(meshInfoStatus?.StatusMessage))
                     {
                         request.StatusCode     = (int)eHttpStatusCode.OK;
                         request.ResponseBuffer = TheCommonUtils.CUTF8String2Array(TheCommonUtils.SerializeObjectToJSONString(meshInfoStatus.MeshInfo));
                     }
                     else
                     {
                         request.StatusCode = meshInfoStatus.StatusCode; //Better if meshInfoStatus also defines this as there are different messages (wrong MIT, too frequent tests etc)
                         errorText          = meshInfoStatus.StatusMessage;
                     }
                 }
                 else
                 {
                     request.StatusCode = 400;
                     errorText          = "Invalid or badly formed ORG parameter.";
                 }
             }
             else
             {
                 request.StatusCode = 400;
                 errorText          = "No ORG parameter found for mesh info request.";
             }
         }
         else
         {
             request.StatusCode = (int)eHttpStatusCode.AccessDenied;
             errorText          = "Access denied";
         }
         if (!string.IsNullOrEmpty(errorText))
         {
             TheErrorResponse errorResponse = new TheErrorResponse {
                 Error = errorText, CTIM = DateTimeOffset.Now
             };
             request.ResponseBuffer = TheCommonUtils.CUTF8String2Array(TheCommonUtils.SerializeObjectToJSONString(errorResponse));
         }
     }
 }
        private void sinkResults(TheRequestData resBytes)
        {
            TheBaseAssets.MySYSLOG.WriteToLog(400, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM(MyBaseEngine.GetEngineName(), string.Format("Result Bytes:{1} with Cookie:{2} For Page:{0} Sent", resBytes.cdeRealPage, resBytes.ResponseBuffer != null ? resBytes.ResponseBuffer.Length : 0, resBytes.CookieString), eMsgLevel.l4_Message));
            if (!string.IsNullOrEmpty(resBytes.CookieString))
            {
                string[] tCookies = resBytes.CookieString.Split(';');
                if (ReqBuffer.ContainsID(TheCommonUtils.CGuid(tCookies[tCookies.Length - 1])))
                {
                    if (tCookies.Length > 1)
                    {
                        resBytes.CookieString = "";
                        for (int i = 0; i < tCookies.Length - 1; i++)
                        {
                            if (resBytes.CookieString.Length > 0)
                            {
                                resBytes.CookieString += ";";
                            }
                            resBytes.CookieString += tCookies[i];
                        }
                    }
                    if (resBytes.ResponseBuffer == null && !string.IsNullOrEmpty(resBytes.ErrorDescription))
                    {
                        resBytes.ResponseBuffer = TheCommonUtils.CUTF8String2Array(resBytes.ErrorDescription);
                    }

                    //TODO: HackProcessing - Advanced Hack Table: Replace X with Y
                    //Console.WriteLine("SR:" + resBytes.cdeRealPage.ToLower());

                    /*
                     * if (resBytes.cdeRealPage.ToLower().StartsWith("/js/default.js"))
                     * {
                     *  string t = TheCommonUtils.CArray2UTF8String(resBytes.ResponseBuffer);
                     *  //var checkLocal = document.URL replace with return true; //TODO: Hack List
                     *  if (t.IndexOf("var checkLocal=document.URL;") >= 0)
                     *      t = t.Replace("var checkLocal=document.URL;", "return true;");
                     *  //if (t.IndexOf("return _.isObject(user)&&user.isLogin()") >= 0)
                     *  //  t = t.Replace("return _.isObject(user)&&user.isLogin()", "return true;");
                     *  t = t.Replace("window.location.hostname", "window.location.hostname+':'+window.location.port");
                     *  resBytes.ResponseBuffer = TheCommonUtils.CUTF8String2Array(t);
                     * }*/

                    ReqBuffer.AddOrUpdateItem(TheCommonUtils.CGuid(tCookies[tCookies.Length - 1]), resBytes, null);
                }
                else
                {
                    TheBaseAssets.MySYSLOG.WriteToLog(400, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM(MyBaseEngine.GetEngineName(), string.Format("Result Bytes For Page:{0} NoLonger in ReqBuffer", resBytes.cdeRealPage), eMsgLevel.l2_Warning));
                }
            }
        }
示例#20
0
        void sinkDeleteLog(StoreEventArgs pArgs)
        {
            Guid tPluginG = TheCommonUtils.CGuid(pArgs.Para);

            if (tPluginG == Guid.Empty)
            {
                return;
            }
            var tPlugin = MyLogFiles.GetEntryByID(tPluginG);

            if (tPlugin != null && File.Exists(tPlugin.FileName))
            {
                File.Delete(tPlugin.FileName);
            }
        }
示例#21
0
        private void StartVerifier()
        {
            var thing = TheThingRegistry.GetThingByMID("*", TheCommonUtils.CGuid(this.ThingToVerify));

            if (thing != null)
            {
                thing.RegisterEvent(eThingEvents.PropertySet, OnThingUpdate);
                m_thingToVerify = thing;
                g_sw            = new System.Diagnostics.Stopwatch();
                g_sw.Start();
                MyBaseThing.StatusLevel = 1;
                IsStarted = true;
                MyBaseThing.LastMessage = "Verifier started";
            }
        }
示例#22
0
        private void RemoveTrigger(TheRule tRule, bool DoForce)
        {
            if (TheCDEngines.MyThingEngine == null || !TheBaseAssets.MasterSwitch)
            {
                return;
            }
            if (tRule.IsRuleActive || DoForce)
            {
                if (TheThingRegistry.HasThingsWithFunc(MyBaseEngine.GetEngineName(), s => s.cdeMID != tRule.GetBaseThing().cdeMID&&
                                                       TheThing.GetSafePropertyString(s, "TriggerObject") == tRule.TriggerObject && TheThing.GetSafePropertyBool(s, "IsRuleActive")))
                {
                    return;
                }
                switch (tRule.TriggerObjectType)
                {
                default:
                    TheThing tTriggerThing = TheThingRegistry.GetThingByMID("*", TheCommonUtils.CGuid(tRule.TriggerObject));
                    if (tTriggerThing != null)
                    {
                        cdeP tProp = tTriggerThing.GetProperty(tRule.TriggerProperty);
                        if (tProp != null)
                        {
                            tProp.UnregisterEvent(eThingEvents.PropertyChanged, sinkRuleAction);
                        }
                    }
                    break;

                case "CDE_ENGINE":
                    TheThing tBase = TheThingRegistry.GetBaseEngineAsThing(tRule.TriggerObject);
                    if (tBase != null)
                    {
                        tBase.UnregisterEvent(eEngineEvents.IncomingMessage, sinkRuleIncoming);
                    }
                    break;

                case "CDE_EVENTFIRED":
                    TheThing tBaseE = TheThingRegistry.GetThingByID("*", tRule.TriggerObject);
                    if (tBaseE != null)
                    {
                        tBaseE.UnregisterEvent(tRule.TriggerProperty, sinkRuleThingEvent);
                    }
                    break;
                }
                tRule.IsRuleActive  = false;
                tRule.IsRuleRunning = false;
                tRule.IsRuleWaiting = true;
            }
        }
示例#23
0
 /// <summary>
 /// Sends a TSM with a custom topic with a possible target and Source Sender - in Par with ICDECommChannel
 /// </summary>
 /// <param name="tTSM"></param>
 /// <param name="pTopic"></param>
 /// <param name="pTarget"></param>
 /// <param name="pSender"></param>
 /// <returns></returns>
 public bool SendTSM(TSM tTSM, string pTopic = null, Guid?pTarget = null, Guid?pSender = null)
 {
     if (MyQSender == null || tTSM == null)
     {
         return(false);
     }
     if (!tTSM.ORG.Contains(":") && pSender != null)
     {
         tTSM.ORG += $":{TheCommonUtils.CGuid(pSender)}";
     }
     if (string.IsNullOrEmpty(tTSM.SID))
     {
         tTSM.SID = mSScope;
     }
     return(MyQSender.SendQueued(TheBaseAssets.MyScopeManager.AddScopeID(pTopic, RS, ref tTSM.SID, false, true), tTSM, false, TheCommonUtils.CGuid(pTarget), pTopic, RS, null));     //GRSI: rare
 }
示例#24
0
        public async void ConnectToCloud(string pScopeID)
        {
            if (TheBaseAssets.MasterSwitch)
            {
                await UpdateLog("SYSTEM: Already Connected");

                return;
            }
            TheScopeManager.SetApplicationID("/cVjzPfjlO;{@QMj:jWpW]HKKEmed[llSlNUAtoE`]G?"); //SDK Non-Commercial ID. FOR COMMERCIAL APP GET THIS ID FROM C-LABS!

            TheBaseAssets.MyServiceHostInfo = new TheServiceHostInfo(cdeHostType.Application)
            {
                ApplicationName  = "My-Relay",                                                     //Friendly Name of Application
                cdeMID           = TheCommonUtils.CGuid("{4DB8E613-093F-4581-8E84-FE60FFA05A8E}"), //TODO: Give a Unique ID to this Host Service
                Title            = "HackChatXAML (C) C-Labs. Corp 2019",                           //Title of this Host Service
                ApplicationTitle = "HackChat",                                                     //Title visible in the NMI Portal
                CurrentVersion   = 1.0001,                                                         //Version of this Service, increase this number when you publish a new version that the store displays the correct update icon
                DebugLevel       = eDEBUG_LEVELS.VERBOSE,                                          //Define a DebugLevel for the SystemLog output.
                SiteName         = "http://cloud.c-labs.com",                                      //Link to the main Cloud Node of this host. this is not required and for documentation only

                ISMMainExecutable = "HCXaml",                                                      //Name of the executable (without .exe)
            };

            #region Args Parsing
            Dictionary <string, string> ArgList = new Dictionary <string, string>();
            #endregion

            ArgList.Add("ServiceRoute", "wss://cloud.c-labs.com");
            ArgList.Add("UseRandomDeviceID", "true");                        //Set the Scope Access Level
            ArgList.Add("ScopeUserLevel", "255");                            //Set the Scope Access Level
            TheBaseApplication MyBaseApplication = new TheBaseApplication(); //Create a new Base (C-DEngine IoT) Application
            TheCDEngines.eventAllEnginesStarted += sinkReady;
            var tChatPlugin = new cdePluginService1();
            if (!MyBaseApplication.StartBaseApplication(tChatPlugin, ArgList))         //Start the C-DEngine Application. If a PluginService class is added DIRECTLY to the host project you can instantiate the Service here replacing the null with "new cdePluginService1()"
            {
                await UpdateLog("SYSTEM: Start BaseApp failed!");

                return;                                                         //If the Application fails to start, quit the app. StartBaseApplication returns very fast as all the C-DEngine code is running asynchronously
            }
            else
            {
                TheScopeManager.SetScopeIDFromEasyID(pScopeID);
                await UpdateLog("SYSTEM: Start BaseApp started!");
            }
        }
示例#25
0
        public bool LogEvent(string ActionText)
        {
            TheEventLogData tSec = new TheEventLogData
            {
                EventTime   = DateTimeOffset.Now,
                EventLevel  = eMsgLevel.l4_Message,
                StationName = TheBaseAssets.MyServiceHostInfo.GetPrimaryStationURL(false),
                EventName   = TheCommonUtils.GenerateFinalStr(MyBaseThing.FriendlyName, MyBaseThing)
            };

            if (!string.IsNullOrEmpty(tSec.EventName))
            {
                tSec.EventName = tSec.EventName.Replace("%OldValue%", TriggerOldValue);
            }
            tSec.EventTrigger = TheThingRegistry.GetThingByMID(TheCommonUtils.CGuid(TriggerObject))?.FriendlyName;
            tSec.ActionObject = ActionText;
            var tEng = MyBaseEngine.GetBaseThing().GetObject() as TheRulesEngine;

            tEng?.LogEvent(tSec);
            return(true);
        }
        private static TSM CheckResponseMessage(string messageName, Guid correlationToken, object responseMsgObj)
        {
            if (!(responseMsgObj is TheProcessMessage processMsg))
            {
                return(null);
            }
            var responseMsg = processMsg.Message;

            if (!responseMsg.TXT.StartsWith(messageName + "_RESPONSE:"))
            {
                return(null);
            }

            var parts = responseMsg.TXT.Split(new[] { ':' }, 3);

            if (parts.Length < 2 || TheCommonUtils.CGuid(parts[1]) != correlationToken)
            {
                return(null);
            }
            return(responseMsg);
        }
示例#27
0
        public static bool Init(string strGuid, string strUserScopeID, string strAppID)
        {
            TheScopeManager.SetApplicationID(strAppID); // SDK Non-Commercial ID. FOR COMMERCIAL APP GET THIS ID FROM C-LABS!

            TheBaseAssets.MyServiceHostInfo = new TheServiceHostInfo(cdeHostType.Application)
            {
                ApplicationName  = "AppHostTest",             // Friendly Name of Application
                cdeMID           = TheCommonUtils.CGuid(strGuid),
                Title            = "My-Relay (C)  2019",      // Title of this Host Service
                ApplicationTitle = "AppHostTest",             // Title visible in the NMI Portal
                CurrentVersion   = 1.0001,                    // Version of this Service, increase this number when you publish a new version that the store displays the correct update icon
                SiteName         = "http://cloud.c-labs.com", // Link to the main Cloud Node of this host. this is not required and for documentation only

                ISMMainExecutable = "AppHostTest",            // Name of the executable (without .exe)

                ServiceRoute = "https://cloud.c-labs.com",
            };

            strScopeID = strUserScopeID;

            settings = new TheBaseAppSettings();

            // Directly add keys to settings table.
            settings.AddKey("UseTcpListenerInsteadOfHttpListener", true);
            settings.SetKeyUnlessAlreadySet("DEBUGLEVEL", eDEBUG_LEVELS.OFF);

            // Select either user manager or scope manager. But not both!!
            settings.InitUserManager();
            // strScopeID = settings.InitScopeManager(strScopeID, 255);

            // Rely on helper functions to initialize other settings.
            settings.InitEnvironmentVarSettings(true, true);
            settings.DisableCodeSigningValidation(true);
            settings.InitClientBinPersistence(false);

            // Initialize ports for web server and web sockets.
            settings.InitWebPorts(8720, 8721);

            return(true);
        }
示例#28
0
 /// <summary>
 /// Executes a SQL query against the store of the MyClass
 /// </summary>
 /// <param name="MyClass">Type of the Class determining the store to run the query against</param>
 /// <param name="SQLExec">SQL statement to execute</param>
 /// <param name="pColFilter"></param>
 /// <param name="pMagicID">MagicID to be used for back-publish</param>
 /// <param name="pCallBack">If set, and the call came from a local service, the sevices calls back without using the communication system</param>
 public void EdgeStorageExecuteSql(Type MyClass, string SQLExec, string pColFilter, string pMagicID, Action <TSM> pCallBack, string pTableName)
 {
     if (!MyBaseEngine.GetEngineState().IsSimulated)
     {
         if (TheCDEngines.MyIStorageService != null)
         {
             string tableName = pTableName;
             string post      = "CDE_EXECUTESQL";
             post += ":";
             if (pMagicID.Length > 0 && pCallBack != null)
             {
                 MyTimedCallbacks.AddAnItem(new TheTimedCallback()
                 {
                     cdeMID = TheCommonUtils.CGuid(pMagicID), MyCallback = pCallBack
                 });
                 post += pMagicID;
             }
             if (MyClass != null)
             {
                 if (MyClass.Equals(typeof(cdeP)))
                 {
                     tableName = null;
                     post     += ":" + TheStorageUtilities.GenerateUniqueIDFromType(typeof(TheThing), pTableName);
                 }
             }
             string serializedXML = TheStorageUtilities.SerializeDataToExecute(MyClass, pMagicID, SQLExec, pColFilter, tableName);
             TSM    tTSM          = new TSM(MyBaseEngine.GetEngineName(), post, serializedXML);
             if (TheCDEngines.MyIStorageService.GetBaseEngine().GetEngineState().IsService)
             {
                 ProcessStorageServiceCommands(tTSM, pCallBack, true);
             }
             //else //Later for Remote Storage
             //{
             //    tTSM.SetToServiceOnly(true);
             //    TheCommCore.PublishCentral(tTSM);
             //}
         }
     }
 }
示例#29
0
        public TheProviderInfo GetSensorProviderInfo()
        {
            var providerInfoProp = this.GetProperty(strSource);
            var subscriptionId   = TheCommonUtils.CGuid(providerInfoProp?.GetProperty(nameof(TheThing.TheSensorSubscription.SubscriptionId), false));

            var providerInfo = new TheProviderInfo
            {
                ProviderMid = TheCommonUtils.CGuidNullable(providerInfoProp?.GetProperty(nameof(TheProviderInfo.ProviderMid), false)),

                Subscription = new TheThing.TheSensorSubscription
                {
                    SensorId       = TheCommonUtils.CStrNullable(providerInfoProp?.GetProperty(nameof(TheThing.TheSensorSubscription.SensorId), false)),
                    SampleRate     = TheCommonUtils.CIntNullable(providerInfoProp?.GetProperty(nameof(TheThing.TheSensorSubscription.SampleRate), false)),
                    SubscriptionId = subscriptionId != Guid.Empty ? subscriptionId : this.cdeMID,
                    TargetThing    = new TheThingReference(this.OwnerThing),
                    TargetProperty = cdeP.GetPropertyPath(this),
                    ExtensionData  = ReadDictionaryFromProperties(providerInfoProp, TheProviderInfo.KnownProperties),
                }
            };

            return(providerInfo);
        }
示例#30
0
        public static bool Init(string strGuid, string strUserScopeID)
        {
            TheScopeManager.SetApplicationID(strAppID); // SDK Non-Commercial ID. FOR COMMERCIAL APP GET THIS ID FROM C-LABS!

            TheBaseAssets.MyServiceHostInfo = new TheServiceHostInfo(cdeHostType.Application)
            {
                ApplicationName  = "AppHostTest",             // Friendly Name of Application
                cdeMID           = TheCommonUtils.CGuid(strGuid),
                Title            = "My-Relay (C)  2019",      // Title of this Host Service
                ApplicationTitle = "AppHostTest",             // Title visible in the NMI Portal
                CurrentVersion   = 1.0001,                    // Version of this Service, increase this number when you publish a new version that the store displays the correct update icon
                SiteName         = "http://cloud.c-labs.com", // Link to the main Cloud Node of this host. this is not required and for documentation only

                ISMMainExecutable = "AppHostTest",            // Name of the executable (without .exe)

                // CloudServiceRoute = "https://cloud.c-labs.com",
                MyStationWSPort = 0,
            };

            strScopeID = strUserScopeID;

            return(true);
        }