Example #1
0
        async void HandleMessageAsync(ICDEThing pSender, object para)
        {
            TheProcessMessage tMsg = para as TheProcessMessage;

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

            var tCmd = tMsg.Message.TXT.Split(':');

            switch (tCmd[0])
            {
            case "MsgChatHello":
                try
                {
                    var t = TheCommonUtils.DeserializeJSONStringToObject <MsgChatHello>(tMsg.Message.PLS);
                    await UpdateLog($"{t.SenderName}: {t.Message}");
                } catch (Exception)
                {
                    await UpdateLog($"SOMEBODY SENT ILLEGAL JSON");
                }
                break;
            }
        }
Example #2
0
 public override string ProcessEventData(TheThing thing, object evnt, DateTimeOffset defaultTimestamp)
 {
     string error = null;
     string json = DecodeEventAsString(evnt);
     if (json == null)
     {
         error = "Invalid payload";
     }
     else
     {
         MeasurementPayload payload = null;
         try
         {
             payload = TheCommonUtils.DeserializeJSONStringToObject<MeasurementPayload>(json);
             if (payload == null)
             {
                 error = "No data in payload";
             }
             else
             {
                 // TODO Implement deserializer (not customer requirement at this point)
             }
         }
         catch (Exception e)
         {
             error = e.ToString();
         }
     }
     return error;
 }
        public void HandleMessage(ICDEThing sender, object pIncoming)
        {
            TheProcessMessage pMsg = pIncoming as TheProcessMessage;

            if (pMsg == null)
            {
                return;
            }

            var tCmd = pMsg.Message.TXT.Split(':');

            switch (tCmd[0])
            {
            case "CDE_NODETOPICS":
                sinkServiceInfo(pMsg?.Message);
                break;

            case "ADD_FOOTPRINT":
                var Tf = TheCommonUtils.DeserializeJSONStringToObject <NodeTypeScript>(pMsg.Message.PLS);
                if (Tf?.NodeTypes != null && Tf.NodeTypes.Count > 0)
                {
                    MyFootPrints.AddItems(Tf.NodeTypes, null);
                }
                TheCommCore.PublishToOriginator(pMsg.Message, new TSM(pMsg.Message.ENG, $"{tCmd[0]}_RESPONSE{(tCmd.Length>1?$":{tCmd[1]}":"")}", "{\"RESPONSE\":\"SUCCESS\"}"), true);
                break;
            }
        }
Example #4
0
        //private static byte[] clabsLicensePublicRSAKeyCSPBlob = new byte[] { 7, 2, 0, 0, 0, 36, 0, 0, 82, 83, 65, 50, 0, 4, 0, 0, 1, 0, 1, 0, 21, 17, 123, 167, 63, 93, 243, 184, 12, 109, 232, 229, 15, 154, 130, 63, 171, 242, 129, 156, 33, 47, 93, 236, 161, 94, 27, 145, 129, 214, 104, 73, 192, 224, 213, 189, 96, 209, 38, 39, 218, 167, 198, 34, 110, 90, 247, 14, 152, 46, 48, 67, 89, 20, 198, 220, 136, 149, 7, 5, 223, 53, 239, 113, 192, 76, 157, 90, 114, 71, 54, 2, 171, 128, 254, 96, 9, 109, 124, 197, 161, 158, 242, 92, 127, 135, 141, 149, 123, 127, 4, 84, 189, 22, 10, 191, 110, 108, 178, 190, 73, 162, 75, 36, 160, 23, 73, 184, 170, 195, 180, 80, 86, 79, 74, 97, 185, 223, 233, 221, 116, 40, 177, 128, 54, 73, 17, 173, 249, 31, 64, 15, 125, 18, 197, 136, 150, 66, 98, 91, 38, 118, 192, 167, 246, 239, 49, 193, 161, 168, 183, 228, 180, 27, 33, 8, 132, 28, 69, 2, 4, 134, 82, 135, 234, 40, 216, 175, 139, 227, 58, 55, 227, 118, 158, 44, 173, 113, 33, 177, 212, 171, 92, 122, 129, 142, 129, 100, 216, 155, 58, 215, 253, 56, 69, 112, 108, 253, 69, 171, 231, 131, 99, 133, 97, 93, 166, 59, 12, 241, 207, 5, 238, 77, 7, 5, 188, 236, 190, 240, 15, 86, 124, 219, 98, 152, 45, 209, 93, 169, 66, 89, 116, 113, 131, 104, 129, 187, 37, 68, 216, 82, 225, 139, 82, 120, 229, 67, 199, 10, 94, 240, 2, 22, 218, 205, 161, 112, 155, 226, 165, 71, 105, 53, 254, 148, 44, 84, 247, 136, 176, 235, 81, 23, 166, 114, 95, 220, 172, 169, 145, 50, 134, 144, 61, 190, 37, 66, 215, 205, 130, 149, 35, 94, 104, 154, 8, 44, 150, 85, 255, 141, 105, 1, 252, 28, 128, 125, 104, 85, 44, 106, 246, 165, 215, 180, 153, 219, 132, 28, 21, 225, 202, 83, 122, 53, 138, 211, 208, 87, 112, 241, 200, 223, 130, 195, 165, 178, 234, 14, 20, 38, 35, 213, 87, 108, 89, 147, 198, 188, 192, 109, 236, 146, 57, 109, 150, 149, 75, 247, 100, 67, 171, 26, 212, 221, 125, 117, 2, 131, 7, 134, 14, 225, 101, 41, 199, 142, 36, 181, 127, 180, 10, 129, 234, 142, 66, 16, 18, 220, 77, 53, 32, 188, 124, 1, 73, 227, 142, 2, 186, 42, 85, 173, 35, 252, 247, 143, 196, 246, 209, 120, 245, 223, 108, 188, 24, 16, 138, 27, 39, 83, 105, 155, 158, 6, 29, 203, 165, 89, 240, 154, 199, 199, 151, 250, 65, 63, 249, 36, 127, 42, 66, 199, 57, 126, 138, 152, 249, 173, 203, 108, 129, 220, 242, 15, 69, 119, 248, 26, 147, 234, 231, 116, 223, 60, 93, 30, 197, 97, 201, 153, 161, 131, 236, 36, 191, 222, 237, 51, 23, 53, 176, 10, 13, 238, 231, 52, 44, 6, 241, 130, 119, 7, 255, 86, 184, 179, 201, 157, 32, 34, 50, 169, 204, 16, 8, 102, 178, 153, 106, 198, 191, 3, 162, 153, 101, 235, 198, 245, 193, 87, 180, 34, 70, 117, 162, 201, 109, 106, 149, 167, 227, 128, 203, 225, 36, 103, 197, 235, 212, 94, 242, 106, 209, 80, 4, 175, 229, 182, 71, 95, 18, 8, 141, 210, 171, 135, 111, 40, 199, 97, 102, 185, 234, 91, 60, 232, 215, 218, 66, 169, 37, 200, 255, 5 };
