Example #1
0
        /// <summary>
        /// Delete index
        /// </summary>
        public virtual void DeleteIndex(string alias = null)
        {
            lock (_lockObject)
            {
                var client = CreateElasticClient(CommonConnectionSettings.ConnectionSettings); // use a raw elasticclient because we just need this to be quick

                var indicesToDelete = new List <string>();

                if (alias == null) // determine if we are deleting only aliases of all index prefixes
                {
                    var indexPrefix = $"{Index}_";
                    var indices     = client.CatIndices();

                    if (indices?.Records?.Any() == true)
                    {
                        foreach (var index in indices.Records.Where(i => i.Index.StartsWith(indexPrefix)).Select(i => i.Index))
                        {
                            indicesToDelete.Add(index);
                        }
                    }
                }
                else
                {
                    var aliasPrefix = $"{Index}-" + alias;

                    var aliases = client.CatAliases();

                    if (aliases?.Records?.Any() == true)
                    {
                        foreach (var index in aliases.Records.Where(a => a.Alias.StartsWith(aliasPrefix)).Select(i => i.Index))
                        {
                            indicesToDelete.Add(index);
                        }
                    }
                }

                var deleted = new List <string>();

                if (indicesToDelete.Any())
                {
                    foreach (var index in indicesToDelete)
                    {
                        var response = client.DeleteIndex(index);

                        if (!response.IsValid)
                        {
                            Logger.Error($"Could not run a delete index: {response.DebugInformation}");
                        }
                        else
                        {
                            deleted.Add(index);
                        }
                    }

                    DeletedIndices?.Invoke(deleted);
                }

                Clients?.Clear(); // need to force a re-creation
            }
        }
Example #2
0
 public void Dispose()
 {
     Console.WriteLine("Dispose");
     _sockets?.Clear();
     _channel?.Dispose();
     _conn?.Dispose();
 }
Example #3
0
        public override void Dispose()
        {
            using (Trace.Log())
            {
                Console.WriteLine($"Disposing {Identifier}");

                Disposed?.Invoke(this);

                disposed = true;

                activeJob?.CancelTasks(pendingTasks.Values);
                activeJob?.CancelTasks(activeTasks.Values);
                activeJob = null;

                activeTasks?.Clear();
                pendingTasks?.Clear();

                if (dispatcher != null)
                {
                    dispatcher.ActiveJobChanged -= OnActiveJobChanged;
                    dispatcher = null;
                }

                connection?.Dispose();
                connection = null;

                TaskStateChanged = null;
            }
        }
        /// <summary>
        /// Returns the color count from the palette of the given image.
        /// </summary>
        /// <param name="image">
        /// The <see cref="System.Drawing.Image"/> to get the colors from.
        /// </param>
        /// <returns>
        /// The <see cref="int"/> representing the color count.
        /// </returns>
        public static int GetColorCount(Image image)
        {
            ConcurrentDictionary<Color, Color> colors = new ConcurrentDictionary<Color, Color>();
            int width = image.Width;
            int height = image.Height;

            using (FastBitmap fastBitmap = new FastBitmap(image))
            {
                Parallel.For(
                    0,
                    height,
                    y =>
                    {
                        for (int x = 0; x < width; x++)
                        {
                            // ReSharper disable once AccessToDisposedClosure
                            Color color = fastBitmap.GetPixel(x, y);
                            colors.TryAdd(color, color);
                        }
                    });
            }

            int count = colors.Count;
            colors.Clear();
            return count;
        }
 public void ClearCorrelation()
 {
     threadId      = null;
     correlationId = null;
     correlationDictionary?.Clear();
     correlationDictionary = null;
 }
Example #6
0
        public virtual void Dispose()
        {
            if (_disposed)
            {
                return;
            }
            lock (this)
            {
                if (_disposed)
                {
                    return;
                }

                _cts.Cancel();
                _disposed = true;
                CleanThreadLocalState();
                ThreadLocalCleanup.ReleaseThreadLocalState -= CleanThreadLocalState;
                _nativeMemoryCleaner.Dispose();
                _nativeMemoryCleaner = null;

                foreach (var kvp in EnumerateAllThreadContexts())
                {
                    kvp.Dispose();
                }
                _contextStacksByThreadId?.Clear();
                _contextStacksByThreadId = null;
                _threadIds = Array.Empty <ThreadIdHolder>();
            }
        }
Example #7
0
        protected void Dispose(bool disposing)
        {
            if (!disposing)
            {
                return;
            }

            if (_cancel != null)
            {
                _cancel.Cancel();
                _cancel.Token.WaitHandle.WaitOne();
                _cancel.Dispose();
                _cancel = null;
            }

            _factories?.Clear();
            _schedulers?.Clear();

            _scheduler?.Dispose();
            _scheduler = null;

            _background?.Dispose();
            _background = null;

            _maintenance?.Dispose();
            _maintenance = null;
        }
Example #8
0
 public override void Dispose()
 {
     LoggerExtensions.LogTrace(_logger, "Disposing", Array.Empty <object>());
     _queue.Dispose();
     base.Dispose();
     _delayedMessages?.Clear();
     _subscribers?.Clear();
 }
Example #9
0
 public void Clear()
 {
     lock (_lock)
     {
         _members?.Clear();
         _residualMembers?.Clear();
     }
 }
		static DebuggerDecompilerService()
		{
			DebugInformation = new ConcurrentDictionary<int, DecompileInformation>();
			ProjectService.SolutionClosed += delegate {
				DebugInformation.Clear();
				GC.Collect();
			};
		}
Example #11
0
 public void Dispose()
 {
     changes?.Clear();
     changes = null;
     timer?.Dispose();
     timer = null;
     watcher?.Dispose();
     watcher = null;
 }
Example #12
0
        public void Dispose()
        {
            Project.FileAddedToProject     -= OnFileAddedToProject;
            Project.FileRemovedFromProject -= OnFileRemovedFromProject;
            Project.FileRenamedInProject   -= OnFileRenamedInProject;
            Project.ParentSolution.UserProperties.Changed -= OnUserPropertiesChanged;

            projectFiles?.Clear();
        }
Example #13
0
 public void Dispose()
 {
     foreach (var item in _dbConnectionCache)
     {
         item.Value?.Close();
         item.Value?.Dispose();
     }
     _dbConnectionCache?.Clear();
 }
Example #14
0
 static ObjectBaseValidator()
 {
     Cache = new ConcurrentDictionary<Type, ObjectBaseValidator>();
     DxSettings.GlobalSettings.PropertyChanged += (sender, e) =>
     {
         if (e.PropertyName == "CacheTypeCheckers" && !DxSettings.GlobalSettings.CacheTypeCheckers)
             Cache.Clear();
     };
 }
Example #15
0
 /// <summary>
 /// 执行与释放或重置非托管资源关联的应用程序定义的任务。
 /// </summary>
 public void Dispose()
 {
     foreach (var item in _channelDic)
     {
         item.Value?.Dispose();
     }
     _connection?.Dispose();
     _channelDic?.Clear();
 }
Example #16
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="disposing"></param>
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         _cts.Cancel();
         _executingJobs?.Values.ToList().ForEach(x => x.Dispose());
         _executingJobs?.Clear();
     }
 }
