Example #1
0
 public void RegisterDeviceLost(string pUid, Action <TheUPnPDeviceInfo> pCallback)
 {
     if (!mUPnpLost.ContainsKey(pUid))
     {
         mUPnpLost.TryAdd(pUid, pCallback);
     }
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="engine"></param>
        /// <returns></returns>
        private static ResourceManager GetStringResourceManager(string engine)
        {
            ResourceManager rm = null;

            if (!string.IsNullOrEmpty(engine) && ResourceManagersPerEngine.TryGetValue(engine, out rm))
            {
                return(rm);
            }
            if (string.IsNullOrEmpty(engine) || !TheBaseAssets.MyCDEPluginTypes.TryGetValue(engine, out Type plugInType))
            {
                engine = "cdeEngine";
                if (ResourceManagersPerEngine.TryGetValue(engine, out rm))
                {
                    return(rm);
                }
                plugInType = typeof(TheCommonUtils);
            }
            try
            {
                rm = new ResourceManager("cdeStrings", plugInType.Assembly);
            }
            catch (Exception ex)
            {
                TheBaseAssets.MySYSLOG.WriteToLog(1, TSM.L(eDEBUG_LEVELS.OFF)
                    ? null
                    : new TSM(eEngineName.NMIService, "Error creating resource manager", eMsgLevel.l2_Warning, $"cdeStrings, {plugInType.Name}: {ex}"));
            }
            if (rm != null)
            {
                ResourceManagersPerEngine.TryAdd(engine, rm);
            }
            return(rm);
        }
Example #3
0
 // Creates a new entry in the KPIIndexes and KPIs.  If the KPIs array is full, it will be recreated.
 private static void CreateNewEntry(string name, long value, bool dontReset)
 {
     try
     {
         lock (KPIIndexes)
         {
             lock (KPIs)
             {
                 int entries = KPIIndexes.Count;
                 if (entries == KPIs.Length)
                 {
                     long[] newKPIs = new long[entries + arrayIncreaseSize];
                     Array.Copy(KPIs, newKPIs, entries);
                     KPIs = newKPIs;
                 }
                 if (KPIs.Length > entries)
                 {
                     if (KPIIndexes.TryAdd(name, entries))
                     {
                         Interlocked.Exchange(ref KPIs[entries], value);
                     }
                 }
                 if (dontReset)
                 {
                     doNotReset.Add(name);
                     doNotComputeTotals.Add(name);
                 }
             }
         }
     }
     catch (Exception)
     {
         // Log exception?
     }
 }
Example #4
0
 /// <summary>
 /// Log a new Visitor
 /// </summary>
 /// <param name="IP">IP address of the Visitor</param>
 /// <param name="pReferer">A cookie (i.e. URL Referer) of the visitor stored with the Log Entry</param>
 /// <returns></returns>
 public Guid LogVisitor(string IP, string pReferer)
 {
     if (mIsHostLogged)
     {
         TheVisitorLogData tLog    = new TheVisitorLogData();
         string            tFilter = "";
         lock (mVisitorListLock)
         {
             tLog.ip          = IP;
             tLog.LastVisit   = DateTimeOffset.Now;
             tLog.Referrer    = pReferer;
             tLog.Description = "VISITOR";
             tFilter          = "ip='" + IP + "'";
             if (mVisitorList.ContainsKey(tFilter) && DateTimeOffset.Now.Subtract(mVisitorList[tFilter].LastVisit).TotalMinutes < 10)
             {
                 return(Guid.Empty);
             }
             if (mVisitorList.ContainsKey(tFilter))
             {
                 mVisitorList[tFilter] = tLog;
             }
             else
             {
                 mVisitorList.TryAdd(tFilter, tLog);
             }
         }
         MyVisitorLogStore.GetRecords(tFilter, 1, GetIP, false);
         return(tLog.cdeMID);
     }
     return(Guid.Empty);
 }
Example #5
0
 public void RegisterUPnPUID(string pUid, Action <TheUPnPDeviceInfo> pCallback)
 {
     if (!mUPnpUIDs.ContainsKey(pUid))
     {
         mUPnpUIDs.TryAdd(pUid, pCallback);
         ScanKnownDevices(pUid);
     }
 }
Example #6
0
 private static void CreateKPIIndexes()
 {
     // We could wait here for engines, but then other KPIs will not be written in meantime
     // await TheBaseEngine.WaitForEnginesStartedAsync();
     KPIIndexes = new cdeConcurrentDictionary <string, int>();
     lock (KPIIndexes)
     {
         Array indexes = Enum.GetValues(typeof(eKPINames));
         foreach (var index in indexes)
         {
             KPIIndexes.TryAdd(Enum.GetName(typeof(eKPINames), index), (int)index);
         }
         List <string> engineNames = TheThingRegistry.GetEngineNames(false);
         foreach (string engineName in engineNames)
         {
             KPIIndexes.TryAdd($"TSMbyENG-{engineName}", KPIIndexes.Count);
         }
     }
 }
Example #7
0
 public bool RegisterDISCOService(ICDEDiscoService pScanner)
 {
     if (pScanner == null || pScanner.GetBaseThing() == null)
     {
         return(false);
     }
     if (MyDiscoScanners.Any(s => s.Key == pScanner.GetBaseThing().cdeMID))
     {
         return(false);
     }
     pScanner.StartService(this);
     MyDiscoServices.TryAdd(pScanner.GetBaseThing().cdeMID, pScanner);
     return(true);
 }
Example #8
0
 public TheWSProcessor8(object wsc)
 {
     websocket = wsc as WebSocket;
     if (websocket != null)
     {
         while (!allSockets.TryAdd(websocket, this))
         {
             if (allSockets.TryRemove(websocket, out TheWSProcessor8 wsProcessor))
             {
                 TheBaseAssets.MySYSLOG.WriteToLog(4363, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("TheWSProcessor8", "Attempt to create second TheWSProcessor8 instance for the same websocket!", eMsgLevel.l2_Warning, wsProcessor.IsActive.ToString()));
             }
         }
     }
 }
Example #9
0
        public bool RegisterScanner(ICDESniffer pScanner)
        {
            if (pScanner == null || pScanner.GetBaseThing() == null)
            {
                return(false);
            }
            if (MyDiscoScanners.Any(s => s.Key == pScanner.GetBaseThing().cdeMID))
            {
                return(false);
            }

            pScanner.RegisterDeviceLost(sinkByeBye);
            pScanner.StartScan(this);
            MyDiscoScanners.TryAdd(pScanner.GetBaseThing().cdeMID, pScanner);
            return(true);
        }
Example #10
0
 internal static TheThing RegisterNMISubscription(TheClientInfo pClientInfo, string pDataItem, TheMetaDataBase tFld)
 {
     if (!string.IsNullOrEmpty(pDataItem))
     {
         TheThing tThing = null;
         lock (MyNMIElements.MyLock) //This can cause jams of threads here! Highly optimized to get out of lock as fast as possible
         {
             if (!MyNMIElements.ContainsKey(tFld.cdeMID))
             {
                 MyNMIElements.TryAdd(tFld.cdeMID, new cdeConcurrentDictionary <Guid, TheNMISubscription>());
             }
             if (!MyNMIElements[tFld.cdeMID].ContainsKey(pClientInfo.NodeID))
             {
                 tThing = TheThingRegistry.GetThingByMID(tFld.cdeO); //Most expensive call in here
                 if (tThing != null)
                 {
                     var tNewEle = new TheNMISubscription()
                     {
                         cdeN = pClientInfo.NodeID, cdeO = tThing.cdeMID, HasLiveSub = true, DataItem = pDataItem, cdeMID = tFld.cdeMID
                     };
                     MyNMIElements[tFld.cdeMID].TryAdd(pClientInfo.NodeID, tNewEle);
                 }
             }
         }
         if (tThing != null)
         {
             if (tFld is TheFieldInfo && (tFld as TheFieldInfo).Type == eFieldType.Table)    //fix for Bug#1195
             {
                 return(tThing);
             }
             RegisterNewNMINode(pClientInfo.NodeID, tFld.cdeMID, tThing.cdeMID, pDataItem, true);
             var OnUpdateName = pDataItem;
             if (OnUpdateName.StartsWith("MyPropertyBag."))  //TODO: Test this with Prop of Prop
             {
                 OnUpdateName = OnUpdateName.Split('.')[1];
             }
             tThing.GetProperty(OnUpdateName, true).SetPublication(true, Guid.Empty); //Guid.Empty uses PublishCentral - a specific node would use SYSTEMWIDE
             return(tThing);
         }
     }
     return(null);
 }
Example #11
0
            internal void RequestOwnership(string correlationToken, string sourceORG, string ownerORG)
            {
                _pendingAcks.TryAdd(correlationToken, new TaskCompletionSource <bool>(DateTimeOffset.Now + new TimeSpan(0, 1, 0)));

                if (_ackCleanupTask == null)
                {
                    _ackCleanupTask = TheCommonUtils.cdeRunTaskAsync("ackCleanup", async(o) =>
                    {
                        try
                        {
                            while (!_pendingAcks.IsEmpty && TheBaseAssets.MasterSwitch)
                            {
                                try
                                {
                                    await TheCommonUtils.TaskDelayOneEye(61000, 100).ConfigureAwait(false);
                                }
                                catch { }
                                var now = DateTimeOffset.Now;
                                foreach (var ack in _pendingAcks.GetDynamicEnumerable())
                                {
                                    try
                                    {
                                        var expiration = (DateTimeOffset?)ack.Value?.Task?.AsyncState;
                                        if (expiration < now)
                                        {
                                            _pendingAcks.RemoveNoCare(ack.Key);
                                        }
                                    }
                                    catch { }
                                }
                            }
                        }
                        catch { }
                        finally
                        {
                            _ackCleanupTask = null;
                        }
                    }).ContinueWith(c => { var ignored = c.Exception; }, TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously);
                }
            }
Example #12
0
 internal static bool RegisterNewNMINode(Guid pNodeID, Guid pID, Guid pOwner, string pDataItem, bool?pHasLiveSubs)
 {
     if (MyAliveNMINodes.ContainsKey(pNodeID))
     {
         if (pID != Guid.Empty)
         {
             MyAliveNMINodes[pNodeID].cdeMID = pID;
         }
         if (pOwner != Guid.Empty)
         {
             MyAliveNMINodes[pNodeID].cdeO = pOwner;
         }
         if (!string.IsNullOrEmpty(pDataItem))
         {
             MyAliveNMINodes[pNodeID].DataItem = pDataItem;
         }
         if (pHasLiveSubs != null)
         {
             MyAliveNMINodes[pNodeID].HasLiveSub = TheCommonUtils.CBool(pHasLiveSubs);
         }
         return(true);
     }
     else
     {
         var tsub = new TheNMISubscription()
         {
             cdeN = pNodeID, cdeO = pOwner, DataItem = pDataItem, HasLiveSub = TheCommonUtils.CBool(pHasLiveSubs), cdeMID = pID
         };
         MyAliveNMINodes.TryAdd(pNodeID, tsub);
         if (pOwner != Guid.Empty)
         {
             MyAliveThings[pOwner] = tsub;
         }
     }
     return(false);
 }
Example #13
0
        /// <summary>
        /// Adds a new callback to the waiting list
        /// </summary>
        /// <param name="pCallBack">The callback to be called</param>
        /// <param name="pTimeOut">A timeout after which the callback will be called if it has not fired before.</param>
        /// <param name="pCookie">A cookie that will be fired with the callback to be sent back to the caller</param>
        /// <returns></returns>
        public static string AddTimedRequest(Action <string, T> pCallBack, int pTimeOut, object pCookie)
        {
            TheTimedRequest <T> tReq = new TheTimedRequest <T>
            {
                MyRequest = pCallBack,
                MagicID   = Guid.NewGuid(),
                Cookie    = pCookie
            };
            string Magix = tReq.MagicID.ToString();

            SetFailureTimer(tReq, pTimeOut);
            lock (MyStoreRequestsLock)
            {
                if (MyStoreRequests.ContainsKey(tReq.MagicID.ToString()))
                {
                    MyStoreRequests[tReq.MagicID.ToString()] = tReq;
                }
                else
                {
                    MyStoreRequests.TryAdd(tReq.MagicID.ToString(), tReq);
                }
            }
            return(Magix);
        }
        internal static bool GetLocalIPs(bool AddLoopBack)
        {
            bool NewAddition = false;
            bool HasLoop     = false;

            if ((Type.GetType("Mono.Runtime") != null))
            {
                try
                {
                    if (string.IsNullOrEmpty(MyHostName))
                    {
                        MyHostName = cdeGetHostName();
                    }

                    IPHostEntry hostByName = cdeGetHostEntry(MyHostName);
                    if (hostByName == null)
                    {
                        return(false);
                    }
                    TheSystemMessageLog.ToCo(string.Format("NetworkInfo - HostName : {0}", hostByName.HostName));
                    ArrayList tAddressTable = new ArrayList(hostByName.AddressList);
                    foreach (IPAddress address in tAddressTable)
                    {
                        if (address.AddressFamily != AddressFamily.InterNetworkV6)
                        {
                            NewAddition = true;
                            byte[]   ipAdressBytes = address.GetAddressBytes();
                            TheIPDef tI            = new TheIPDef()
                            {
                                ipAdressBytes = ipAdressBytes, SubnetBytes = new byte[] { 255, 0, 0, 0 }, IPAddr = address, IsDnsEnabled = true, IsPrivateIP = IsPrivateIPBytes(ipAdressBytes)
                            };
                            if (address.ToString().Equals(IPAddress.Loopback.ToString()))
                            {
                                HasLoop       = true;
                                tI.IsLoopBack = true;
                            }
                            AddressTable.TryAdd(address, tI);
                        }
                    }
                    //TheSystemMessageLog.ToCo($"NetworkInfo - AddressTable : {AddressTable.Aggregate("", (s, a) => $"{s} {a}")}");
                }
                catch (Exception e)
                {
                    TheSystemMessageLog.ToCo($"NetworkInfo - Exception: {e.ToString()}");
                    // throw;
                }
            }
            else
            {
                NetworkInterface[] networkInterfaces;
                try
                {
                    networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
                }
                catch
                {
                    networkInterfaces = null;
                }
                if (networkInterfaces != null)
                {
                    foreach (var f in networkInterfaces)
                    {
                        var ipInterface = f.GetIPProperties();

                        foreach (UnicastIPAddressInformation unicastAddress in ipInterface.UnicastAddresses)
                        {
                            try
                            {
                                if (unicastAddress.IPv4Mask != null)
                                {
                                    IPv4InterfaceProperties ipv4_properties = null;
                                    try
                                    {
                                        ipv4_properties = ipInterface.GetIPv4Properties();
                                    }
                                    catch
                                    {
                                        //ignored
                                    }
                                    if (ipv4_properties == null)
                                    {
                                        continue;                           //TODO: IPv6 Support later
                                    }
                                    byte[] tSubnetBytes = unicastAddress.IPv4Mask.GetAddressBytes();
                                    if (tSubnetBytes[0] == 0)
                                    {
                                        continue;
                                    }
                                    byte[]    ipAdressBytes = unicastAddress.Address.GetAddressBytes();
                                    IPAddress tIP           = new IPAddress(ipAdressBytes);
                                    if (!AddressTable.ContainsKey(tIP))
                                    {
                                        TheIPDef tI = new TheIPDef()
                                        {
                                            ipAdressBytes = ipAdressBytes,
                                            SubnetBytes   = tSubnetBytes,
                                            IPAddr        = tIP,
                                            //IsDnsEnabled = unicastAddress.IsDnsEligible,
                                            IsPrivateIP           = IsPrivateIPBytes(ipAdressBytes),
                                            NetworkInterfaceIndex = ipv4_properties.Index,
                                            MACAddress            = f.GetPhysicalAddress().ToString(),
                                        };
                                        if (!_platformDoesNotSupportUnicastIPAddressInformationIsDNSEnabled)
                                        {
                                            try
                                            {
                                                tI.IsDnsEnabled = unicastAddress.IsDnsEligible;
                                            }
                                            catch (PlatformNotSupportedException)
                                            {
                                                _platformDoesNotSupportUnicastIPAddressInformationIsDNSEnabled = true;
                                            }
                                        }
                                        if (_platformDoesNotSupportUnicastIPAddressInformationIsDNSEnabled)
                                        {
                                            if (string.IsNullOrEmpty(MyHostName))
                                            {
                                                MyHostName = cdeGetHostName();
                                            }
                                            var ipAddresses = cdeGetHostEntry(MyHostName)?.AddressList;
                                            if (ipAddresses?.FirstOrDefault(ip => ip.Equals(unicastAddress.Address)) != null)
                                            {
                                                tI.IsDnsEnabled = true;
                                            }
                                        }
                                        if (tIP.ToString().Equals(IPAddress.Loopback.ToString()))
                                        {
                                            HasLoop       = true;
                                            tI.IsLoopBack = true;
                                        }
                                        AddressTable.TryAdd(tIP, tI);
                                        NewAddition = true;
                                    }
                                }
                            }
                            catch
                            {
                            }
                        }
                    }
                }
            }

            if (AddLoopBack && !HasLoop)
            {
                AddressTable.TryAdd(IPAddress.Loopback, new TheIPDef()
                {
                    IPAddr = IPAddress.Loopback, ipAdressBytes = IPAddress.Loopback.GetAddressBytes(), SubnetBytes = new byte[] { 255, 0, 0, 0 }, IsPrivateIP = true, IsDnsEnabled = false, IsLoopBack = true
                });
                NewAddition = true;
            }
            return(NewAddition);
        }