#if !CDE_NET35 && !CDE_NET4
        /// <summary>
        /// This function reads (deserializes) licenses from existing license files in a directory for each skuid.
        /// </summary>
        /// <param name="licenseDirectory"></param>
        /// <param name="publicKeyCSPBlobs"></param>
        /// <param name="licenses"></param>
        /// <returns></returns>
        public static bool ReadLicensesForActivationKey(string licenseDirectory, List <byte[]> publicKeyCSPBlobs, out List <TheLicense> licenses)
        {
            licenses = new List <TheLicense>();
            try
            {
                var licenseFileContainer = Directory.EnumerateFiles(licenseDirectory, "*.cdex"); // TODO Review license file deployment mechanism and naming
                foreach (var containerFile in licenseFileContainer)
                {
                    using (var zipFileStream = new FileStream(containerFile, FileMode.Open, FileAccess.Read))
                    {
                        using (var zipArchive = new ZipArchive(zipFileStream, ZipArchiveMode.Read))
                        {
                            foreach (var licenseFile in zipArchive.Entries)
                            {
                                if (licenseFile.Name.EndsWith(".cdel"))
                                {
                                    using (var fileStream = licenseFile.Open())
                                    {
                                        var licenseBytes = new byte[fileStream.Length];
                                        if (fileStream.Read(licenseBytes, 0, licenseBytes.Length) == licenseBytes.Length)
                                        {
                                            var licenseJson = Encoding.UTF8.GetString(licenseBytes);
                                            var license     = TheCommonUtils.DeserializeJSONStringToObject <TheLicense>(licenseJson);
                                            if (!license.ValidateSignature(publicKeyCSPBlobs))
                                            {
                                                //Console.WriteLine("Invalid or unrecognized signature on license {0}", licenseFile);
                                                return(false);
                                            }
                                            licenses.Add(license);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                var licenseFiles = Directory.EnumerateFiles(licenseDirectory, "*.cdel"); // TODO Review license file deployment mechanism and naming
                foreach (var licenseFile in licenseFiles)
                {
                    var licenseJson = File.ReadAllText(licenseFile);
                    var license     = TheCommonUtils.DeserializeJSONStringToObject <TheLicense>(licenseJson);
                    if (!license.ValidateSignature(publicKeyCSPBlobs))
                    {
                        //Console.WriteLine("Invalid or unrecognized signature on license {0}", licenseFile);
                        return(false);
                    }
                    licenses.Add(license);
                }
            }
            catch (Exception)
            {
                //Console.WriteLine("Failed to extract license:" + ee.ToString());
                return(false);
            }

            return(true);
        }
Example #5
0
        public static List <T> ReadDataLog <T>(string filePath)
        {
            var json = File.ReadAllText(filePath);

            json = "[" + json + "]";
            var entries = TheCommonUtils.DeserializeJSONStringToObject <List <T> >(json);

            return(entries);
        }
Example #6
0
 /// <summary>
 /// Places any additional properties of a derived class into TheThing.TheSensorSubscription.ExtensionData
 /// </summary>
 /// <returns></returns>
 public virtual TheThing.TheSensorSubscription GetBaseSubscription()
 {
     if (this.GetType().IsSubclassOf(typeof(TheThing.TheSensorSubscription)))
     {
         var baseJson         = TheCommonUtils.SerializeObjectToJSONString(this);
         var baseSubscription = TheCommonUtils.DeserializeJSONStringToObject <TheThing.TheSensorSubscription>(baseJson);
         return(baseSubscription);
     }
     return(this);
 }
        /// <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;
            }
        }
Example #8
0
        public static TheLicense ParseLicense(string licenseText, List <byte[]> publicKeyCSPBlobs)
        {
            var license = TheCommonUtils.DeserializeJSONStringToObject <TheLicense>(licenseText);

            if (!license.ValidateSignature(publicKeyCSPBlobs))
            {
                //Console.WriteLine("Invalid or unrecognized signature on license {0}", licenseFile);
                return(null);
            }
            return(license);
        }
Example #9
0
        private async Task <bool> Initialize(OPCUAParameters opcUAParameters, ThingCreationParameters thingCreation)
        {
            if (thingCreation == null)
            {
                thingCreation = new ThingCreationParameters();
            }

            Dictionary <string, object> properties;

            if (opcUAParameters != null)
            {
                try
                {
                    properties = TheCommonUtils.DeserializeJSONStringToObject <Dictionary <string, object> >(TheCommonUtils.SerializeObjectToJSONString(opcUAParameters));
                }
                catch
                {
                    return(false);
                }
            }
            else
            {
                properties = new Dictionary <string, object>();
            }

            var tTaskForThing = TheThingRegistry.CreateOwnedThingAsync(new TheThingRegistry.MsgCreateThingRequestV1
            {
                EngineName       = TheOPCUAClientEngines.EngineName,
                DeviceType       = eOPCUAClientDeviceTypes.RemoteServer,
                Address          = ServerAddress,
                CreateIfNotExist = thingCreation.CreateIfNotExist,
                FriendlyName     = thingCreation.FriendlyName,
                Hidden           = thingCreation.Hidden,
                ReadOnly         = thingCreation.ReadOnly,
                InstanceId       = thingCreation.InstanceId,
                OwnerAddress     = OwnerAddress,
                Properties       = properties,
            }, new TheMessageAddress {
                Node = TheBaseAssets.MyServiceHostInfo.MyDeviceInfo.DeviceID
            }, new TimeSpan(0, 0, 30));
            var tThing = await tTaskForThing;

            if (tThing == null)
            {
                return(false);
            }

            OpcThingAddress = tThing;
            _opcThing       = tThing;
            RegisterEvent(eOPCUAClientEvents.ConnectComplete, sinkConnected);
            RegisterEvent(eOPCUAClientEvents.ConnectFailed, sinkConnectFailure);
            RegisterEvent(eOPCUAClientEvents.DisconnectComplete, sinkDisconnected);
            return(true);
        }
Example #10
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
            });
        public override string ProcessEventData(TheThing thing, object evnt, DateTimeOffset defaultTimestamp)
        {
            if (thing == null)
            {
                return("P08 Event Converter does not support thing mapping");
            }
            List <JSonOpcArrayElement> payload = null;
            string error = null;
            string json  = DecodeEventAsString(evnt);

            if (json == null)
            {
                error = "Invalid payload";
            }
            else
            {
                try
                {
                    payload = TheCommonUtils.DeserializeJSONStringToObject <List <JSonOpcArrayElement> >(json);
                    //payload = TheCommonUtils.DeserializeJSONStringToObject<List<JSonArrayElement>>(json);
                    if (payload == null || payload.Count == 0)
                    {
                        error = "No data in payload";
                    }
                    else
                    {
                        foreach (var prop in payload)
                        {
                            if (prop != null)
                            {
                                if (prop.identifier != null)
                                {
                                    var tProp = thing.SetProperty(prop.identifier, prop.value, new DateTimeOffset(prop.sourcetimestamp, DateTimeOffset.Now.Offset));
                                    // TODO Capture servertimestamp
                                }
                                else
                                {
                                }
                            }
                            else
                            {
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    error = e.ToString();
                }
            }
            return(error);
        }
Example #12
0
        private static Task <IEnumerable <object> > LoadThingUpdatesAsync(string fileName)
        {
            if (fileName.ToLowerInvariant() != "meshsenderdata.log") // We allow this filename so one can use the immediate local output from the mesh sender, all others are sanitized and must be effectively uploaded via the file uploader
            {
                fileName = TheCommonUtils.cdeFixupFileName(fileName);
            }
            var fileContent = File.ReadAllText(fileName, Encoding.UTF8);

            if (!fileContent.StartsWith("["))
            {
                fileContent = "[" + fileContent + "]";
            }
            var logEntries = TheCommonUtils.DeserializeJSONStringToObject <List <Dictionary <string, object> > >(fileContent);

            return(TheCommonUtils.TaskFromResult(logEntries.Where(e => e.ContainsKey("PLS")).Select(e => e["PLS"])));
        }
        void sinkServiceInfo(TSM pMsgMessage)
        {
            if (string.IsNullOrEmpty(pMsgMessage?.PLS))
            {
                return;
            }
            var MyInfo = TheCommonUtils.DeserializeJSONStringToObject <List <TheNodeTopics> >(pMsgMessage.PLS);

            int bk = 0;

            foreach (TheFootPrints tf in MyFootPrints.MyMirrorCache.TheValues)
            {
                tf.Counter = 0;
                tf.IsDirty = false;
            }
            if (MyInfo?.Count > 0)
            {
                foreach (var tIn in MyInfo)
                {
                    if (tIn.NodeType == cdeSenderType.CDE_JAVAJASON)
                    {
                        bk++;
                    }
                    else
                    {
                        foreach (TheFootPrints tf in MyFootPrints.MyMirrorCache.TheValues)
                        {
                            List <string> tFs = TheCommonUtils.CStringToList(tf.Footprint, ';');
                            if (IsListInList(tIn.Topics, tFs) && (tf.ExactCount == 0 || tf.ExactCount == tIn.Topics.Count))
                            {
                                tf.Counter++;
                                tf.IsDirty = true;
                            }
                        }
                    }
                }
                TheThing.SetSafePropertyNumber(MyBaseThing, "BrowserCount", bk);
            }
            foreach (TheFootPrints tf in MyFootPrints.MyMirrorCache.TheValues)
            {
                if (tf.IsDirty || tf.Counter == 0)
                {
                    MyFootPrints.UpdateItem(tf);
                    TheThing.SetSafePropertyNumber(MyBaseThing, $"{tf.NodeType}_Count", tf.Counter);
                }
            }
        }
Example #14
0
        private static TheScript LoadScript(string scriptFile)
        {
            var scriptText = File.ReadAllText(scriptFile);

            //var scriptText = File.ReadAllText(@"test.json");
            scriptText = Regex.Replace(scriptText, @"(?:jsonFragment\()(.*)(?:\))", (m) =>
            {
                return(TheCommonUtils.GenerateFinalStr(m.Groups[1].Value));
            });
            var script = TheCommonUtils.DeserializeJSONStringToObject <TheScript>(scriptText);

            if (string.IsNullOrEmpty(script.Name))
            {
                script.Name = Path.GetFileNameWithoutExtension(scriptFile);
            }
            script.FileName  = scriptFile;
            script.ScriptRaw = scriptText;
            return(script);
        }
Example #15
0
        internal void sinkProcessLocation(TheRequestData pLocationState)
        {
            if (pLocationState.ResponseBuffer == null)
            {
                return;
            }
            TheVisitorLogData tlog = pLocationState.CookieObject as TheVisitorLogData;

            if (tlog != null)
            {
                MyLocation = tlog;
            }
            if (MyLocation == null)
            {
                MyLocation = new TheVisitorLogData();
            }

            string pLocation = TheCommonUtils.CArray2UTF8String(pLocationState.ResponseBuffer);

            if (!string.IsNullOrEmpty(pLocation))
            {
                try
                {
                    TheVisitorLogData tIP = TheCommonUtils.DeserializeJSONStringToObject <TheVisitorLogData>(pLocation);
                    if (tIP != null)
                    {
                        MyLocation.ip          = tIP.ip;
                        MyLocation.latitude    = tIP.latitude;
                        MyLocation.longitude   = tIP.longitude;
                        MyLocation.region_code = tIP.region_code;
                        MyLocation.region_name = tIP.region_name;
                        MyLocation.zip         = tIP.zip;
                        MyBaseThing?.FireEvent("NewVisitorLogged", MyBaseThing, null, true);
                        //TheREST.GetRESTAsync(new Uri(string.Format("http://a4544535456.api.wxbug.net/getLiveWeatherRSS.aspx?ACode=a4544535456&lat={0}&long={1}&UnitType=1&OutputType=1", MyLocation.Latitude, MyLocation.Longitude)), 0, MyWeather.sinkProcessWeather, null);
                    }
                }
                catch (Exception ee)
                {
                    TheBaseAssets.MySYSLOG.WriteToLog(512, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("VisitorLog", "Error processing Location ", eMsgLevel.l1_Error, ee.ToString() + ":::" + pLocation));
                }
            }
            MyVisitorLogStore?.UpdateItem(MyLocation);
        }
Example #16
0
 public void HandleMessage(TheProcessMessage msg)
 {
     if (msg.Message.TXT.StartsWith(MessageToken.RegistryAlive) ||
         msg.Message.TXT.StartsWith(MessageToken.DiscoveryResponse) ||
         msg.Message.TXT.StartsWith(MessageToken.SubscribeTrigger))
     {
         var registryIdentity = TheCommonUtils.DeserializeJSONStringToObject <RegistryIdentity>(msg.Message.PLS);
         HandleMessage(msg.Message.ORG, registryIdentity.instanceId, msg.Message.TXT, msg.Message);
     }
     else if (msg.Message.TXT.StartsWith(MessageToken.SubscribeResponse))
     {
         var subscribeResponse = TheCommonUtils.DeserializeJSONStringToObject <RegistrySubscriptionResponse>(msg.Message.PLS);
         HandleMessage(msg.Message.ORG, subscribeResponse.instanceId, msg.Message.TXT, msg.Message);
     }
     else
     {
         HandleMessage(msg.Message.ORG, null, msg.Message.TXT, msg.Message);
     }
 }
Example #17
0
        internal static TheFOR GetScreenOptions(Guid FormId, TheClientInfo pClientInfo, TheFormInfo pInfo)
        {
            TheFOR tso = null;

            if (pInfo != null && !string.IsNullOrEmpty(pInfo.ModelID))
            {
                var tMods = pInfo.ModelID.Split(';');
                foreach (string tM in tMods)
                {
                    string tPlS1 = TheCommonUtils.LoadStringFromDisk($"FormORs\\{tM}.cdeFOR", null);
                    if (!string.IsNullOrEmpty(tPlS1))
                    {
                        TheFOR Ttso = TheCommonUtils.DeserializeJSONStringToObject <TheFOR>(tPlS1);
                        tso = SetTSO(tso, Ttso);
                        if (!string.IsNullOrEmpty(Ttso?.StartGroup))
                        {
                            pInfo.PropertyBag = new ThePropertyBag {
                                $"StartGroup={Ttso.StartGroup}"
                            }
                        }
                        ;
                    }
                }
            }

            string tPlS = TheCommonUtils.LoadStringFromDisk($"{pClientInfo.UserID}\\{FormId}.cdeFOR", null);

            if (!string.IsNullOrEmpty(tPlS))
            {
                TheFOR Ttso = TheCommonUtils.DeserializeJSONStringToObject <TheFOR>(tPlS);
                tso = SetTSO(tso, Ttso, true);
                if (pInfo != null && !string.IsNullOrEmpty(Ttso?.StartGroup))
                {
                    pInfo.PropertyBag = new ThePropertyBag {
                        $"StartGroup={Ttso.StartGroup}"
                    }
                }
                ;
            }
            return(tso);
        }
Example #18
0
        private void ProcessPubSubMessage(DateTimeOffset time, string channel, string message)
        {
            try
            {
                var pubSubMessage = TheCommonUtils.DeserializeJSONStringToObject <ThePubSubMessage>(message);

                var bSuccess = ProcessMessage(pubSubMessage.MsgId, pubSubMessage.PayloadFormat, time, pubSubMessage.Payload, null, true, out var ReceiveErrorCount, out var bSendAck);
                if (bSendAck)
                {
                    var ackMessage = new ThePubSubAckMessage
                    {
                        MsgId   = pubSubMessage.MsgId,
                        Error   = ReceiveErrorCount,
                        Success = bSuccess,
                    };
                    var ackMessageString = TheCommonUtils.SerializeObjectToJSONString(ackMessage);
                    _publisher.Publish($"{channel}/ack", ackMessageString);
                }
            }
            catch { }
        }
Example #19
0
 public TheOPCSensorSubscription(TheThing.TheSensorSubscription baseSubscription) : base(baseSubscription)
 {
     if (baseSubscription.ExtensionData != null)
     {
         if (baseSubscription.ExtensionData.TryGetValue(nameof(QueueSize), out var queueSize))
         {
             QueueSize = TheCommonUtils.CIntNullable(queueSize);
             ExtensionData.Remove(nameof(QueueSize));
         }
         if (baseSubscription.ExtensionData.TryGetValue(nameof(ChangeTrigger), out var changeTrigger))
         {
             ChangeTrigger = TheCommonUtils.CIntNullable(changeTrigger);
             ExtensionData.Remove(nameof(ChangeTrigger));
         }
         if (baseSubscription.ExtensionData.TryGetValue(nameof(DeadbandValue), out var deadbandValue))
         {
             DeadbandValue = TheCommonUtils.CIntNullable(deadbandValue);
             ExtensionData.Remove(nameof(DeadbandValue));
         }
         if (baseSubscription.ExtensionData.TryGetValue(nameof(HistoryStartTime), out var historyStartTime))
         {
             HistoryStartTime = TheCommonUtils.CDateNullable(historyStartTime);
             ExtensionData.Remove(nameof(HistoryStartTime));
         }
         if (baseSubscription.ExtensionData.TryGetValue(nameof(EventInfo), out var eventInfo))
         {
             if (eventInfo is TheEventSubscription)
             {
                 EventInfo = eventInfo as TheEventSubscription;
             }
             else
             {
                 EventInfo = TheCommonUtils.DeserializeJSONStringToObject <TheEventSubscription>(eventInfo?.ToString());
             }
             ExtensionData.Remove(nameof(EventInfo));
         }
     }
 }
Example #20
0
        void sinkRegResult(TheRequestData pData)
        {
            if (pData.CookieObject is Action <string, TheUPnPDeviceInfo> tResultCallback)
            {
                switch (pData.StatusCode)
                {
                case (int)eHttpStatusCode.OK:
                    TheUPnPDeviceInfo tInfo = null;
                    try
                    {
                        if (pData.PostData != null && pData.PostData.Length > 0)
                        {
                            tInfo = TheCommonUtils.DeserializeJSONStringToObject <TheUPnPDeviceInfo>(TheCommonUtils.CArray2UTF8String(pData.ResponseBuffer));
                        }
                        tResultCallback("OK", tInfo);
                    }
                    catch
                    {
                        tResultCallback("FAILED-No valid TheUPnPDeviceInfo received", null);
                    }
                    break;

                case (int)eHttpStatusCode.ServerError:
                    tResultCallback("FAILED-Server Not found or has errors", null);
                    break;

                case (int)eHttpStatusCode.NotAcceptable:
                    tResultCallback("FAILED-Server failed to register device", null);
                    break;

                default:
                    tResultCallback("FAILED-Unkown error", null);
                    break;
                }
            }
        }
Example #21
0
        private void OnMessage(string topic, string msgVersion, TheProcessMessage msg)
        {
            if (Callback == null && _rawCallback == null)
            {
                return;
            }
            if (!msg.Message.IsRoutingAllowed(RoutingOptions))
            {
                return;
            }
            if (!IsTopicMatch(topic))
            {
                return;
            }

            var message = msgVersion == PubSubVersion.V1
                ? new Message {
                Topic = topic, Payload = msg.Message.PLS
            }
                : TheCommonUtils.DeserializeJSONStringToObject <Message>(msg.Message.PLS);

            Callback?.Invoke(msg.Message.TIM, message);
            _rawCallback?.Invoke(msgVersion, msg);
        }
Example #22
0
        private async Task RunScriptAsync(TheScript script, TheThing variables, int stepNumber = 1, bool replay = false)
        {
            TheThing variablesSnapshot;

            try
            {
                for (; stepNumber <= script.Steps.Length; stepNumber++)
                {
                    //Clone thing before step occurs
                    variablesSnapshot = new TheThing();
                    variables.CloneThingAndPropertyMetaData(variablesSnapshot, true);

                    var step = script.Steps[stepNumber - 1];

                    var existingSnapshot = MyScriptTableStorage.MyMirrorCache.GetEntryByFunc(snapshot => snapshot.ScriptName == script.Name && snapshot.ScriptStep == stepNumber);
                    if (existingSnapshot?.Disabled == true)
                    {
                        TheBaseAssets.MySYSLOG.WriteToLog(175002, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(MyBaseThing.EngineName, "Finished script step: skipped step because it was disabled", eMsgLevel.l3_ImportantMessage, TheCommonUtils.SerializeObjectToJSONString(new Dictionary <String, object> {
                            { "Script", script.Name },
                            { "Step", stepNumber },
                            { "Message", step.Message.MessageName },
                            { "Target", step.Message.Target },
                        })));

                        UpdateStorageList(script.Name, "Disabled", stepNumber, script, variablesSnapshot, replay);
                        continue;
                    }

                    if (step.Condition != null)
                    {
                        var condition = TheCommonUtils.GenerateFinalStr(step.Condition, variables);
                        if (
                            (condition == "" || condition.ToLowerInvariant() == "false" || condition.Trim() == "0") ||
                            (condition.StartsWith("!") && condition.Length >= 1 && (condition.Substring(1).ToLowerInvariant() == "true") || condition.Substring(1).Trim() == "1"))
                        {
                            TheBaseAssets.MySYSLOG.WriteToLog(175002, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(MyBaseThing.EngineName, "Finished script step: skipped step due to condition not met", eMsgLevel.l3_ImportantMessage, TheCommonUtils.SerializeObjectToJSONString(new Dictionary <String, object> {
                                { "Script", script.Name },
                                { "Step", stepNumber },
                                { "Message", step.Message.MessageName },
                                { "Target", step.Message.Target },
                                { "Condition", step.Condition },
                                { "ConditionEvaluated", condition },
                            })));

                            UpdateStorageList(script.Name, "Condition Not Met", stepNumber, script, variablesSnapshot, replay);

                            continue;
                        }
                    }
                    var messageType = TheCommonUtils.GenerateFinalStr(step.Message.MessageName, variables);
                    var txtPayload  = TheCommonUtils.GenerateFinalStr(step.Message.Parameters?.ToString(), variables);
                    {
                        var txtPayload2 = txtPayload?.Replace("\"\\\"", "");
                        var txtPayload3 = txtPayload2?.Replace("\\\"\"", "");
                        txtPayload = txtPayload3;
                    }

                    // TODO Need a simpler and more flexible way to specify thing address in the script JSON
                    var target = step.Message.Target;
                    if (target == null)
                    {
                        if (txtPayload.Contains("EngineName"))
                        {
                            var    payloadDict        = TheCommonUtils.DeserializeJSONStringToObject <Dictionary <string, object> >(txtPayload);
                            object engineNameInferred = null;
                            if (payloadDict?.TryGetValue("EngineName", out engineNameInferred) == true && !string.IsNullOrEmpty(engineNameInferred?.ToString()))
                            {
                                target = new TheMessageAddress {
                                    EngineName = engineNameInferred.ToString()
                                };
                            }
                        }
                    }
                    if (target.EngineName.StartsWith("%") || target.EngineName.StartsWith("{"))
                    {
                        target.EngineName = TheCommonUtils.GenerateFinalStr(target.EngineName, variables);
                        // TODO Clean this up: support a serialized TheMessageAddress in the engine name, so that an output variable can be fed into a method invocation
                        try
                        {
                            var newTarget = TheCommonUtils.DeserializeJSONStringToObject <TheMessageAddress>(target.EngineName);
                            if (newTarget != null)
                            {
                                target = newTarget;
                            }
                        }
                        catch
                        {
                            // parsing error: ignore, will result in other errors downstream
                        }
                    }

                    await TheThingRegistry.WaitForInitializeAsync(target);

                    bool bDoRetry;
                    int  remainingRetryCount = step.RetryCount ?? 0;
                    do
                    {
                        existingSnapshot = MyScriptTableStorage.MyMirrorCache.GetEntryByFunc(snapshot => snapshot.ScriptName == script.Name && snapshot.ScriptStep == stepNumber);
                        if (existingSnapshot?.Disabled == true)
                        {
                            TheBaseAssets.MySYSLOG.WriteToLog(175002, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(MyBaseThing.EngineName, "Finished script step: skipped step because it was disabled", eMsgLevel.l3_ImportantMessage, TheCommonUtils.SerializeObjectToJSONString(new Dictionary <String, object> {
                                { "Script", script.Name },
                                { "Step", stepNumber },
                                { "Message", step.Message.MessageName },
                                { "Target", step.Message.Target },
                            })));

                            UpdateStorageList(script.Name, "Disabled", stepNumber, script, variablesSnapshot, replay);
                            break;
                        }

                        bDoRetry = false;
                        var response = await TheCommRequestResponse.PublishRequestAsync(MyBaseThing, target, messageType, new TimeSpan(0, 0, 0, 0, step.Message.timeout), null, txtPayload, null);

                        if (!string.IsNullOrEmpty(response?.PLS))
                        {
                            var outputs = TheCommonUtils.DeserializeJSONStringToObject <Dictionary <string, object> >(response.PLS);
                            if (outputs != null)
                            {
                                if (step.Message.outputs != null)
                                {
                                    foreach (var output in step.Message.outputs)
                                    {
                                        if (output.Key == "*")
                                        {
                                            variables.SetProperty(output.Value, response.PLS);
                                        }
                                        else if (outputs.TryGetValue(output.Key, out var outputValue))
                                        {
                                            variables.SetProperty(output.Value, outputValue);
                                            if (output.Value.Contains("Error") && !string.IsNullOrEmpty(TheCommonUtils.CStr(outputValue)))
                                            {
                                                TheBaseAssets.MySYSLOG.WriteToLog(175004, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(MyBaseThing.EngineName, "Error in script step: output reported error", eMsgLevel.l1_Error, TheCommonUtils.SerializeObjectToJSONString(new Dictionary <String, object> {
                                                    { "Script", script.Name },
                                                    { "Step", stepNumber },
                                                    { "Message", messageType },
                                                    { "Target", target },
                                                    { "PLS", txtPayload },
                                                    { "Response", response },
                                                    { "ResponsePLS", response?.PLS },
                                                })));

                                                UpdateStorageList(script.Name, $"Error {outputValue} in output", stepNumber, script, variablesSnapshot, replay);

                                                if (remainingRetryCount < 0 || remainingRetryCount > 0)
                                                {
                                                    remainingRetryCount--;
                                                    bDoRetry = true;
                                                }
                                                string retriesRemaining = bDoRetry ? (remainingRetryCount >= 0 ? $"{remainingRetryCount + 1}" : "infinite") : "none";
                                                MyBaseThing.SetStatus(3, $"Error in script '{script?.Name}', step {stepNumber}: output '{output.Value}' reported error {outputValue}. Retries remaining: {retriesRemaining}");
                                            }
                                        }
                                        else
                                        {
                                            // TODO provide access to sub-elements in the JSON
                                            //var outputParts = output.Key.Split('/');
                                            //dynamic currentNode = outputs;
                                            //foreach (var outputPart in outputParts)
                                            //{
                                            //    if (currentNode.TryGetValue(outputPart, out var nextNode))
                                            //    {
                                            //        currentNode = nextNode;
                                            //    }
                                            //}
                                        }
                                    }
                                }
                                TheBaseAssets.MySYSLOG.WriteToLog(175003, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(MyBaseThing.EngineName, "Finished script step", eMsgLevel.l3_ImportantMessage, TheCommonUtils.SerializeObjectToJSONString(new Dictionary <String, object> {
                                    { "Script", script.Name },
                                    { "Step", stepNumber },
                                    { "Message", messageType },
                                    { "Target", target },
                                    { "PLS", txtPayload },
                                    { "ResponsePLS", response.PLS },
                                })));

                                UpdateStorageList(script.Name, "Finished", stepNumber, script, variablesSnapshot, replay);
                            }
                            else
                            {
                                TheBaseAssets.MySYSLOG.WriteToLog(175004, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(MyBaseThing.EngineName, "Error in script step: no outputs found in response", eMsgLevel.l1_Error, TheCommonUtils.SerializeObjectToJSONString(new Dictionary <String, object> {
                                    { "Script", script.Name },
                                    { "Step", stepNumber },
                                    { "Message", messageType },
                                    { "Target", target },
                                    { "PLS", txtPayload },
                                    { "Response", response },
                                    { "ResponsePLS", response?.PLS },
                                })));

                                UpdateStorageList(script.Name, "Error: No Output", stepNumber, script, variablesSnapshot, replay);

                                if (step.DontRetryOnEmptyResponse != true && (remainingRetryCount < 0 || remainingRetryCount > 0))
                                {
                                    remainingRetryCount--;
                                    bDoRetry = true;
                                }
                                string retriesRemaining = bDoRetry ? (remainingRetryCount >= 0 ? $"{remainingRetryCount + 1}" : "infinite") : "none";
                                MyBaseThing.SetStatus(3, $"Error in script '{script?.Name}', step {stepNumber}: no outputs found in response. Retries remaining: {retriesRemaining}");
                            }
                        }
                        else
                        {
                            TheBaseAssets.MySYSLOG.WriteToLog(175005, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(MyBaseThing.EngineName, "Error Script step: timeout", eMsgLevel.l1_Error, TheCommonUtils.SerializeObjectToJSONString(new Dictionary <String, object> {
                                { "Script", script.Name },
                                { "Step", stepNumber },
                                { "Message", messageType },
                                { "Target", target },
                                { "PLS", txtPayload },
                                { "Response", response },
                            })));

                            UpdateStorageList(script.Name, "Error: Timeout", stepNumber, script, variablesSnapshot, replay);

                            //Retries infinitely unless count is specified
                            if (remainingRetryCount < 0 || remainingRetryCount > 0)
                            {
                                remainingRetryCount--;
                                bDoRetry = true;
                            }
                            string retriesRemaining = bDoRetry ? (remainingRetryCount >= 0 ? $"{remainingRetryCount + 1}" : "infinite") : "none";
                            MyBaseThing.SetStatus(3, $"Error in script '{script?.Name}', step {stepNumber}: timeout. Retries remaining: {retriesRemaining}");
                        }
                        if (bDoRetry)
                        {
                            await TheCommonUtils.TaskDelayOneEye(30000, 100).ConfigureAwait(false);
                        }
                    } while (bDoRetry && TheBaseAssets.MasterSwitch);
                }
            }
            catch (Exception e)
            {
                TheBaseAssets.MySYSLOG.WriteToLog(175006, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(MyBaseThing.EngineName, "Error in script step", eMsgLevel.l1_Error, TheCommonUtils.SerializeObjectToJSONString(new Dictionary <String, object> {
                    { "Script", script.Name },
                    { "Exception", e.Message },
                })));
                MyBaseThing.SetStatus(3, $"Error in script '{script?.Name}': {e.Message}");
                //Save variables instead of snapshot in case of error
                UpdateStorageList(script.Name, $"Error: {e.Message}", stepNumber, script, variables, replay);
            }
        }
Example #23
0
        public static Dictionary <string, Type> MyCDEPluginTypes = new Dictionary <string, Type>();       //DIC-Allowed   STRING

        public static int PackagePlugIn(string pluginFilePath, string binDirectoryPath, string storeDirectoryPath, string pPlatform, ILogger logger, bool bDiagnostics, bool bCheckForFileOverwrite, out string error)
        {
            if (!binDirectoryPath.EndsWith(Path.DirectorySeparatorChar.ToString()))// && !binDirectoryPath.EndsWith("."))
            {
                binDirectoryPath += Path.DirectorySeparatorChar;
            }
            if (storeDirectoryPath != null && !storeDirectoryPath.EndsWith(Path.DirectorySeparatorChar.ToString())) // && !storeDirectoryPath.EndsWith("."))
            {
                storeDirectoryPath += Path.DirectorySeparatorChar;
            }


            TheBaseAssets.MyServiceHostInfo = new TheServiceHostInfo(cdeHostType.NOTSET, cdeNodeType.NOTSET, binDirectoryPath)
            {
            };

            cdePlatform tPluginPlatform = cdePlatform.NOTSET;

            if (TheCommonUtils.CInt(pPlatform) > 0)
            {
                Enum.TryParse <cdePlatform>(pPlatform, out tPluginPlatform);
            }
            else
            {
                switch (pPlatform)
                {
                case "net35":
                    tPluginPlatform = cdePlatform.X32_V3;
                    break;

                case "net45":
                    tPluginPlatform = cdePlatform.X64_V3;
                    break;

                case "net40":
                    tPluginPlatform = cdePlatform.NETV4_64;
                    break;

                case "netstandard2.0":
                    tPluginPlatform = cdePlatform.NETSTD_V20;
                    break;
                }
            }

            var packageStr = $"Packaging {pluginFilePath} from {binDirectoryPath}";

            if (!String.IsNullOrEmpty(storeDirectoryPath))
            {
                packageStr += $" to {storeDirectoryPath}";
            }

            logger.WriteLine(packageStr);

            //try
            //{
            //    var workingDirectory = Path.GetDirectoryName(pluginFilePath);
            //    logger.WriteLine($"Setring working directory to {workingDirectory}");

            //    Directory.SetCurrentDirectory(workingDirectory);
            //}
            //catch (Exception e)
            //{
            //    logger.WriteLine($"$Warning: unable to set working directory: {e.ToString()}");
            //}

            if (File.Exists(Path.ChangeExtension(pluginFilePath, ".cdes")))
            {
                pluginFilePath = Path.ChangeExtension(pluginFilePath, ".cdes");
            }

            error = "";
            if (pluginFilePath.ToLower().EndsWith(".cdes"))
            {
                try
                {
                    var tInfo = TheCommonUtils.DeserializeJSONStringToObject <ThePluginInfo>(File.ReadAllText(pluginFilePath));
                    if (tPluginPlatform > 0)
                    {
                        tInfo.Platform = tPluginPlatform;
                    }
                    error = CreateCDEX(storeDirectoryPath, tInfo, logger, bCheckForFileOverwrite, out var cdesPath);
                    if (!String.IsNullOrEmpty(error))
                    {
                        logger.WriteLine($"Error creating package: {error}");
                        return(7);
                    }
                    else
                    {
                        logger.WriteLine($"Created CDES at {cdesPath}");
                    }
                }
                catch (Exception e)
                {
                    logger.WriteLine($"Error packaging CDES file {pluginFilePath}: {e} ");
                    error = e.ToString();
                    return(6);
                }
            }
            else
            {
                try
                {
                    AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += (o, args) =>
                    {
                        string   name = null;
                        Assembly ass  = null;
                        try
                        {
                            name = AppDomain.CurrentDomain.ApplyPolicy(args.Name);
                            try
                            {
                                ass = System.Reflection.Assembly.ReflectionOnlyLoad(name);
                            }
                            catch (Exception e)
                            {
                                var assName = new AssemblyName(name).Name;
                                var assPath = Path.Combine(binDirectoryPath, assName + ".dll");
                                if (bDiagnostics)
                                {
                                    logger.WriteLine($"Error resolving {args.Name} {name}, trying {assPath}: {e.Message}");
                                }
                                ass = System.Reflection.Assembly.ReflectionOnlyLoadFrom(assPath);
                            }
                        }
                        catch (Exception e)
                        {
                            logger.WriteLine($"Error resolving {args.Name} {name}: {e.Message}");
                            throw;
                        }
                        if (bDiagnostics)
                        {
                            logger.WriteLine($"Resolving {args.Name} {name}: {ass.CodeBase}");
                        }
                        return(ass);
                    };
                    Assembly tAss;
                    try
                    {
                        // TODO load for reflection only first (to support cross-platform tooling). But needs to be in separate app domain like in the engine host. For now only do reflection when LoadFrom fails (i.e. native x86 assembly in x64 packager process).
                        tAss = Assembly.LoadFrom(pluginFilePath);
                    }
                    catch
                    {
                        tAss = Assembly.ReflectionOnlyLoadFrom(pluginFilePath);
                    }
                    tPluginPlatform = TheCommonUtils.GetAssemblyPlatformHostAgnostic(tAss, bDiagnostics, out string diagInfo);
                    if (!string.IsNullOrEmpty(diagInfo))
                    {
                        logger.WriteLine(diagInfo);
                    }

                    var CDEPlugins = from t in tAss.GetTypes() //.GetTypes()
                                     let ifs = t.GetInterfaces()
                                               where ifs != null && ifs.Length > 0 && ((ifs.FirstOrDefault(i => i.AssemblyQualifiedName == typeof(ICDEPlugin).AssemblyQualifiedName) != null)
#if CDE_METRO
                                                                                       || ifs.Contains(typeof(ICDEUX))
#endif
                                                                                       )
                                               select new { Type = t, t.Namespace, t.Name, t.FullName };
                    // ReSharper disable once PossibleMultipleEnumeration
                    if (CDEPlugins == null || !CDEPlugins.Any())
                    {
                        string tPls = "";
                        foreach (Type ttt in tAss.GetTypes())
                        {
                            if (tPls.Length > 0)
                            {
                                tPls += ",\n\r";
                            }
                            tPls += ttt.FullName;
                        }
                        error = $"File {pluginFilePath} - found but did not contain C-DEngine Plug-In Interface. Types found: \n\r{tPls}";
                        logger.WriteLine(error);
                        return(2);
                    }
                    else
                    {
                        // ReSharper disable once PossibleMultipleEnumeration
                        foreach (var Plugin in CDEPlugins)
                        {
                            //TheSystemMessageLog.ToCo("Processing Plugin :" + Plugin.FullName);
                            if (Plugin.Type.GetInterfaces().FirstOrDefault(itf => itf.FullName == typeof(ICDEPlugin).FullName) != null)
                            {
                                if (!MyCDEPluginTypes.ContainsKey(Plugin.FullName))
                                {
                                    MyCDEPluginTypes.Add(Plugin.FullName, Plugin.Type);
                                    logger.WriteLine(string.Format("Plugin {1} in file {0} - found and added", pluginFilePath, Plugin.FullName));
                                }
                            }
                        }
                    }
                }
                catch (ReflectionTypeLoadException eeee)
                {
                    Exception[] tEx      = eeee.LoaderExceptions;
                    string      res      = eeee.ToString();
                    bool        bOldICDE = false;
                    foreach (Exception e in tEx)
                    {
                        if (e.Message.Contains("'Init'"))
                        {
                            bOldICDE = true;
                        }
                        res += "</br>Loader Exception: " + e;
                    }
                    logger.WriteLine($"LoadAssembly {pluginFilePath} failed with ReflectionTypeLoadException: {eeee.StackTrace} {eeee.LoaderExceptions.Aggregate("", (s,e) => $"{s}\r\n{e.Message}")}");
                    if (bOldICDE)
                    {
                        error = $"Assembly {pluginFilePath} appears to be a plug-in for an earlier C-DEngine and is no longer supported.";
                        logger.WriteLine(error);
                        return(3);
                    }
                    if (MyCDEPluginTypes.Count == 0)
                    {
                        return(4);
                    }
                }
                catch (Exception eee)
                {
                    error = $"ProcessDirectory:LoadAssembly {pluginFilePath} failed: {eee}";
                    logger.WriteLine(error);
                    return(4);
                }

                foreach (var tType in MyCDEPluginTypes.Values)
                {
                    string cdexPath = "";
                    try
                    {
                        if (tType.IsAbstract)
                        {
                            continue;
                        }
                        var tBase = new ThePackagerBaseEngine();
                        if (!EngineAssetInfoAttribute.ApplyEngineAssetAttributes(tType, tBase))
                        {
                            Assembly tAssRunning = Assembly.LoadFrom(pluginFilePath);
                            var      tIPlugin    = Activator.CreateInstance(tType) as ICDEPlugin;
                            if (tIPlugin == null)
                            {
                                error = "Could not activate Plugin-Service:" + tType;
                                logger.WriteLine(error);
                                return(5);
                            }
                            tIPlugin.InitEngineAssets(tBase);
                        }

                        // Ensure the file list is populate with at least the main module
                        tBase.AddManifestFiles(null);

                        var tInfo = tBase.GetPluginInfo();

                        if (tInfo.CurrentVersion <= 0)
                        {
                            tInfo.CurrentVersion = TheCommonUtils.GetAssemblyVersion(tType);
                        }
                        if (tPluginPlatform != cdePlatform.NOTSET)
                        {
                            tInfo.Platform = tPluginPlatform;
                        }

                        // Multi-platform mapping is now/will be done by the mesh manager, rather than in the packager
                        //if (tInfo.AllPlatforms?.Count > 0)
                        //{
                        //    foreach (var platform in tInfo.AllPlatforms)
                        //    {
                        //        var tInfoClone = tInfo.Clone();
                        //        tInfoClone.Platform = platform;
                        //        var error2 = CreateCDEX(storeDirectoryPath, tInfoClone, out cdexPath);
                        //        if (!string.IsNullOrEmpty(error2))
                        //        {
                        //            if (!string.IsNullOrEmpty(error))
                        //            {
                        //                error += "\r\n";
                        //            }
                        //            error += error2;
                        //        }
                        //    }
                        //}
                        //else
                        {
                            error = CreateCDEX(storeDirectoryPath, tInfo, logger, bCheckForFileOverwrite, out cdexPath);
                        }
                    }
                    catch (Exception e)
                    {
                        error = $"Plugin failed to start: {e}";
                    }
                    if (!String.IsNullOrEmpty(error))
                    {
                        logger.WriteLine($"Error creating package: {error}");
                        return(7);
                    }
                    else
                    {
                        logger.WriteLine($"Created CDEX at {cdexPath}");
                    }
                }
            }

            return(0);
        }
Example #24
0
        internal static bool ParseSimplex(string pScopedTopic, TSM pMessage, TheQueuedSender pQSender) //, TheSessionState pSessionState, Action<TSM> pLocalCallback)
        {
            if (pMessage == null)
            {
                return(false);
            }
#if !JC_COMMDEBUG
            try
            {
#endif
            if (pMessage?.TXT?.Equals("CDE_DELETEORPHAN") == true)
            {
                TheQueuedSenderRegistry.RemoveOrphan(TheCommonUtils.CGuid(pMessage.PLS));
                return(false);
            }

            if (pQSender == null)
            {
                TheBaseAssets.MySYSLOG.WriteToLog(291, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("CoreComm", $"QSender not found! Received from ORG:{TheCommonUtils.GetDeviceIDML(pMessage?.ORG)}", eMsgLevel.l1_Error, pMessage?.PLS));
                return(false);
            }

            //SECURITY-REVIEW: This cannot be permitted without extra tokens and Encryption! otherwise it can be used to change a nodes scope on the fly!
            //if ("CDE_UPDATESCOPE".Equals(pMessage.TXT))
            //{
            //    pQSender.UpdateSubscriptionScope(TheBaseAssets.MyScopeManager.GetRealScopeID(pMessage.SID));     //GRSI: rare
            //    return true;
            //}
            if (pQSender != null && pMessage.ENG?.StartsWith(eEngineName.ContentService) == true && pMessage?.TXT == "CDE_SERVICE_INFO" && pQSender.MyTargetNodeChannel?.RealScopeID == TheBaseAssets.MyScopeManager.GetRealScopeID(pMessage.SID))
            {
                try
                {
                    pQSender.SetNodeInfo(TheCommonUtils.DeserializeJSONStringToObject <TheNodeInfoClone>(pMessage?.PLS));
                }
                catch (Exception e)
                {
                    TheBaseAssets.MySYSLOG.WriteToLog(23056, TSM.L(eDEBUG_LEVELS.FULLVERBOSE) ? null : new TSM("CoreComm", $"Error decoding SystemInfo {pQSender?.MyTargetNodeChannel?.ToMLString()}", eMsgLevel.l1_Error, e.ToString()));
                }
            }

            if (pMessage.TXT?.Equals("CDE_SUBSCRIBE") == true || pMessage.TXT?.Equals("CDE_INITIALIZE") == true) //9-9-2012 CDEC Did not work right on CDE_INIT
            {
                TheBaseAssets.MySYSLOG.WriteToLog(292, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM("CoreComm", $"Parse-Simplex Subscribe from {pQSender?.MyTargetNodeChannel?.ToMLString()} Parsed: {pMessage?.PLS}", eMsgLevel.l7_HostDebugMessage));
                if (pQSender?.MyISBlock != null && !TheBaseAssets.MyServiceHostInfo.IsCloudService)
                {
                    TheBaseAssets.MySYSLOG.WriteToLog(292, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM("CoreComm", "Parse-Simplex Subscribe rejected for Custom ISBConnect", eMsgLevel.l7_HostDebugMessage));
                    return(true);
                }
                ParseSubscribe(pMessage.PLS, pQSender);
                if (pMessage.ENG.Equals("CLOUDSYNC"))
                {
                    string[] tTopics = pMessage.PLS.Split(';');
                    foreach (string t in tTopics)
                    {
                        TSM.GetScrambledIDFromTopic(t, out string tEng);
                        if (TheThingRegistry.IsEngineRegistered(tEng))
                        {
                            IBaseEngine tsBase = TheThingRegistry.GetBaseEngine(tEng);
                            tsBase?.GetBaseThing()?.FireEvent(eEngineEvents.NewSubscription, tsBase.GetBaseThing(), pQSender.MyTargetNodeChannel, true);
                        }
                    }
                    return(true);
                }
                else
                {
                    TheThing tBase2 = TheThingRegistry.GetBaseEngineAsThing(pMessage.ENG);
                    if (tBase2 != null)
                    {
                        tBase2.FireEvent(eEngineEvents.NewSubscription, tBase2, pQSender.MyTargetNodeChannel, true);
                    }
                }
                if (pMessage.TXT.Equals("CDE_SUBSCRIBE"))       //NEW:2.06 Make sure Subscribe and Unsubscribe only go to first node
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            if (pMessage.TXT?.Equals("CDE_UNSUBSCRIBE") == true)
            {
                TheBaseAssets.MySYSLOG.WriteToLog(292, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM("CoreComm", $"Parse-Simplex Unsubscribe from {pQSender.MyTargetNodeChannel?.ToMLString()} Parsed: {pMessage.PLS}", eMsgLevel.l7_HostDebugMessage));
                ParseUnsubscribe(pMessage.PLS, pQSender);
                return(true);       //NEW:2.06 Make sure Subscribe and Unsubscribe only go to first node
            }
#if !JC_COMMDEBUG
        }

        catch (Exception ee)
        {
            TheBaseAssets.MySYSLOG.WriteToLog(316, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("CoreComm", "Parse-Simplex", eMsgLevel.l1_Error, ee.ToString()));
        }
#endif
            return(false);
        }
        public override void HandleMessage(ICDEThing sender, object pIncoming)
        {
            TheProcessMessage pMsg = pIncoming as TheProcessMessage;

            if (pMsg == null || pMsg.Message == null)
            {
                return;
            }
            string[] tCmd = pMsg.Message.TXT.Split(':');
            switch (tCmd[0])   //string 2 cases
            {
            case "CDE_INITIALIZED":
                MyBaseEngine.SetInitialized(pMsg.Message);
                break;

            case "CDE_INITIALIZE":
                if (!MyBaseEngine.GetEngineState().IsEngineReady)
                {
                    MyBaseEngine.SetInitialized(pMsg.Message);
                }
                MyBaseEngine.ReplyInitialized(pMsg.Message);
                break;

            case "CDE_REGISTERRULE":
                TheRule tRule = TheCommonUtils.DeserializeJSONStringToObject <TheRule>(pMsg.Message.PLS);
                if (tRule != null)
                {
                    RegisterRule(tRule);
                }
                break;

            case "CLAIM_RULES":
                List <TheThing> tList = TheThingRegistry.GetThingsByFunc(eEngineName.ThingService, s => TheThing.GetSafePropertyString(s, "DeviceType").Equals(eKnownDeviceTypes.TheThingRule));
                if (tList != null && tList.Count > 0)
                {
                    foreach (TheThing tThing in tList)
                    {
                        tThing.Parent     = MyBaseThing.ID;
                        tThing.EngineName = MyBaseEngine.GetEngineName();
                    }
                }
                ActivateRules();
                MyDash.Reload(null, false);
                TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", $"{tList.Count} New Rules claimed"));
                break;

            case "REFRESH_DASH":
                ActivateRules();
                MyDash.Reload(null, false);
                break;

            case "FIRE_RULE":
                var t = TheThingRegistry.GetThingByMID(MyBaseEngine.GetEngineName(), TheCommonUtils.CGuid(pMsg?.Message?.PLS));
                if (t != null)
                {
                    TheRule tR = t.GetObject() as TheRule;
                    if (tR != null)
                    {
                        tR.RuleTrigger(tR.TriggerOldValue, true);
                    }
                }
                break;
            }
        }
Example #26
0
        private static Image DrawStrip(Guid pThingGuid, DateTimeOffset now, TheFieldInfo pInfo)
        {
            int pixelWidth = 78 * TheCommonUtils.CInt(pInfo?.PropBagGetValue("TileWidth"));

            if (pixelWidth == 0)
            {
                pixelWidth = 78;
            }
            int Hours = TheCommonUtils.CInt(pInfo?.PropBagGetValue("Hours"));

            if (Hours == 0)
            {
                Hours = 1;
            }
            int    pixelHeight = 1;
            Bitmap bmp         = new Bitmap(pixelWidth, pixelHeight, PixelFormat.Format32bppArgb);

            int    st           = 0;
            string tColorString = pInfo?.PropBagGetValue("ChartColors");

            string[] htmlColors = null;
            if (string.IsNullOrEmpty(tColorString))
            {
                htmlColors = TheBaseAssets.MyServiceHostInfo.StatusColors.Split(';');
            }
            else
            {
                htmlColors = tColorString.Split(';');
            }
            Dictionary <int, SolidBrush> stateColorMapping = htmlColors.ToDictionary(x => st++, y => new SolidBrush(ColorTranslator.FromHtml(y)));

            TheThing tThing = TheThingRegistry.GetThingByMID("*", pThingGuid);

            if (tThing == null)
            {
                return(null);
            }
            cdeP pMSH = ((ICDEThing)tThing.GetObject())?.GetProperty("MachineStorageHistory", false);

            if (pMSH == null)
            {
                return(null);
            }
            List <TheMachineStateHistory> tList = TheCommonUtils.DeserializeJSONStringToObject <List <TheMachineStateHistory> >(pMSH.ToString());

            if (tList == null)
            {
                return(null);
            }
            tList = tList.Where(s => now.Subtract(s.StateChangeTime).TotalHours < Hours).OrderBy(s => s.StateChangeTime).ToList();

            cdeP LastDeletedEntry            = tThing.GetProperty("LastDeletedEntry", false);
            TheMachineStateHistory lastState = null;

            if (LastDeletedEntry != null)
            {
                TheMachineStateHistory tHis = TheCommonUtils.DeserializeJSONStringToObject <TheMachineStateHistory>(LastDeletedEntry.ToString());
                lastState = new TheMachineStateHistory()
                {
                    State = tHis.State, StateChangeTime = now.Subtract(new TimeSpan(Hours, 0, 0))
                };
            }

            using (Graphics g = Graphics.FromImage(bmp))
            {
                g.ScaleTransform((float)pixelWidth / (Hours * 60 * 60), 1.0f);
                List <KeyValuePair <int, RectangleF> > rectangles = new List <KeyValuePair <int, RectangleF> >();
                foreach (var t in tList)
                {
                    if (lastState != null && t.State != lastState.State)
                    {
                        float start = (float)now.Subtract(t.StateChangeTime).TotalSeconds;
                        float size  = (float)t.StateChangeTime.Subtract(lastState.StateChangeTime).TotalSeconds;
                        rectangles.Add(new KeyValuePair <int, RectangleF>(lastState.State, new RectangleF(new PointF(start, 0), new SizeF(size, pixelHeight))));
                        lastState = t;
                    }
                    if (lastState == null)
                    {
                        lastState = t;
                    }
                }
                if (lastState != null)
                {
                    float size = (float)now.Subtract(lastState.StateChangeTime).TotalSeconds;
                    rectangles.Add(new KeyValuePair <int, RectangleF>(lastState.State, new RectangleF(new PointF(0, 0), new SizeF(size, pixelHeight))));
                }
                if (rectangles.Count > 0)
                {
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    // g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    for (int state = 0; state <= rectangles.Max(x => x.Key); state++)
                    {
                        if (stateColorMapping.ContainsKey(state))
                        {
                            IEnumerable <RectangleF> rects = rectangles.Where(x => x.Key == state).Select(x => x.Value);
                            var rectangleFs = rects as RectangleF[] ?? rects.ToArray();
                            if (rectangleFs.Any())
                            {
                                if (state > stateColorMapping.Count)
                                {
                                    g.FillRectangles(new SolidBrush(Color.Pink), rectangleFs.ToArray());
                                }
                                else
                                {
                                    g.FillRectangles(stateColorMapping[state], rectangleFs.ToArray());
                                }
                            }
                        }
                    }
                }
            }
            if (TheCommonUtils.CBool(pInfo?.PropBagGetValue("DrawRightToLeft")))
            {
                bmp.RotateFlip(RotateFlipType.RotateNoneFlipX); //draw right to left
            }
            return(bmp);
        }
Example #27
0
        private void CreateConfigurationSection(int writeEnableFlag, TheFormInfo tMyForm, int pStartFld, int pParentFld)
        {
            UseTree = TheCommonUtils.CBool(TheBaseAssets.MySettings.GetSetting("UseTreeView"));

            TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.CollapsibleGroup, pStartFld, 2, 0xc0, "Tag Management...", null, ThePropertyBag.Create(new nmiCtrlCollapsibleGroup()
            {
                DoClose = !UseTree, IsSmall = true, ParentFld = pParentFld, TileWidth = UseTree ? 18 : 6
            }));

            if (!UseTree)
            {
                TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.SingleEnded, pStartFld + 1, writeEnableFlag, 0xC0, "Browse Branch", "BrowseBranch", new nmiCtrlSingleEnded()
                {
                    ParentFld = pStartFld
                });
            }
#if USE_WEBIX
            else
            {
                var stringCols = TheCommonUtils.SerializeObjectToJSONString(new List <TheWXColumn> {
                    { new TheWXColumn()
                      {
                          TileWidth = 6, Header = "Node Name", ID = "DisplayName", FilterType = "textFilter", Template = "{common.treetable()}{common.treecheckbox()}&nbsp;<strong>#DisplayName#</strong>"
                      } },
                    //{ new TheWXColumn() { TileWidth = 2, Header = "Host Property", ID = "HostPropertyNameOverride", SortType = "string", Flags=2 } },
                    { new TheWXColumn()
                      {
                          TileWidth = 1, Header = "Sample-Rate", ID = "SampleRate", SortType = "int", Flags = 2
                      } },
                    { new TheWXColumn()
                      {
                          TileWidth = 1, Header = "Deadband-Filter", ID = "DeadbandFilterValue", SortType = "int", Flags = 2
                      } },
                    { new TheWXColumn()
                      {
                          TileWidth = 1, Header = "Trigger", ID = "ChangeTrigger", SortType = "int", Flags = 2
                      } },
                    { new TheWXColumn()
                      {
                          TileWidth = 6, Header = "Node ID", ID = "NodeIdName", FilterType = "textFilter", SortType = "int"
                      } }
                });

                OpcTagTree = TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.UserControl, pStartFld + 6, 2, 0, "Sample Tree", "SelectedIs", new nmiCtrlWXTreeTable()
                {
                    ParentFld       = pStartFld,
                    TileWidth       = 12,
                    TileHeight      = 12,
                    NoTE            = true,
                    RootNode        = "Objects",
                    TreeNode        = "Parent",
                    NameNode        = "DisplayName",
                    SelectNode      = "HasActiveHostThing",
                    LeftSplit       = 1,
                    OpenAllBranches = false,
                    SplitCharacter  = ".",
                    Columns         = stringCols
                });
                OpcTagTree.RegisterEvent2("NMI_FIELD_EVENT", (pMSG, para) => {
                    var tUpdate = TheCommonUtils.DeserializeJSONStringToObject <TheWXFieldEvent>(pMSG.Message.PLS);
                    if (tUpdate != null)
                    {
                        var MyTag = MyTags.MyMirrorCache.GetEntryByID(tUpdate.cdeMID);
                        if (MyTag != null)
                        {
                            switch (tUpdate.Name)
                            {
                            case "SampleRate":
                                MyTag.SampleRate = TheCommonUtils.CInt(tUpdate.Value);
                                break;

                            case "DeadbandFilterValue":
                                MyTag.DeadbandFilterValue = TheCommonUtils.CDbl(tUpdate.Value);
                                break;

                            case "ChangeTrigger":
                                MyTag.ChangeTrigger = TheCommonUtils.CInt(tUpdate.Value);
                                break;
                            }
                        }
                    }
                });
            }
#endif

            // BROWSE Button
            TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.TileButton, pStartFld + 2, writeEnableFlag, 0xC0, "Browse", null, new nmiCtrlTileButton()
            {
                ParentFld = pStartFld, ClassName = "cdeGoodActionButton", TileWidth = 3, NoTE = true
            })
            .RegisterUXEvent(MyBaseThing, eUXEvents.OnClick, "BROWSE", (pThing, pObj) =>
            {
                TheProcessMessage pMsg = pObj as TheProcessMessage;
                if (pMsg == null || pMsg.Message == null)
                {
                    return;
                }
                if (ConnectionState != ConnectionStateEnum.Connected)
                {
                    TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", "Server not connected - please connect first"));
                }
                else
                {
                    TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", "Browsing..."));
                    LastMessage   = "Browsing Started at " + DateTimeOffset.Now.ToString();
                    BrowsedTagCnt = 0;
                    Browser(currentRoot, currentRoot.ToString(), true, false, null);


                    var dataModelJson = TheCommonUtils.SerializeObjectToJSONString(
                        MyTags.MyMirrorCache.TheValues
                        .Where(t => t.HostPropertyNameOverride?.Contains("].[") != true)     // Filter out any DataValue sub-properties (i.e. engineering units), as the tree view doesn't seem to handle nodes under leaf-nodes (or inner nodes with data) yet
                        .ToList());
                    OpcTagTree?.SetUXProperty(pMsg.Message.GetOriginator(), $"DataModel={dataModelJson}", true);
                    LastMessage += " - Browsing done at " + DateTimeOffset.Now.ToString();
                    TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", LastMessage));
                }
            });
            TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.Number, pStartFld + 3, 0, 0x0, "Browsed Tags:", "BrowsedTagCnt", new nmiCtrlNumber()
            {
                ParentFld = pStartFld, TileWidth = 3
            });


            ///Browsed TAGS Form
            {
                var tDataSource = "TheOPCTags";
                if (MyTags != null)
                {
                    tDataSource = MyTags.StoreMID.ToString();
                }
                var tOPCTagForm = new TheFormInfo(TheThing.GetSafeThingGuid(MyBaseThing, "TAGLIST_ID"), eEngineName.NMIService, "OPC-UA Server Tags", $"{tDataSource};:;1000")
                {
                    IsNotAutoLoading = true, AddButtonText = "Add new Tag", PropertyBag = new nmiCtrlTableView {
                        ShowFilterField = true
                    }
                };
                TheNMIEngine.AddFormToThingUX(MyBaseThing, tOPCTagForm, "CMyTable", "Tag List", 1, 3, 0xF0, null, null, new ThePropertyBag()
                {
                    "Visibility=false"
                });
                TheNMIEngine.AddFields(tOPCTagForm, new List <TheFieldInfo> {
                    // 1: Thing subscription
                    { new TheFieldInfo()
                      {
                          FldOrder = 3, DataItem = "IsSubscribedAsThing", Flags = 0, Type = eFieldType.SingleCheck, Header = "Has Tag Thing", FldWidth = 1
                      } },
                    { new TheFieldInfo()
                      {
                          FldOrder = 11, DataItem = "Parent", Flags = 0, Type = eFieldType.SingleEnded, Header = "Parent", FldWidth = 4
                      } },
                    { new TheFieldInfo()
                      {
                          FldOrder = 12, DataItem = "DisplayName", Flags = 0, Type = eFieldType.SingleEnded, Header = "Name", FldWidth = 3
                      } },
                    { new TheFieldInfo()
                      {
                          FldOrder = 13, DataItem = nameof(TheOPCTag.HostPropertyNameOverride), Flags = writeEnableFlag, Type = eFieldType.SingleEnded, Header = "Host Property Name", FldWidth = 3
                      } },
                    { new TheFieldInfo()
                      {
                          FldOrder = 14, DataItem = "HostThingMID", Flags = writeEnableFlag, Type = eFieldType.ThingPicker, Header = "Host Thing", FldWidth = 3
                      } },
                    { new TheFieldInfo()
                      {
                          FldOrder = 15, DataItem = nameof(TheOPCTag.ChangeTrigger), Flags = writeEnableFlag, Type = eFieldType.ComboBox, Header = "Change Trigger", FldWidth = 1, PropertyBag = new nmiCtrlComboBox {
                              Options = "Status:0;Value:1;Value & Timestamp:2"
                          }
                      } },
                    { new TheFieldInfo()
                      {
                          FldOrder = 16, DataItem = nameof(TheOPCTag.SampleRate), Flags = writeEnableFlag, Type = eFieldType.Number, Header = "Sample Rate (ms)", FldWidth = 1
                      } },
                    { new TheFieldInfo()
                      {
                          FldOrder = 17, DataItem = nameof(TheOPCTag.DeadbandFilterValue), Flags = writeEnableFlag, Type = eFieldType.Number, Header = "Deadband", FldWidth = 1
                      } },
                    { new TheFieldInfo()
                      {
                          FldOrder = 18, DataItem = "NodeIdName", Flags = 2, Type = eFieldType.SingleEnded, Header = "NodeId", FldWidth = 6
                      } },
                    // 30: Property subscription
                    { new TheFieldInfo()
                      {
                          FldOrder = 19, DataItem = nameof(TheOPCTag.HistoryStartTime), Flags = writeEnableFlag, Type = eFieldType.SingleEnded, Header = "History Start", FldWidth = 3
                      } },
                    //{  new TheFieldInfo() { FldOrder=13,DataItem="PropAttr.7.Value.Value",Flags=0,Type=eFieldType.SingleEnded,Header="Value",FldWidth=5 }},
                    //{  new TheFieldInfo() { FldOrder=14,DataItem="PropAttr.7.DataType",Flags=0,Type=eFieldType.SingleEnded,Header="Type",FldWidth=5 }},
                });
                TheNMIEngine.AddTableButtons(tOPCTagForm, false, 100, 0);

                // Button Subscribe as Thing
                TheNMIEngine.AddSmartControl(MyBaseThing, tOPCTagForm, eFieldType.TileButton, 1, writeEnableFlag, 0xC0, "Create Tag Thing", null, new nmiCtrlTileButton()
                {
                    ClassName = "cdeGoodActionButton", TileHeight = 1
                })
                .RegisterUXEvent(MyBaseThing, eUXEvents.OnClick, "SUBSCRIBE", (tThing, pMsg) => SubscribeAsThing(tThing, pMsg, MyTags));

                // Button: Subscribe property into host thing
                TheNMIEngine.AddSmartControl(MyBaseThing, tOPCTagForm, eFieldType.TileButton, 5, writeEnableFlag, 0xC0, "Monitor as Property", null, new nmiCtrlTileButton()
                {
                    ClassName = "cdeGoodActionButton", TileHeight = 1
                })
                .RegisterUXEvent(MyBaseThing, eUXEvents.OnClick, "SUBSCRIBEPROP", (tThing, pMsg) => SubscribeAsProperty(tThing, pMsg, MyTags));

                TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.TileButton, pStartFld + 4, writeEnableFlag, 0xF0, "Show Tag List", null, new nmiCtrlTileButton()
                {
                    OnClick = $"TTS:{tOPCTagForm.cdeMID}", ParentFld = pStartFld, ClassName = "cdeTransitButton", TileWidth = 3, NoTE = true
                });
            }

            TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.Number, pStartFld + 5, writeEnableFlag, 0xC0, "Default Sample Rate", nameof(DefSampleRate), new nmiCtrlNumber()
            {
                ParentFld = pStartFld, TileWidth = 3
            });


            TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.ThingPicker, pStartFld + 6, writeEnableFlag, 0xC0, "Thing for Property Subs", "TagHostThingForSubscribeAll", new nmiCtrlThingPicker()
            {
                NoTE = true, ParentFld = pStartFld, TileWidth = 4
            });

            // SUBSCRIBE all tags as Properties
            TheNMIEngine.AddSmartControl(MyBaseThing, tMyForm, eFieldType.TileButton, pStartFld + 7, writeEnableFlag, 0xC0, $"Subscribe {(UseTree ? "selected" : "all")} in properties", null, new nmiCtrlTileButton()
            {
                ParentFld = pStartFld, ClassName = "cdeGoodActionButton", TileWidth = 2, NoTE = true
            })
            .RegisterUXEvent(MyBaseThing, eUXEvents.OnClick, "ALLTAGS", (pThing, pObj) =>
            {
                TheProcessMessage pMsg = pObj as TheProcessMessage;
                if (pMsg == null || pMsg.Message == null)
                {
                    return;
                }
                if (ConnectionState != ConnectionStateEnum.Connected)
                {
                    TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", "Server not connected - please connect first"));
                }
                else
                {
                    var tHostThing = TheThingRegistry.GetThingByMID("*", TheCommonUtils.CGuid(this.TagHostThingForSubscribeAll));
                    if (tHostThing == null)
                    {
                        TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", "Host Thing not specified or invalid"));
                        return;
                    }
                    TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", "Subscribing..."));

                    if (MyTags.MyMirrorCache.Count == 0 && !UseTree)
                    {
                        // Clear all previous subscription in either MyTags (tag as thing) oder HostThing (tag as property)
                        MyTags.MyMirrorCache.Reset();

                        // TODO Figure out how to clean up subscribed things in properties.
                        // - Can't just delete as a customer may have hand picked certain properties via browse paths etc.
                        // - Allow customer to use multiple host things?
                        //var tThing = TheThingRegistry.GetThingByMID("*", TheCommonUtils.CGuid(TagHostThing));
                        //if (tThing != null)
                        //{
                        //    foreach (var prop in tThing.GetPropertiesMetaStartingWith("OPCUA:"))
                        //    {
                        //        tThing.RemoveProperty(prop.Name);
                        //    }
                        //}

                        LastMessage = "Subscribing started at " + DateTimeOffset.Now.ToString();

                        BrowsedTagCnt = 0;

                        Browser(currentRoot, currentRoot.ToString(), true, true, tHostThing, CreateIDFilter());

                        LastMessage += " - Subscribing done at " + DateTimeOffset.Now.ToString();
                        TheCommCore.PublishToOriginator(pMsg.Message, new TSM(eEngineName.NMIService, "NMI_TOAST", LastMessage));
                    }
                    else
                    {
                        // Previously browsed: use those tags to do the subscriptions
                        LastMessage = "Subscribing started at " + DateTimeOffset.Now.ToString();

                        var subscription = GetOrCreateSubscription(0);
                        var pFilterIDs   = CreateIDFilter();
                        int count        = 0;
                        //var results = new List<Opc.Ua.Client.MonitoredItem>();//CM: removed as Nothing is done with "results"

                        foreach (var tag in MyTags.TheValues)
                        {
                            string tagNameForFilter;
                            if (tag.DisplayName == "EngineeringUnits" || tag.DisplayName == "EURange")
                            {
                                tagNameForFilter = tag.Parent;
                            }
                            else
                            {
                                tagNameForFilter = $"{tag.Parent}.{tag.DisplayName}";
                            }

                            if (pFilterIDs != null && pFilterIDs.Contains(tagNameForFilter))
                            {
                                tag.HostThingMID = TheCommonUtils.cdeGuidToString(tHostThing.cdeMID);
                                var childTags    = tag.GetChildTags();
                                if (childTags?.Any() == true)
                                {
                                    foreach (var childTag in childTags)
                                    {
                                        childTag.HostThingMID = tag.HostThingMID;
                                    }
                                }
                                if (!RegisterAndMonitorTagInHostThing(subscription, tag, out string error, false, true, false) || !string.IsNullOrEmpty(error))
                                {
                                    // error
                                }
Example #28
0
        /// <summary>
        /// Message Handler of TheThingEngine
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="pIncoming"></param>
        public override void HandleMessage(ICDEThing sender, object pIncoming)
        {
            if (!(pIncoming is TheProcessMessage pMsg) || pMsg.Message == null)
            {
                return;
            }
            string[] tCmd = pMsg.Message.TXT.Split(':');
            switch (tCmd[0])   //string 2 cases
            {
            case "CDE_INITIALIZED":
                MyBaseEngine.SetInitialized(pMsg.Message);
                break;

            case "CDE_INITIALIZE":
                if (!MyBaseEngine.GetEngineState().IsEngineReady)
                {
                    MyBaseEngine.SetInitialized(pMsg.Message);
                }
                MyBaseEngine.ReplyInitialized(pMsg.Message);
                break;

            case "CDE_REGISTERPROPERTY":
                if (tCmd.Length > 1)
                {
                    TheThing tThing2 = TheThingRegistry.GetThingByMID("*", TheCommonUtils.CGuid(tCmd[1]));
                    if (tThing2 != null)
                    {
                        cdeP tProp = tThing2.GetProperty(pMsg.Message.PLS);
                        if (tProp == null)
                        {
                            return;
                        }
                        tProp.SetPublication(true, pMsg.Message.GetOriginator());       //OK - Very late "Binding"
                    }
                }
                break;

            case "CDE_REGISTERTHING":
                if (MyThingRegistry != null)
                {
                    //if (TheScopeManager.IsNodeTrusted(pMsg.Message.GetOriginator())) // CODE-REVIEW: This security enhancement will not all Global Things to work anymore. WE need to bring this back when we have the meshmanager working
                    //{
                    //    TheBaseAssets.MySYSLOG.WriteToLog(7678, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(eEngineName.ContentService, String.Format("Register Thing from untrusted node received {0} - disallowed", pMsg.Message.GetOriginator()), eMsgLevel.l3_ImportantMessage));
                    //    return;
                    //}
                    TheThing tThing = TheCommonUtils.DeserializeJSONStringToObject <TheThing>(pMsg.Message.PLS);
                    if (tThing != null)
                    {
                        TheThingRegistry.RegisterThing(tThing);
                    }
                }
                break;

            case "CDE_UNREGISTERTHING":
                if (MyThingRegistry != null)
                {
                    //if (TheScopeManager.IsNodeTrusted(pMsg.Message.GetOriginator()))
                    //{
                    //    TheBaseAssets.MySYSLOG.WriteToLog(7678, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(eEngineName.ContentService, String.Format("Unregister Thing from untrusted node received {0} - disallowed", pMsg.Message.GetOriginator()), eMsgLevel.l3_ImportantMessage));
                    //    return;
                    //}
                    TheThingRegistry.DeleteThingByID(TheCommonUtils.CGuid(pMsg.Message.PLS));
                }
                break;

            case "CDE_SETP":
                if (!string.IsNullOrEmpty(pMsg.Message.PLS) && tCmd.Length > 1)
                {
                    TheThing tG = TheThingRegistry.GetThingByMID(TheCommonUtils.CGuid(tCmd[1]), true);
                    if (tG != null)
                    {
                        cdeP p = TheCommonUtils.DeserializeJSONStringToObject <cdeP>(pMsg.Message.PLS);
                        if (p != null)
                        {
                            tG.UpdatePropertyInBag(p, true, true);
                        }
                    }
                }
                break;

            case "CDE_SYNC_THINGS":
                if (pMsg.Message.PLS.Length > 2)
                {
                    List <TheThing> tList = TheCommonUtils.DeserializeJSONStringToObject <List <TheThing> >(pMsg.Message.PLS);
                    TheBaseAssets.MySYSLOG.WriteToLog(7678, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM(eEngineName.ContentService, String.Format("CDE_SYNC_THINGS: Received for node {0}", pMsg.Message.GetOriginator()), eMsgLevel.l3_ImportantMessage));     //, pMsg.Message.PLS));
                    TheThingRegistry.SyncGlobalThings(pMsg.Message.GetOriginator(), tList);
                }
                break;

            case "CDE_SEND_GLOBAL_THINGS":
                SendGlobalThings(pMsg.Message.GetOriginator());
                break;

            case "CDE_REGISTERRULE":
                var tEngs = TheThingRegistry.GetBaseEnginesByCap(eThingCaps.RulesEngine);
                foreach (var t in tEngs)
                {
                    t.GetBaseThing()?.HandleMessage(sender, pMsg);
                }
                break;
            }
        }
Example #29
0
        private void GenerateMetrics()
        {
            foreach (var senderThing in MySenderThings.TheValues)
            {
                if (senderThing.Disable)
                {
                    continue;
                }
                List <TheThing> thingsToSend = null;
                {
                    var tThing = senderThing.GetThing();
                    if (tThing == null)
                    {
                        if (!string.IsNullOrEmpty(senderThing.EngineName))
                        {
                            thingsToSend = TheThingRegistry.GetThingsOfEngine(senderThing.EngineName, true, true);
                            if (!string.IsNullOrEmpty(senderThing.DeviceType))
                            {
                                thingsToSend.RemoveAll(t => t.DeviceType != senderThing.DeviceType);
                            }
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(senderThing.DeviceType))
                            {
                                thingsToSend = TheThingRegistry.GetThingsByFunc("*", t => t.DeviceType.Equals(senderThing.DeviceType, StringComparison.Ordinal), true);
                            }
                        }
                    }
                    else
                    {
                        thingsToSend = new List <TheThing> {
                            tThing
                        };
                    }
                }
                if (thingsToSend == null || thingsToSend.Count == 0)
                {
                    continue;
                }
                //if (string.IsNullOrEmpty(senderThing.PropertiesIncluded)) senderThing.PropertiesIncluded = "Value"; //Make sure we have at least one included
                var propsIncludedConf  = string.IsNullOrEmpty(senderThing.PropertiesIncluded) ? null : TheCommonUtils.cdeSplit(senderThing.PropertiesIncluded, ',', false, false);
                var propsExcluded      = string.IsNullOrEmpty(senderThing.PropertiesExcluded) ? null : TheCommonUtils.cdeSplit(senderThing.PropertiesExcluded, ',', false, false);
                var propsIncludedSplit = propsIncludedConf?.Select(p => TheCommonUtils.cdeSplit(p, ';', false, false));
                var propsIncluded      = propsIncludedSplit?.Select(p => p[0]);

                foreach (var tThing in thingsToSend)
                {
                    // Capture the metrics as specified in the sender thing
                    var tMetricThing = nsCDEngine.ViewModels.TheThingStore.CloneFromTheThing(tThing, false, true, true, propsIncluded, propsExcluded);

                    // Unpack any JSON objects (i.e. DeviceGateLogMesh) into separate properties

                    foreach (var tMetric in tMetricThing.PB.ToList())
                    {
                        if (tMetric.Value?.ToString().Contains("{") == true)
                        {
                            var metricValue = tMetric.Value.ToString().Trim();
                            if (metricValue.StartsWith("{") && metricValue.EndsWith("}"))
                            {
                                try
                                {
                                    var jsonBag = TheCommonUtils.DeserializeJSONStringToObject <Dictionary <string, object> >(metricValue);
                                    if (jsonBag?.Count > 0)
                                    {
                                        if (jsonBag.TryGetValue("PLO", out var payload))
                                        {
                                            // Unpack the PLO in case the payload is a KPI TSM
                                            try
                                            {
                                                var payloadBag = TheCommonUtils.DeserializeJSONStringToObject <Dictionary <string, object> >(payload.ToString());
                                                if (payloadBag != null && payloadBag.Count > 0)
                                                {
                                                    jsonBag = payloadBag as Dictionary <string, object>;
                                                }
                                            }
                                            catch { }
                                        }
                                        foreach (var prop in jsonBag)
                                        {
                                            var metricPrefix = $"[{tMetric.Key.Trim(new char[] { '[', ']' })}]";
                                            var metricName   = $"{metricPrefix}.[{prop.Key}]";
                                            if (propsIncluded?.Contains(metricName) == true || propsIncluded?.Contains($"{metricPrefix}.*") == true)
                                            {
                                                tMetricThing.PB[metricName] = prop.Value;
                                            }
                                        }
                                        if (tMetricThing.PB.ContainsKey(tMetric.Key))
                                        {
                                            tMetricThing.PB.Remove(tMetric.Key);
                                        }
                                    }
                                }
                                catch { }
                            }
                        }
                    }

                    foreach (var tMetric in tMetricThing.PB)
                    {
                        string metricName = "";
                        try
                        {
                            var propertyName = tMetric.Key;
                            var metricInfo   = propsIncludedSplit.FirstOrDefault(ps => ps[0] == propertyName);
                            if (metricInfo != null && metricInfo.Length > 1)
                            {
                                metricName = metricInfo[1];
                            }
                            else
                            {
                                metricName = GetValidLabelName(tMetric.Key);
                            }

                            var valueToReport = GetMetricValue(tMetric.Value);
                            if (senderThing.ChangeNaNToNull && valueToReport == 0) //CM: closest reuse of disable sending of null/0
                            {
                                continue;
                            }
                            var labels = GetMetricLabels(senderThing, propertyName, metricName);

                            switch (senderThing.TargetType?.ToLowerInvariant())
                            {
                            case "counter":
                            {
                                var counter = myCountersByMetricName.GetOrAdd(metricName,
                                                                              (s) =>
                                    {
                                        Prometheus.Counter cs;
                                        try
                                        {
                                            cs = Metrics.CreateCounter(s, "", labels);
                                            return(cs);
                                        }
                                        catch (Exception e)
                                        {
                                            TheBaseAssets.MySYSLOG.WriteToLog(95307, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(strPrometheusExporter, $"Error creating metric {s} in server: {this.MyBaseThing?.Address}", eMsgLevel.l1_Error, e.ToString()));
                                        }
                                        return(null);
                                    });
                                if (counter != null)
                                {
                                    if (counter.LabelNames.Length > 0)
                                    {
                                        var labelValues  = GetLabelValues(tThing, counter.LabelNames);
                                        var labelCounter = counter.Labels(labelValues);
                                        var valueInc     = valueToReport - labelCounter.Value;
                                        if (valueInc > 0)
                                        {
                                            labelCounter.Inc(valueInc);
                                        }
                                        else if (valueInc < 0)
                                        {
                                            TheBaseAssets.MySYSLOG.WriteToLog(95307, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM(strPrometheusExporter, $"Error reporting metric {metricName} in '{this.MyBaseThing?.Address} {this.MyBaseThing}'. Counter value {valueToReport} smaller than reported {labelCounter.Value}", eMsgLevel.l1_Error));
                                        }
                                    }
                                    else
                                    {
                                        counter.Inc(valueToReport - counter.Value);
                                    }
                                }
                            }
                            break;

                            case null:
                            case "":
                            case "gauge":
                            {
                                var gauge = myGaugesByMetricName.GetOrAdd(metricName, (s) => Metrics.CreateGauge(s, "", labels));
                                if (gauge != null)
                                {
                                    if (gauge.LabelNames.Length > 0)
                                    {
                                        var labelValues = GetLabelValues(tThing, gauge.LabelNames);
                                        gauge.Labels(labelValues).Set(valueToReport);
                                    }
                                    else
                                    {
                                        gauge.Set(valueToReport);
                                    }
                                }
                            }
                            break;

                            case "histogram":
                            {
                                var histogram = myHistogramsByMetricName.GetOrAdd(metricName, (s) => Metrics.CreateHistogram(s, "", GetHistogramBuckets(senderThing, propertyName, metricName, labels)));
                                if (histogram != null)
                                {
                                    if (histogram.LabelNames.Length > 0)
                                    {
                                        var labelValues = GetLabelValues(tThing, histogram.LabelNames);
                                        histogram.Labels(labelValues).Observe(valueToReport);
                                    }
                                    else
                                    {
                                        histogram.Observe(valueToReport);
                                    }
                                }
                            }
                            break;

                            case "summary":
                            {
                                var summary = mySummariesByMetricName.GetOrAdd(metricName, (s) => Metrics.CreateSummary(s, "", labels));
                                if (summary != null)
                                {
                                    if (summary.LabelNames.Length > 0)
                                    {
                                        var labelValues = GetLabelValues(tThing, summary.LabelNames);
                                        summary.Labels(labelValues).Observe(valueToReport);
                                    }
                                    else
                                    {
                                        summary.Observe(valueToReport);
                                    }
                                }
                            }
                            break;

                            default:
                                TheBaseAssets.MySYSLOG.WriteToLog(95307, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(strPrometheusExporter, $"Unexpected metric type in server: {this.MyBaseThing?.Address}", eMsgLevel.l1_Error, senderThing.TargetType));
                                break;
                            }
                        }
                        catch (Exception e)
                        {
                            TheBaseAssets.MySYSLOG.WriteToLog(95307, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(strPrometheusExporter, $"Error reporting metric {metricName} in server: {this.MyBaseThing?.Address}", eMsgLevel.l1_Error, e.ToString()));
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Creates an installation package for a plugin.
        /// </summary>
        /// <param name="tInfo">Meta information about the plug-in. (can be null, but then tPlace has to be specified)</param>
        /// <param name="tPlace">Additional information about the plug-in's presence in a market place (can be null, but then tInfo has to be specified)</param>
        /// <param name="outputDirectory">Path to a directory that will be used for temporary files as well as the generated installation package</param>
        /// <param name="bForce">Overwrites output files if they already exists.</param>
        /// <param name="packageFilePath">Path to the installation package within the outputDirectory.</param>
        /// <returns>null or empty string if successful. Error information on failure.</returns>
        public static string CreatePluginPackage(ThePluginInfo tInfo, TheServicesMarketPlace tPlace, string outputDirectory, bool bForce, out string packageFilePath)
        {
            packageFilePath = null;
            string tMetaFile = "";

            if (tInfo != null)
            {
                if (tInfo.Capabilities != null && tInfo.Capabilities.Contains(eThingCaps.Internal))
                {
                    return($"{tInfo.ServiceName} Is Internal Only");
                }
                if (String.IsNullOrEmpty(outputDirectory))
                {
                    tMetaFile = TheCommonUtils.cdeFixupFileName($"store\\{tInfo.cdeMID}\\{tInfo.Platform}\\");
                }
                else
                {
                    tMetaFile = $"{outputDirectory}\\store\\{tInfo.cdeMID}\\{tInfo.Platform}\\";
                }
                if (!Directory.Exists(tMetaFile))
                {
                    TheCommonUtils.CreateDirectories(tMetaFile);
                }
                WriteServiceInfo(tInfo, outputDirectory);

                string tgr = tMetaFile + "new\\";
                if (TheCommonUtils.IsOnLinux())
                {
                    tgr = tgr.Replace('\\', '/');
                }
                if (Directory.Exists(tgr))
                {
                    Directory.Delete(tgr, true);
                }

                if (tInfo.FilesManifest != null && tInfo.FilesManifest.Count > 0)
                {
                    foreach (string tFile in tInfo.FilesManifest)
                    {
                        if (tFile == null)
                        {
                            continue;
                        }
                        string tFinalFile = tFile;
                        try
                        {
                            if (tFile.StartsWith("@"))  //If a Manifest file starts with @ this function expects this syntax: "@<platform>@<FileName>"
                            {
                                var tC = tFile.Split('@');
                                if (tC.Length < 3)
                                {
                                    continue;
                                }
                                switch (tC[1])
                                {
                                case "net35":
                                    if (tInfo.Platform != cdePlatform.X32_V3)
                                    {
                                        continue;
                                    }
                                    break;

                                case "net40":
                                    if (tInfo.Platform != cdePlatform.NETV4_32 && tInfo.Platform != cdePlatform.NETV4_64)
                                    {
                                        continue;
                                    }
                                    break;

                                case "net45":
                                    if (tInfo.Platform != cdePlatform.X64_V3 && tInfo.Platform != cdePlatform.X32_V4)
                                    {
                                        continue;
                                    }
                                    break;

                                case "netstandard2.0":
                                    break;

                                default:
                                    if ((TheCommonUtils.CInt(tC[1]) > 0 && TheCommonUtils.CInt(tC[1]) != TheCommonUtils.CInt(tInfo.Platform)))
                                    {
                                        continue;
                                    }
                                    break;
                                }
                                tFinalFile = tC[2];
                            }
                            string src = TheBaseAssets.MyServiceHostInfo.BaseDirectory;
                            if (TheBaseAssets.MyServiceHostInfo.cdeHostingType == cdeHostType.IIS)
                            {
                                src += "bin\\";
                            }
                            src += tFinalFile;
                            if (TheCommonUtils.IsOnLinux())
                            {
                                src = src.Replace('\\', '/');
                            }
                            tgr = tMetaFile + "new\\" + tFinalFile;
                            if (TheCommonUtils.IsOnLinux())
                            {
                                tgr = tgr.Replace('\\', '/');
                            }
                            TheCommonUtils.CreateDirectories(tgr);
                            File.Copy(src, tgr, true);
                        }
                        catch (Exception e)
                        {
                            return(string.Format("Manifest File {0} could not be copied: {1}", tFile, e.ToString()));
                            //TheBaseAssets.MySYSLOG.WriteToLog(2, new TSM("ISMManager", string.Format("Manifest Filer {0} could not be copied.", tFile), eMsgLevel.l1_Error, e.ToString())); //Log Entry that service has been started
                        }
                    }
                }
            }
            else
            {
                tMetaFile = TheCommonUtils.cdeFixupFileName(string.Format("store\\{0}\\{1}\\", tPlace.PluginID, tPlace.Platform));  //now PluginID which contains ThePluginInfo.cdeMID
            }

            if (tPlace != null && File.Exists(tMetaFile + "META.CDEM"))
            {
                TheServicesMarketPlace tPl = null;
                using (StreamReader sr = new StreamReader(tMetaFile + "META.CDEM"))
                {
                    String line = sr.ReadToEnd();
                    tPl = TheCommonUtils.DeserializeJSONStringToObject <TheServicesMarketPlace>(line);
                }
                if ((tInfo != null && tInfo.CurrentVersion <= tPl.CurrentVersion) || (tPl != null && tPlace.CurrentVersion <= tPl.CurrentVersion))
                {
                    return($"{tPlace?.ServiceName} has existing Version in Store: PInfo:{tInfo?.CurrentVersion} vs Meta:{tPl?.CurrentVersion} vs Place:{tPlace?.CurrentVersion}");
                }
            }
            if (tPlace == null)
            {
                tPlace = new TheServicesMarketPlace();
                tPlace.Capabilities    = tInfo.Capabilities;
                tPlace.Categories      = tInfo.Categories;
                tPlace.PluginID        = tInfo.cdeMID; //PluginID now contains ThePluginInfo.cdeMID
                tPlace.CurrentVersion  = tInfo.CurrentVersion;
                tPlace.LongDescription = tInfo.LongDescription;
                tPlace.Developer       = tInfo.Developer;
                tPlace.DeveloperUrl    = tInfo.DeveloperUrl;
                tPlace.HomeUrl         = tInfo.HomeUrl;
                tPlace.Platform        = tInfo.Platform;
                tPlace.Price           = tInfo.Price;
                tPlace.ServiceName     = tInfo.ServiceName;
                tPlace.AvailableSince  = DateTime.Now;
                tPlace.RaterCount      = new List <int>()
                {
                    0, 0, 0, 0, 0
                };
                tPlace.Rating             = 0;
                tPlace.DownloadCounter    = 0;
                tPlace.ServiceDescription = string.IsNullOrEmpty(tInfo.ServiceDescription) ? tInfo.ServiceName : tInfo.ServiceDescription;
                if (TheBaseAssets.MyServiceHostInfo != null)
                {
                    if (string.IsNullOrEmpty(tPlace.HomeUrl))
                    {
                        tPlace.HomeUrl = TheBaseAssets.MyServiceHostInfo.GetPrimaryStationURL(false) + "/%PluginID%";
                    }
                    tPlace.IconUrl = tInfo.IconUrl;
                    if (string.IsNullOrEmpty(tPlace.IconUrl) || tPlace.IconUrl == "toplogo-150.png")
                    {
                        tPlace.IconUrl = "<i class=\"cl-font cl-Logo cl-4x\"></i>"; // TheBaseAssets.MyServiceHostInfo.UPnPIcon;
                    }
                    if (tPlace.IconUrl.EndsWith(".png", StringComparison.OrdinalIgnoreCase) || tPlace.IconUrl.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase))
                    {
                        tPlace.IconUrl = $"<img src='{tPlace.IconUrl}' class='Blocked' width='78' height='78'></img>";
                    }
                    else if (tPlace.IconUrl.StartsWith("FA"))
                    {
                        tPlace.IconUrl = "<i class='fa faIcon " + (tPlace.IconUrl.Substring(3, 1) == "S" ? "fa-spin " : "") + "fa-" + tPlace.IconUrl.Substring(2, 1) + "x'>&#x" + tPlace.IconUrl.Substring(4, tPlace.IconUrl.Length - 4) + ";</i>";
                    }
                }
                if (Directory.Exists(tMetaFile + "new"))
                {
                    var res = CreateCDEX(tPlace, tMetaFile, true, out packageFilePath);
                    if (res != null)
                    {
                        return(res);
                    }
                    //Directory.Move(tMetaFile + "new", tMetaFile + "DONE_" + TheCommonUtils.GetTimeStamp());
                }
                else
                {
                    return("Error: Output directory does not exists");
                }
            }
            else
            {
                if (tInfo.CurrentVersion > tPlace.CurrentVersion)
                {
                    tPlace.CurrentVersion = tInfo.CurrentVersion;
                }
                var res = CreateCDEX(tPlace, tMetaFile, bForce, out packageFilePath);
                if (res != null)
                {
                    return(res);
                }
            }
            tPlace.LastUpdate = DateTime.Now;
            using (StreamWriter sr = new StreamWriter(tMetaFile + "META.CDEM"))
                sr.Write(TheCommonUtils.SerializeObjectToJSONString <TheServicesMarketPlace>(tPlace));
            return("");
        }