Example #17
0
 private void HideActiveAnimations()
 {
     LocalEntities?.Values.ToList().ForEach(entity => entity?.ClearAnimations(null));
     foreach (var anim in LocalAnimations)
     {
         anim.Value?.Dispose();
     }
     LocalAnimations?.Clear();
     ClearMapAttributes();
 }
Example #18
0
 /// <summary>
 /// Disposes the instance and every registered node.
 /// </summary>
 public void Dispose()
 {
     _subsDictionary?.Clear();
     _nodes.Keys.ForEach(n =>
     {
         try { n.Dispose(); }
         catch { }
     });
     _nodes?.Clear();
 }
 /// <summary>
 /// Clear all caches
 /// </summary>
 public static void ClearCaches()
 {
     s_viewStateAssets?.Clear();
     s_widgetAssets?.Clear();
     s_viewModelCache?.Clear();
     s_templateCache?.Clear();
     s_cache?.Clear();
     s_viewStateAssets = null;
     s_widgetAssets    = null;
 }
    public static ActionBlock<StatsdMessage> CreateBlock(ITargetBlock<Bucket> target,
      string rootNamespace, 
      bool removeZeroGauges,
      IIntervalService intervalService,
      ILog log)
    {
      var gauges = new ConcurrentDictionary<string, double>();
      var root = rootNamespace;
      var ns = String.IsNullOrEmpty(rootNamespace) ? "" : rootNamespace + ".";

      var incoming = new ActionBlock<StatsdMessage>(p =>
        {
          var gauge = p as Gauge;
          gauges.AddOrUpdate(gauge.Name, gauge.Value, (key, oldValue) => gauge.Value);
        },
        Utility.UnboundedExecution());

      intervalService.Elapsed += (sender, e) =>
        {
          if (gauges.Count == 0)
          {
            return;
          }
          var items = gauges.ToArray();
          var bucket = new GaugesBucket(items, e.Epoch, ns);
          if (removeZeroGauges)
          {
            // Get all zero-value gauges
            double placeholder;
            var zeroGauges = 0;
            for (int index = 0; index < items.Length; index++)
            {
              if (items[index].Value == 0)
              {
                gauges.TryRemove(items[index].Key, out placeholder);
                zeroGauges += 1;
              }
            }
            if (zeroGauges > 0)
            {
              log.InfoFormat("Removed {0} empty gauges.", zeroGauges);
            }
          }
          
          gauges.Clear();
          target.Post(bucket);
        };

      incoming.Completion.ContinueWith(p =>
        {
          // Tell the upstream block that we're done
          target.Complete();
        });
      return incoming;
    }
Example #21
0
        public void Dispose()
        {
            var contexts = _contexts.Values.ToList();

            foreach (var context in contexts)
            {
                context.Dispose();
            }

            _contexts?.Clear();
        }
Example #22
0
 public void Dispose()
 {
     changes?.Clear();
     changes = null;
     timer?.Dispose();
     timer = null;
     watcher?.Dispose();
     watcher = null;
     gameDirectoryWatcher?.Dispose();
     gameDirectoryWatcher = null;
 }
Example #23
0
 static PlatformFactory()
 {
     HelperCache = new ConcurrentDictionary<string, HelperBase>();
     //添加监听
     ConfigManager.Change += file =>
     {
         if (file == ConfigUtils<PlatformConfig>.Instance.FileName)
         {
             HelperCache.Clear();
         }
     };
 }
Example #24
0
 public void Dispose()
 {
     chunks?.Clear();
     chunks = null;
     tgts?.Clear();
     tgts = null;
     refs?.Clear();
     refs = null;
     root = null;
     server?.Dispose();
     server = null;
 }
    public static ActionBlock<StatsdMessage> CreateBlock(ITargetBlock<Bucket> target,
      string rootNamespace, 
      IIntervalService intervalService,
      int percentile,
      string percentileName,
      ILog log,
      int maxItemsPerBucket = 1000)
    {
      var latencies = new ConcurrentDictionary<string, DatapointBox>();
      var root = rootNamespace;
      var ns = String.IsNullOrEmpty(rootNamespace) ? "" : rootNamespace + ".";
      var random = new Random();
      percentileName = "." + ( percentileName ?? ( "p" + percentile ) );

      var incoming = new ActionBlock<StatsdMessage>( p =>
        {
          var latency = p as Timing;
          latencies.AddOrUpdate(latency.Name,
              (key) =>
              {
                return new DatapointBox(maxItemsPerBucket, latency.ValueMS); 
              },
              (key, bag) =>
              {
                bag.Add(latency.ValueMS);
                return bag;
              });
        },
        new ExecutionDataflowBlockOptions() { MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded });

      intervalService.Elapsed += (sender, e) =>
        {
          if (latencies.Count == 0)
          {
            return;
          }
          var bucket = new PercentileBucket(latencies.ToArray(),
            e.Epoch,
            ns,
            percentileName,
            percentile);
          latencies.Clear();
          target.Post(bucket);
        };

      incoming.Completion.ContinueWith(p =>
        {
          // Tell the upstream block that we're done
          target.Complete();
        });
      return incoming;
    }
Example #26
0
        public void GuardAgainstRace()
        {
            // This code will trigger the load of CDSCollectionETWBCLProvider
            var dictionary = new ConcurrentDictionary<int, int>();
            dictionary.Clear();

            var log = typeof(ConcurrentDictionary<int, int>)
                .Assembly
                .GetType("System.Collections.Concurrent.CDSCollectionETWBCLProvider")
                .GetField("Log", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static)
                .GetValue(null);
            Assert.NotNull(log);
        }
        /// <summary>
        /// This method adds the serializer to the collection.
        /// </summary>
        /// <param name="serializer">The serializer to add.</param>
        public IPayloadSerializer Add(IPayloadSerializer serializer)
        {
            if (string.IsNullOrEmpty(serializer.ContentType))
            {
                throw new ArgumentOutOfRangeException("ContentType cannot be null or empty.");
            }

            var contentType = serializer.ContentType.ToLowerInvariant();

            mPayloadSerializers.Add(contentType, serializer);
            if (serializer is IPayloadSerializerMagicBytes)
            {
                var mb = (IPayloadSerializerMagicBytes)serializer;
                mPayloadSerializersMagicBytes.Add(mb.ToIdentifier(), mb);
            }

            mLookUpCache?.Clear();

            DefaultContentType = DefaultContentType ?? contentType;

            return(serializer);
        }
    public static ActionBlock<StatsdMessage> CreateBlock(ITargetBlock<SetsBucket> target,
      string rootNamespace, 
      IIntervalService intervalService,
      ILog log)
    {
      var sets = new ConcurrentDictionary<string, ConcurrentDictionary<int, bool>>();
      var root = rootNamespace;
      var ns = String.IsNullOrEmpty(rootNamespace) ? "" : rootNamespace + ".";

      var incoming = new ActionBlock<StatsdMessage>(p =>
        {
          var set = p as Set;
          sets.AddOrUpdate(set.Name, 
            (key) =>
              {
                var setDict = new ConcurrentDictionary<int, bool>();
                setDict.AddOrUpdate( set.Value, ( key2 ) => true, ( key2, oldValue ) => true );
                return setDict;
              },
            (key, setDict) =>
              {
                setDict.AddOrUpdate( set.Value, ( key2 ) => true, ( key2, oldValue ) => true );
                return setDict;
              });
        },
        new ExecutionDataflowBlockOptions() { MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded });

      intervalService.Elapsed += (sender, e) =>
        {
          if (sets.Count == 0)
          {
            return;
          }
          var rawData = sets.ToArray();
          sets.Clear();
          var bucket = new SetsBucket(
            rawData.Select(p =>
              new KeyValuePair<string, List<KeyValuePair<int, bool>>>(p.Key, p.Value.ToList())
            ).ToList(),
            e.Epoch,
            ns);

          target.Post(bucket);
        };
      incoming.Completion.ContinueWith(p =>
        {
          // Tell the upstream block that we're done
          target.Complete();
        });
      return incoming;
    }
        protected override void DisposeResources()
        {
            //// Add lock here

            foreach (System.Collections.Generic.KeyValuePair <string, CacheItem> pair in _keyDataMappings)
            {
                pair.Value?.Dispose();
            }

            _keyDataMappings?.Clear();
            _keyTmpLockMappings?.Clear();

            _lockForClean?.Dispose();
        }
Example #30
0
        /// <summary>
        /// Disposes of managed and unmanaged resources.
        /// </summary>
        /// <param name="disposing">True - the method has been called (in)directly by code.
        /// False - the method has been called by the runtime from inside the finalizer -
        /// do not reference other objects.</param>
        private void Dispose(bool disposing)
        {
            // Check to see if Dispose() has already been called
            if (!disposed)
            {
                // Dispose all managed and unmanaged resources
                // Called upon IDE shutdown
                if (disposing)
                {
                    _features?.Clear();
                }
            }

            disposed = true;
        }
        /// <summary>
        /// Constructs a new MultiClampDevice
        /// </summary>
        /// <param name="commander">MultiClampCommander instance</param>
        /// <param name="c">Symphony Controller instance</param>
        /// <param name="background">Dictionary of background Measurements for each MultiClamp operating mode</param>
        public MultiClampDevice(IMultiClampCommander commander, Controller c, IDictionary<MultiClampInterop.OperatingMode, IMeasurement> background)
            : base("Multiclamp-" + commander.SerialNumber + "-" + commander.Channel, "Molecular Devices", c)
        {
            InputParameters = new ConcurrentDictionary<DateTimeOffset, MultiClampParametersChangedArgs>();
            OutputParameters = new ConcurrentDictionary<DateTimeOffset, MultiClampParametersChangedArgs>();

            Commander = commander;
            Commander.ParametersChanged += (sender, mdArgs) =>
                {
                    lock (_bindLock)
                    {
                        log.DebugFormat(
                            "MultiClamp parameters changed. Mode = {0}, External Command Sensistivity Units = {1} Timestamp = {2}",
                            mdArgs.Data.OperatingMode,
                            mdArgs.Data.ExternalCommandSensitivityUnits,
                            mdArgs.TimeStamp);

                        if (!HasBoundInputStream)
                            InputParameters.Clear();

                        InputParameters[mdArgs.TimeStamp.ToUniversalTime()] = mdArgs;

                        if (!HasBoundOutputStream)
                            OutputParameters.Clear();

                        OutputParameters[mdArgs.TimeStamp.ToUniversalTime()] = mdArgs;

                        foreach (var outputStream in OutputStreams.Where(s => s.DAQ != null && s.DAQ.IsHardwareReady && !s.DAQ.IsRunning))
                        {
                            log.DebugFormat("Setting new background for stream {0}", outputStream.Name);
                            try
                            {
                                outputStream.ApplyBackground();
                            }
                            catch (Exception x)
                            {
                                log.ErrorFormat("Error applying new background: {0}", x);
                                throw;
                            }

                        }
                    }
                };
            Commander.RequestTelegraphValue();

            Backgrounds = background;
        }
Example #32
0
 public void Dispose()
 {
     if (_contexts != null)
     {
         foreach (var context in _contexts)
         {
             context.Value?.Dispose();
         }
     }
     _contexts?.Clear();
     _contexts = null;
     connnections?.ForEach(item =>
     {
         item.Dispose();
     });
     connnections?.Clear();
     connnections = null;
 }
Example #33
0
        protected virtual void Dispose(bool disposing)
        {
            if (_disposed)
            {
                return;
            }

            Disconnect();

            if (disposing)
            {
                _channel?.Dispose();
                _connection?.Dispose();
            }

            _typeMap?.Clear();
            _disposed = true;
        }
Example #34
0
 public void Dispose()
 {
     if (isdisposed)
     {
         return;
     }
     lock (isdisposedLock)
     {
         if (isdisposed)
         {
             return;
         }
         isdisposed = true;
     }
     _ib?.Dispose();
     _wq?.Dispose();
     _tasks?.Clear();
     Interlocked.Exchange(ref _quantityTempTask, 0);
     Interlocked.Exchange(ref _quantityTask, 0);
     (_taskHandler as IDisposable)?.Dispose();
 }
        public void Dispose()
        {
            if (_isDisposed)
            {
                return;
            }

            foreach (var item in _moduleStates)
            {
                item.Value.Dispose();
            }

            CoClasses?.Clear();
            RemoveEventHandlers();

            _moduleStates.Clear();
            // no lock because nobody should try to update anything here
            _projects.Clear();

            _isDisposed = true;
        }
        void IProxyService.Start()
        {
            ProxyClients = new ConcurrentDictionary<IntPtr, Socket>();
            new Thread(async t =>
            {
                ProxyConnection = new TcpListener(IPAddress.Any, 3939);
                ProxyConnection.Start();

                while (true)
                {
                    var socket = await ProxyConnection.AcceptSocketAsync();
                    ProxyClients.Clear();
                    ProxyClients.TryAdd(socket.Handle, socket);

                    var socketAsyncEventArgs = new SocketAsyncEventArgs();
                    byte[] buffer = new byte[8192];
                    socketAsyncEventArgs.SetBuffer(buffer, 0, buffer.Length);
                    socketAsyncEventArgs.Completed += SocketAsyncEventArgs_Completed;
                    socket.ReceiveAsync(socketAsyncEventArgs);
                }
            }).Start();
        }
    public static ActionBlock<StatsdMessage> CreateBlock(ITargetBlock<Bucket> target,
      string rootNamespace, 
      IIntervalService intervalService,
      ILog log)
    {
      var counters = new ConcurrentDictionary<string, double>();
      var root = rootNamespace;
      var ns = String.IsNullOrEmpty(rootNamespace) ? "" : (rootNamespace + ".");

      var incoming = new ActionBlock<StatsdMessage>(p =>
        {
          var counter = p as Counter;
          counters.AddOrUpdate(counter.Name, counter.Value, (key, oldValue) => oldValue + counter.Value);
        },
        new ExecutionDataflowBlockOptions() { MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded });

      intervalService.Elapsed += (sender, e) =>
        {
          if (counters.Count == 0)
          {
            return;
          }

          var bucket = new CounterBucket(counters.ToArray(), e.Epoch, ns);
          counters.Clear();
          target.Post(bucket);
        };

      incoming.Completion.ContinueWith(p =>
        {
          log.Info("TimedCounterAggregatorBlock completing.");
          // Tell the upstream block that we're done
          target.Complete();
        });
      return incoming;
    }
Example #38
0
        public ImbleWatcher()
        {
            this.watcher = new BluetoothLEAdvertisementWatcher();
            this.watcher.ScanningMode = BluetoothLEScanningMode.Active;     // We have to perform active scanning to check scan responses from devices.
            this.resetSubject = new Subject<Unit>().AddTo(this.disposables);
            
            var candidateAddresses = new ConcurrentDictionary<ulong, ulong>();
            var resetObservable = this.resetSubject
                .Do(_ => candidateAddresses.Clear());

            var receivedObservable = Observable.FromEvent<TypedEventHandler<BluetoothLEAdvertisementWatcher, BluetoothLEAdvertisementReceivedEventArgs>, BluetoothLEAdvertisementReceivedEventArgs>(
                handler => (sender, args) => handler(args),
                handler => this.watcher.Received += handler,
                handler => this.watcher.Received -= handler)
                .Publish();

            // Check scan responses and add their address to the candidate device list if they contains the target service UUID as Service Solicitation data.
            receivedObservable
                .Where(args => args.AdvertisementType.HasFlag(BluetoothLEAdvertisementType.ScanResponse))
                .Where(args => args.Advertisement.DataSections.Any(section => MatchSolicitationServiceLong(section, ImbleDevice.ServiceUuid)))
                .Subscribe(args => candidateAddresses.TryAdd(args.BluetoothAddress, args.BluetoothAddress))
                .AddTo(this.disposables);

            // Check advertisement data 
            this.UnconnectedDevices = receivedObservable
                .Where(args => !args.AdvertisementType.HasFlag(BluetoothLEAdvertisementType.ScanResponse))
                .Where(args => candidateAddresses.ContainsKey(args.BluetoothAddress))
                .Distinct(args => args.BluetoothAddress)
                .Select(args => new UnconnectedImbleDevice(args.BluetoothAddress, args.Advertisement, args.RawSignalStrengthInDBm))
                .ToReadOnlyReactiveCollection(resetObservable)
                .AddTo(this.disposables);

            receivedObservable.Connect().AddTo(this.disposables);

            this.watcher.Start();
        }
        public void Clear_ThrowsNotImplementedException()
        {
            // Arrange
            ConcurrentDictionary<int, int> dictionary = new ConcurrentDictionary<int, int>();

            // Act/Assert
            Assert.Throws<NotImplementedException>(() => dictionary.Clear());
        }
        public void Close()
        {
            IsOpen = false;
            var connections = _fdbConnections;
            _fdbConnections = new ConcurrentDictionary<int, IntPtr>();
            foreach(var ptr in connections) {
                ForestDBBridge.Check(err => Native.c4db_close((C4Database*)ptr.Value.ToPointer(), err));
            }

            _fdbConnections.Clear();
        }
Example #41
0
 /// <inheritdoc />
 public void Clear()
 {
     m_content.Clear();
     m_pathRealizationModes?.Clear();
 }
Example #42
0
        /// <summary>
        /// Use this function on a Xbim Model that has just been creted from IFC content
        /// This will create the default 3D mesh geometry for all IfcProducts and add it to the model
        /// </summary>
        /// <param name="model"></param>
        public static void GenerateGeometry(XbimModel model, ILogger Logger = null, ReportProgressDelegate progDelegate = null, IEnumerable<IfcProduct> toMesh = null)
        {
            //Create the geometry engine by reflection to allow dynamic loading of different binary platforms (32, 64 etc)
            Assembly assembly = AssemblyResolver.GetModelGeometryAssembly();
            if (assembly == null)
            {
                if (Logger != null)
                {
#if DEBUG
                    Logger.Error("Failed to load Xbim.ModelGeometry.OCCd.dll Please ensure it is installed correctly");
#else
                    Logger.Error("Failed to load Xbim.ModelGeometry.OCC.dll Please ensure it is installed correctly");
#endif
                }
                return;
            }
            IXbimGeometryEngine engine = (IXbimGeometryEngine)assembly.CreateInstance("Xbim.ModelGeometry.XbimGeometryEngine");
            engine.Init(model);
            if (engine == null)
            {
                if (Logger != null)
                {                   
#if DEBUG
                    Logger.Error("Failed to create Xbim Geometry engine. Please ensure Xbim.ModelGeometry.OCCd.dll is installed correctly");
#else
                    Logger.Error("Failed to create Xbim Geometry engine. Please ensure Xbim.ModelGeometry.OCC.dll is installed correctly");
#endif
                }
                return;
            }
           
            //now convert the geometry
            IEnumerable<IfcProduct> toDraw;
            if (toMesh != null)
                toDraw = toMesh;
            else
                toDraw = model.InstancesLocal.OfType<IfcProduct>().Where(t => !(t is IfcFeatureElement));
            //List<IfcProduct> toDraw = new List<IfcProduct>();
            //  toDraw.Add(model.Instances[513489] as IfcProduct);
            if (!toDraw.Any()) return; //othing to do
            TransformGraph graph = new TransformGraph(model);
            //create a new dictionary to hold maps
            ConcurrentDictionary<int, Object> maps = new ConcurrentDictionary<int, Object>();
            //add everything that may have a representation
            graph.AddProducts(toDraw); //load the products as we will be accessing their geometry

            ConcurrentDictionary<int, MapData> mappedModels = new ConcurrentDictionary<int, MapData>();
            ConcurrentQueue<MapRefData> mapRefs = new ConcurrentQueue<MapRefData>();
            ConcurrentDictionary<int, int[]> written = new ConcurrentDictionary<int, int[]>();

            int tally = 0;
            int percentageParsed = 0;
            int total = graph.ProductNodes.Values.Count;

            try
            {
                //use parallel as this improves the OCC geometry generation greatly
                ParallelOptions opts = new ParallelOptions();
                opts.MaxDegreeOfParallelism = 16;
                XbimRect3D bounds = XbimRect3D.Empty;
                double deflection =  model.ModelFactors.DeflectionTolerance;
#if DOPARALLEL
                Parallel.ForEach<TransformNode>(graph.ProductNodes.Values, opts, node => //go over every node that represents a product
#else
                foreach (var node in graph.ProductNodes.Values)
#endif
                {
                    IfcProduct product = node.Product(model);

                    try
                    {
                        IXbimGeometryModel geomModel = engine.GetGeometry3D(product, maps);
                        if (geomModel != null)  //it has geometry
                        {
                            XbimMatrix3D m3d = node.WorldMatrix();
                            
                            if (geomModel.IsMap) //do not process maps now
                            {
                                MapData toAdd = new MapData(geomModel, m3d, product);
                                if (!mappedModels.TryAdd(geomModel.RepresentationLabel, toAdd)) //get unique rep
                                    mapRefs.Enqueue(new MapRefData(toAdd)); //add ref
                            }
                            else
                            {
                                int[] geomIds;
                                XbimGeometryCursor geomTable = model.GetGeometryTable();

                                XbimLazyDBTransaction transaction = geomTable.BeginLazyTransaction();
                                if (written.TryGetValue(geomModel.RepresentationLabel, out geomIds))
                                {
                                    byte[] matrix = m3d.ToArray(true);
                                    short? typeId = IfcMetaData.IfcTypeId(product);
                                    foreach (var geomId in geomIds)
                                    {
                                        geomTable.AddMapGeometry(geomId, product.EntityLabel, typeId.Value, matrix, geomModel.SurfaceStyleLabel);
                                    }
                                }
                                else
                                {
                                    XbimTriangulatedModelCollection tm = geomModel.Mesh(deflection);
                                    XbimRect3D bb = tm.Bounds;

                                    byte[] matrix = m3d.ToArray(true);
                                    short? typeId = IfcMetaData.IfcTypeId(product);

                                    geomIds = new int[tm.Count + 1];
                                    geomIds[0] = geomTable.AddGeometry(product.EntityLabel, XbimGeometryType.BoundingBox, typeId.Value, matrix, bb.ToDoublesArray(), 0, geomModel.SurfaceStyleLabel);
                                    bb = XbimRect3D.TransformBy(bb, m3d);
                                    if (bounds.IsEmpty)
                                        bounds = bb;
                                    else
                                        bounds.Union(bb);
                                    short subPart = 0;
                                    foreach (XbimTriangulatedModel b in tm)
                                    {
                                        geomIds[subPart + 1] = geomTable.AddGeometry(product.EntityLabel, XbimGeometryType.TriangulatedMesh, typeId.Value, matrix, b.Triangles, subPart, b.SurfaceStyleLabel);
                                        subPart++;
                                    }

                                    //            Debug.Assert(written.TryAdd(geomModel.RepresentationLabel, geomIds));
                                    Interlocked.Increment(ref tally);
                                    if (progDelegate != null)
                                    {
                                        int newPercentage = Convert.ToInt32((double)tally / total * 100.0);
                                        if (newPercentage > percentageParsed)
                                        {
                                            percentageParsed = newPercentage;
                                            progDelegate(percentageParsed, "Meshing");
                                        }
                                    }
                                }
                                transaction.Commit();
                                model.FreeTable(geomTable);

                            }
                        }
                        else
                        {
                            // store a transform only if no geomtery is available
                            XbimGeometryCursor geomTable = model.GetGeometryTable();
                            XbimLazyDBTransaction transaction = geomTable.BeginLazyTransaction();
                            XbimMatrix3D m3dtemp = node.WorldMatrix();
                            byte[] matrix = m3dtemp.ToArray(true);
                            short? typeId = IfcMetaData.IfcTypeId(product);
                            geomTable.AddGeometry(product.EntityLabel, XbimGeometryType.TransformOnly, typeId.Value, matrix, new byte[] {});
                            transaction.Commit();
                            model.FreeTable(geomTable);

                            Interlocked.Increment(ref tally);
                            if (progDelegate != null)
                            {
                                int newPercentage = Convert.ToInt32((double)tally / total * 100.0);
                                if (newPercentage > percentageParsed)
                                {
                                    percentageParsed = newPercentage;
                                    progDelegate(percentageParsed, "Meshing");
                        }
                    }
                        }
                    }
                    catch (Exception e1)
                    {
                        String message = String.Format("Error Triangulating product geometry of entity #{0} - {1}",
                            product.EntityLabel,
                            product.GetType().Name
                            );
                        if (Logger != null) Logger.Error(message, e1);
                    }
                }
#if DOPARALLEL
                );
#endif
                graph = null;

                // Debug.WriteLine(tally);
#if DOPARALLEL
                //now sort out maps again in parallel
                Parallel.ForEach<KeyValuePair<int, MapData>>(mappedModels, opts, map =>
#else
                foreach (var map in mappedModels)
#endif
                {
                    IXbimGeometryModel geomModel = map.Value.Geometry;
                    XbimMatrix3D m3d = map.Value.Matrix;
                    IfcProduct product = map.Value.Product;

                    //have we already written it?
                    int[] writtenGeomids = new int[0];
                    if (!written.TryAdd(geomModel.RepresentationLabel, writtenGeomids))
                    {
                        //make maps    
                        mapRefs.Enqueue(new MapRefData(map.Value)); //add ref
                    }
                    else
                    {
                        m3d = XbimMatrix3D.Multiply(geomModel.Transform, m3d);
                        WriteGeometry(model, written, geomModel, ref bounds, m3d, product, deflection);

                    }

                    Interlocked.Increment(ref tally);
                    if (progDelegate != null)
                    {
                        int newPercentage = Convert.ToInt32((double)tally / total * 100.0);
                        if (newPercentage > percentageParsed)
                        {
                            percentageParsed = newPercentage;
                            progDelegate(percentageParsed, "Meshing");
                        }
                    }
                    map.Value.Clear(); //release any native memory we are finished with this
                }
#if DOPARALLEL
                );
#endif
                //clear up maps
                mappedModels.Clear();
                XbimGeometryCursor geomMapTable = model.GetGeometryTable();
                XbimLazyDBTransaction mapTrans = geomMapTable.BeginLazyTransaction();
                foreach (var map in mapRefs) //don't do this in parallel to avoid database thrashing as it is very fast
                {

                    int[] geomIds;
                    if (!written.TryGetValue(map.RepresentationLabel, out geomIds))
                    {
                        if (Logger != null) Logger.WarnFormat("A geometry mapped reference (#{0}) has been found that has no base geometry", map.RepresentationLabel);
                    }
                    else
                    {

                        byte[] matrix = map.Matrix.ToArray(true);
                        foreach (var geomId in geomIds)
                        {
                            geomMapTable.AddMapGeometry(geomId, map.EntityLabel, map.EntityTypeId, matrix, map.SurfaceStyleLabel);
                        }
                        mapTrans.Commit();
                        mapTrans.Begin();

                    }
                    Interlocked.Increment(ref tally);
                    if (progDelegate != null)
                    {
                        int newPercentage = Convert.ToInt32((double)tally / total * 100.0);
                        if (newPercentage > percentageParsed)
                        {
                            percentageParsed = newPercentage;
                            progDelegate(percentageParsed, "Meshing");
                        }
                    }
                    if (tally % 100 == 100)
                    {
                        mapTrans.Commit();
                        mapTrans.Begin();
                    }

                }
                mapTrans.Commit();

                // Store model regions in the database.
                // all regions are stored for the project in one row and need to be desirialised to XbimRegionCollection before being enumerated on read.
                //
                // todo: bonghi: currently geometry labels of partitioned models are not stored, only their bounding box and count are.
                //
                mapTrans.Begin();
                XbimRegionCollection regions = PartitionWorld(model, bounds);
                IfcProject project = model.IfcProject;
                int projectId = 0;
                if (project != null)
                    projectId = Math.Abs(project.EntityLabel);
                geomMapTable.AddGeometry(projectId, XbimGeometryType.Region, IfcMetaData.IfcTypeId(typeof(IfcProject)), XbimMatrix3D.Identity.ToArray(), regions.ToArray());
                mapTrans.Commit();


                model.FreeTable(geomMapTable);
                if (progDelegate != null)
                {
                    progDelegate(0, "Ready");
                }
            }
            catch (Exception e2)
            {
                if (Logger != null) Logger.Warn("General Error Triangulating geometry", e2);
            }
            finally
            {

            }
        }
Example #43
0
 /// <summary> 清空适配器 </summary>
 public static void ClearAdapter()
 {
     LoggerAdapters?.Clear();
 }
Example #44
0
        protected override void UpdateBlocksToNearbyPlayers(object state)
        {
            BlocksUpdateLock.EnterWriteLock();
            int num = Interlocked.Exchange(ref NumBlocksToUpdate, 0);
            ConcurrentDictionary<short, short> temp = BlocksToBeUpdated;
            BlocksToBeUpdated = BlocksUpdating;
            BlocksUpdateLock.ExitWriteLock();

            BlocksUpdating = temp;

            if (num == 1)
            {
                short keyCoords = BlocksUpdating.Keys.First();
                short index;
                BlocksUpdating.TryGetValue(keyCoords, out index);
                int worldX = (X << 4) + (index >> 12 & 0xf);
                int worldY = (index & 0xff);
                int worldZ = (Z << 4) + (index >> 8 & 0xf);
                byte blockId = World.GetBlockId(worldX, worldY, worldZ);
                byte data = World.GetBlockData(worldX, worldY, worldZ);

                SendPacketToAllNearbyPlayers(new BlockChangePacket
                {X = worldX, Y = (sbyte) worldY, Z = worldZ, Data = data, Type = blockId});

            }
            else if (num < 20)
            {
                sbyte[] data = new sbyte[num];
                sbyte[] types = new sbyte[num];
                short[] blocks = new short[num];

                int count = 0;
                foreach (short key in BlocksUpdating.Keys)
                {
                    short index;
                    BlocksUpdating.TryGetValue(key, out index);
                    int worldX = (X << 4) + (index >> 12 & 0xf);
                    int worldY = (index & 0xff);
                    int worldZ = (Z << 4) + (index >> 8 & 0xf);

                    data[count] = (sbyte)World.GetBlockData(worldX, worldY, worldZ);
                    types[count] = (sbyte)World.GetBlockId(worldX, worldY, worldZ);
                    blocks[count] = index;
                }
                SendPacketToAllNearbyPlayers(new MultiBlockChangePacket { Coords = blocks, Metadata = data, Types = types, X = this.X, Z = this.Z});
            }
            else
            {
                SendPacketToAllNearbyPlayers(new MapChunkPacket { Chunk = this });
            }

            BlocksUpdating.Clear();
            base.UpdateBlocksToNearbyPlayers(state);
        }
Example #45
0
        private bool? ReadTail(string file, LogConfigurationElement log, string locationKey, ConcurrentBag<Metric> boomerangValues)
        {
            var rawValues = new ConcurrentDictionary<LogStatConfigurationElement, ConcurrentBag<Metric>>();

            if (log == null)
            {
                return null;
            }

            //If multiple log parsers use the same file, select the maximum size (including infinite)
            long maxTailMB = log.MaxTailMB;

            //Work out the last read position
            var info = new FileInfo(file);
            long offset;
            string hash = null;

            //Handle rolling single files
            if (log.SingleRollingFile)
            {
                //Read first line to compute hash
                var firstLineStream = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                try
                {
                    using (var reader = new StreamReader(firstLineStream))
                    {
                        firstLineStream = null;
                        if (reader.Peek() != -1)
                        {
                            var line = reader.ReadLine();
                            using (var md5 = MD5.Create())
                            {
                                hash = OffsetCursor<long>.GetMD5HashFileName(md5, line);
                            }
                        }
                    }
                }
                catch
                {
                }

                offset = cursor.GetLastRead(log.Name, file, hash);
            }
            else
            {
                offset = cursor.GetLastRead(log.Name, file);
            }

            long lastPosition = offset;

            //If file hasnt changed, don't bother opening
            if (info.Length <= offset)
            {
                return false;
            }

            //If the file is greater than our maxTailMB setting, skip to the maximum and proceed
            if (maxTailMB > 0)
            {
                long maxTailBytes = maxTailMB * 1048576;
                if (info.Length - offset > maxTailBytes)
                {
                    offset = info.Length - maxTailBytes;
                }
            }

            //Loop through the file doing matches
            var stream = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            try
            {
                using (var reader = new StreamReader(stream))
                {
                    stream = null;
                    reader.BaseStream.Seek(offset, SeekOrigin.Begin);
                    long lineCount = 0;

                    while (reader.Peek() != -1)
                    {
                        var line = reader.ReadLine();
                        lineCount++;

                        //Update the lastPosition counter before we try parse so any failures do not repeat the same line
                        lastPosition = reader.BaseStream.Position;
                        ParseLine(log, line, rawValues, boomerangValues, locationKey);

                        //Flush every 1000 lines to minimise memory footprint
                        if (lineCount >= 1000)
                        {
                            //send a debug metric
                            graphiteClient.SendQuickMetric("metrics.logLines.count", (int)lineCount);

                            //send real metrics to graphite
                            CollateAndSend(log, rawValues, file, lastPosition);
                            rawValues.Clear();
                            lineCount = 0;
                        }
                    }

                    //send a debug metric
                    graphiteClient.SendQuickMetric("metrics.logLines.count", (int)lineCount);
                }
            }
            finally
            {
                if (stream != null)
                {
                    stream.Dispose();
                }
            }

            graphiteClient.SendQuickMetric("metrics.logLines.count", rawValues.Count);
            CollateAndSend(log, rawValues, file, lastPosition, hash);

            return true;
        }
 public void Dispose()
 {
     _loggers?.Clear();
 }
Example #47
0
        private void RunUpdate()
        {
            var env = _scene.GetComponent<IEnvironment>();
            long lastRun = 0;
            _scene.GetComponent<ILogger>().Info("gameScene", "Starting update loop");
            long lastLog = 0;
            var metrics = new ConcurrentDictionary<int, uint>();
            _periodicUpdateTask = DefaultScheduler.Instance.SchedulePeriodic(TimeSpan.FromMilliseconds(interval), () =>
            {
                try
                {
                    var current = env.Clock;

                    if (_scene.RemotePeers.Any())
                    {
                        if (_ships.Any(s => s.Value.PositionUpdatedOn > lastRun))
                        {
                            _scene.Broadcast("position.update", s =>
                            {
                                //var nb = 0;
                                foreach (var ship in _ships.Values.ToArray())
                                {
                                    if (ship.PositionUpdatedOn > lastRun && ship.Status == ShipStatus.InGame)
                                    {
                                        using (var writer = new BinaryWriter(s, Encoding.UTF8, true))
                                        {
                                            writer.Write(ship.id);
                                            writer.Write(ship.x);
                                            writer.Write(ship.y);
                                            writer.Write(ship.rot);
                                            writer.Write(ship.PositionUpdatedOn);
                                        }
                                        //nb++;
                                    }
                                }

                                //metrics.AddOrUpdate(nb, 1, (i, old) => old + 1);
                            }, PacketPriority.MEDIUM_PRIORITY, PacketReliability.UNRELIABLE_SEQUENCED);

                            _scene.BrodcastUsedSkill(this.GetUsedSkills());
                        }
                        //else
                        //{
                        //    metrics.AddOrUpdate(0, 1, (i, old) => old + 1);
                        //}

                        lastRun = current;
                        if (current > lastLog + 1000 * 60)
                        {
                            lastLog = current;

                            _scene.GetComponent<ILogger>().Log(LogLevel.Info, "gameloop", "running", new
                            {
                                //sends = metrics.ToDictionary(kvp => kvp.Key, kvp => kvp.Value),
                                //received = ComputeMetrics()
                            });
                            metrics.Clear();
                        }
                        var execution = env.Clock - current;
                        if (execution > this._longestExecution)
                        {
                            this._longestExecution = execution;
                        }
                    }

                    RunGameplayLoop();
                }
                catch (Exception ex)
                {
                    _scene.GetComponent<ILogger>().Error("update.loop", "{0}", ex.Message);
                }
            });
        }
        //load an image file (JPG,PNG,etc) to quantize, convert 5bpp etc
        //The palette quantization here needs to be fixed... 9/4/2012
        public void loadNewImage(Image input)
        {
            WuColorQuantizer the_quantizerZ = new WuColorQuantizer();
            List<Color> yourColorList = new List<Color>();
            Bitmap gayness;

            Int32 parallelTaskCount = the_quantizerZ.AllowParallel ? 8 : 1;
            TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
            Int32 colorCount = 32;

            Image targetImageZ;
            targetImageZ = null;

            errorCache = new ConcurrentDictionary<Color, Int64>();

            if (input.Size != new Size(48, 56))
            {
                MessageBox.Show("Image needs to be 48x56 pixels!");
                return;
            }
            int pal_index = 0;
            int q = 0;
            int location_of_trans_color = 0;

            sourceImage = input; //copy the image, dont really need. TODO: Change

            //the_quantizer.Clear(); //clear the quantizer
            //GETQUANTIZEDIMAGE IS OLD HAT SHIT
            //this.Image = this.GetQuantizedImage(sourceImage);
            // quantization process
            errorCache.Clear();

             //  Task quantization = Task.Factory.StartNew(() =>
            targetImageZ = ImageBuffer.QuantizeImage(sourceImage, the_quantizerZ, colorCount, parallelTaskCount);//,
               //     TaskCreationOptions.LongRunning);
              // Task.Factory.StartNew
               // System.Diagnostics.Debug.WriteLine(TaskScheduler.Current.ToString());

            // finishes after running
             // / quantization.ContinueWith((i) =>
              // {
            //   System.Diagnostics.Debug.WriteLine(i.Status.ToString());
               this.Image = targetImageZ;

               gayness = new Bitmap(this.Image); // uber temporary hack thing to basically let us redraw the image using palette values

               //the_quantizerZ.GetPalette(31); <- this doesnt work for some reason.
               // \/ --- this hack may work instead?
               for (int z = 0; z < 32; z++)
               {
                   yourColorList.Add(System.Drawing.Color.FromArgb(255,the_quantizerZ.reds[z],the_quantizerZ.greens[z],the_quantizerZ.blues[z]));
               }

               //Puts the transparent color at index 0 (Reason? Anything at index 0 is transparent to SNES)
             //  optimized_palette[0] = System.Drawing.Color.FromArgb(255, 255, 0, 255);

               //Put the rest of the colors into the palette array
               /* This CANT be right....why is it loading the optimized palette from existing palette?
               for (Int32 index = 1; index < yourColorList.Count; index++)
               {
                   optimized_palette[index] = palette[index];
               }
               ///  DO \/ THIS \/ INSTEAD?
                */
               foreach (Color color in yourColorList)
               {
                   optimized_palette[pal_index] = color;
                   pal_index++;
               }

               //find where the transparent color is in the pallete
               for (int boobs = 0; boobs < 32; boobs++)
               {
                   if (optimized_palette[boobs].Equals(Color.FromArgb(255, 255, 0, 255)))
                   {
                       location_of_trans_color = boobs;
                       break;
                   }
               }

                //store the color at 0
               Color savedColor = optimized_palette[0];

                //Move the color to where trans color was
               optimized_palette[location_of_trans_color] = savedColor;
               optimized_palette[0] = Color.FromArgb(255, 255, 0, 255);

               /* DEBUG: PRINT THE COLOR PALETTE*/
                 foreach (Color color in optimized_palette )
               {
                   System.Diagnostics.Debug.WriteLine(color.ToString());
               }

               //converts the palette to a SNES palette
               foreach (Color color in optimized_palette)
               {
                   new_color_pal[q] = (byte)(RGBtoSNES(color));
                   new_color_pal[q + 1] = (byte)(RGBtoSNES(color) >> 8);
                   // Console.WriteLine("Snes: " + new_color_pal[q].ToString("X2") + new_color_pal[q + 1].ToString("X2"));
                   q = q + 2;
               }

               for (int y = 0; y < (8 * tile_height); y++)
               {
                   for (int x = 0; x < (8 * tile_width); x++)
                   {
                       new_back_array[x, y] = (byte)colorIndexLookup(gayness.GetPixel(x, y)); // uber temporary hack thing to basically let us redraw the image using palette values
                   }
               }

               //this.Image = gayness;
              redrawFlag = true;
              this.Invalidate();

              // }, uiScheduler);

             /*   Bitmap gayness = (Bitmap)this.Image; // uber temporary hack thing to basically let us redraw the image using palette values

            List<Color> yourColorList = the_quantizerZ.GetPalette(31); // Get a list of the optimized color palette...
            ///... and copy it into an array?
            ///

            optimized_palette[0] = System.Drawing.Color.FromArgb(255,255, 0, 255);

            for (Int32 index = 1; index < yourColorList.Count; index++)
            {
               optimized_palette[index] = palette[index];
            }

            foreach (Color color in yourColorList)
            {
                optimized_palette[pal_index] = color;
                pal_index++;
               }

            //converts the palette to a SNES palette
            foreach (Color color in optimized_palette)
            {
                new_color_pal[q] = (byte)(RGBtoSNES(color));
                new_color_pal[q + 1] = (byte)(RGBtoSNES(color) >> 8);
                // Console.WriteLine("Snes: " + new_color_pal[q].ToString("X2") + new_color_pal[q + 1].ToString("X2"));
                q = q + 2;
            }

            for (int y = 0; y < (8 * tile_height); y++)
            {
                for (int x = 0; x < (8 * tile_width); x++)
                {
                    new_back_array[x, y] = (byte)colorIndexLookup(gayness.GetPixel(x, y)); // uber temporary hack thing to basically let us redraw the image using palette values
                }
            }*/
        }
Example #49
0
 static TypeOverrideDescriptor()
 {
     Cache = new ConcurrentDictionary<Type, TypeOverrideDescriptor>();
     DxSettings.GlobalSettings.PropertyChanged += (sender, e) =>
     {
         if (e.PropertyName == "CacheTypeCheckers" && !DxSettings.GlobalSettings.CacheTypeCheckers)
             Cache.Clear();
     };
 }
Example #50
0
        static TwitchUtility()
        {
            if (Ditto.Twitch == null)
            {
                return;
            }

            Links        = new ConcurrentDictionary <int, Link>();
            IsMonitoring = false;

            Ditto.Connected += () =>
            {
                var _ = Task.Run(async() =>
                {
                    _cancellationTokenSource?.Cancel();
                    _cancellationTokenSource = new CancellationTokenSource();

                    await Ditto.Database.ReadAsync((uow) =>
                    {
                        Links = new ConcurrentDictionary <int, Link>(
                            uow.Links.GetAllWithLinks()
                            .Where(e => e.Type == LinkType.Twitch)
                            .Select(i => new KeyValuePair <int, Link>(i.Id, i))
                            );
                    });

                    try
                    {
                        if (Monitor == null)
                        {
                            Monitor = new LiveStreamMonitorService(Ditto.Twitch, 60);
                            Monitor.OnStreamOnline  += Monitor_OnStreamOnline;
                            Monitor.OnStreamOffline += Monitor_OnStreamOffline;
                            Monitor.OnStreamUpdate  += Monitor_OnStreamUpdate;

                            // Start monitoring the twitch links, this will notify users when a stream switches it's live status.
                            var channels = Links.ToList().Select(e => e.Value.Value.Split("|", StringSplitOptions.RemoveEmptyEntries).FirstOrDefault()).ToList();
                            MonitorChannels(channels);

                            // Instantly update the monitoring service on load.
                            if (Links.Count > 0)
                            {
                                await Monitor.UpdateLiveStreamersAsync(true).ConfigureAwait(false);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error($"Twitch | {ex}");
                    }
                });
                return(Task.CompletedTask);
            };

            Ditto.Exit += () =>
            {
                _cancellationTokenSource?.Cancel();
                Links?.Clear();
                return(Task.CompletedTask);
            };
        }
Example #51
0
 public static void Init()
 {
     ConcurrentDictionary<uint, ushort[]> dimensions = new ConcurrentDictionary<uint, ushort[]>();
     string[] dimensionData = System.IO.File.ReadAllLines("C:/db/mapdimensions.dat");
     foreach (string md in dimensionData)
     {
         string[] mdd = md.Split(' ');
         ushort Width = ushort.Parse(mdd[1]);
         ushort Height = ushort.Parse(mdd[2]);
         ushort[] dim = new ushort[2] { Width, Height };
         dimensions.TryAdd(uint.Parse(mdd[0]), dim);
     }
     Database.Database DB = new Database.Database("C:/db/maps.s3db");
     System.Data.DataTable DT = DB.GetDataTable("SELECT `UniqueID`, `Type` FROM `maptypes`");
     for (int i = 0; i < DT.Rows.Count; i++)
     {
         System.Data.DataRow dr = DT.Rows[i];
         Mapping.Map M = new Map();
         M.UniqueID = Convert.ToUInt32(dr.ItemArray[0]);
         M.Type = Convert.ToUInt32(dr.ItemArray[1]);
         if (!M.LoadDMap())
         {
             ushort[] dims;
             if (dimensions.TryGetValue(M.Type, out dims))
             {
                 M.Width = dims[0];
                 M.Height = dims[1];
             }
             else
             {
                 M.Width = 1300;
                 M.Height = 1300;
             }
             M.Coords = new byte[M.Height, M.Width];
             for (short ix = 0; ix < M.Height; ix++)
                 for (short iy = 0; iy < M.Width; iy++)
                     M.Coords[ix, iy] = (byte)Enums.MapPointType.Empty;
         }
         Kernel.Maps.TryAdd(M.UniqueID, M);
     }
     DB.Dispose();
     dimensions.Clear();
 }
Example #52
0
 public ActiveTrips(string id)
 {
     dict = new ConcurrentDictionary<string, Trip>();
     dict.Clear();
     var lastDbTripId = StorageManager.GetLastTripId();
     this.lastID = lastDbTripId;
 }
Example #53
0
        protected override void UpdateBlocksToNearbyPlayers(object state)
        {
            BlocksUpdateLock.EnterWriteLock();
            int num = Interlocked.Exchange(ref NumBlocksToUpdate, 0);
            ConcurrentDictionary<short, short> temp = BlocksToBeUpdated;
            BlocksToBeUpdated = BlocksUpdating;
            BlocksUpdateLock.ExitWriteLock();

            BlocksUpdating = temp;

            if (num == 1)
            {
                short keyCoords = BlocksUpdating.Keys.First();
                short index;
                BlocksUpdating.TryGetValue(keyCoords, out index);
                int blockX = (index >> 12 & 0xf);
                int blockY = (index & 0xff);
                int blockZ = (index >> 8 & 0xf);
                byte blockId = (byte)GetType(blockX, blockY, blockZ);
                byte data = GetData(blockX, blockY, blockZ);

                World.Server.SendPacketToNearbyPlayers(World, Coords, new BlockChangePacket
                {X = Coords.WorldX + blockX, Y = (sbyte) blockY, Z = Coords.WorldZ + blockZ, Data = data, Type = blockId});

            }
            else if (num < 20)
            {
                sbyte[] data = new sbyte[num];
                sbyte[] types = new sbyte[num];
                short[] blocks = new short[num];

                int count = 0;
                foreach (short key in BlocksUpdating.Keys)
                {
                    short index;
                    BlocksUpdating.TryGetValue(key, out index);
                    int blockX = (index >> 12 & 0xf);
                    int blockY = (index & 0xff);
                    int blockZ = (index >> 8 & 0xf);

                    data[count] = (sbyte)GetData(blockX, blockY, blockZ);
                    types[count] = (sbyte)GetType(blockX, blockY, blockZ);
                    blocks[count] = index;
                    ++count;
                }
                World.Server.SendPacketToNearbyPlayers(World, Coords, new MultiBlockChangePacket { CoordsArray = blocks, Metadata = data, Types = types, ChunkCoords = Coords });
            }
            else
            {
                World.Server.SendPacketToNearbyPlayers(World, Coords, new MapChunkPacket { Chunk = this });
            }

            BlocksUpdating.Clear();
            base.UpdateBlocksToNearbyPlayers(state);
        }
Example #54
0
        public bool RemoveFromMap(Item item, bool handleGameItem)
        {
            if (handleGameItem)
                RemoveSpecialItem(item);

            if (_room.GotSoccer())
                _room.GetSoccer().onGateRemove(item);

            bool isRemoved = false;
            foreach (Point coord in item.GetCoords.ToList())
            {
                if (RemoveCoordinatedItem(item, coord))
                    isRemoved = true;
            }

            ConcurrentDictionary<Point, List<Item>> items = new ConcurrentDictionary<Point, List<Item>>();
            foreach (Point Tile in item.GetCoords.ToList())
            {
                Point point = new Point(Tile.X, Tile.Y);
                if (mCoordinatedItems.ContainsKey(point))
                {
                    List<int> Ids = (List<int>)mCoordinatedItems[point];
                    List<Item> __items = GetItemsFromIds(Ids);

                    if (!items.ContainsKey(Tile))
                        items.TryAdd(Tile, __items);
                }

                SetDefaultValue(Tile.X, Tile.Y);
            }

            foreach (Point Coord in items.Keys.ToList())
            {
                if (!items.ContainsKey(Coord))
                    continue;

                List<Item> SubItems = (List<Item>)items[Coord];
                foreach (Item Item in SubItems.ToList())
                {
                    ConstructMapForItem(Item, Coord);
                }
            }

            items.Clear();
            items = null;

            return isRemoved;
        }