Inheritance: MonoBehaviour
Ejemplo n.º 1
0
        public async Task DeactivationTest_ClientConsumer(Guid streamGuid, string streamNamespace)
        {
            // get producer and consumer
            var producer = GrainClient.GrainFactory.GetGrain<ISampleStreaming_ProducerGrain>(Guid.NewGuid());

            var count = new Counter();
            // get stream and subscribe
            IStreamProvider streamProvider = GrainClient.GetStreamProvider(streamProviderName);
            var stream = streamProvider.GetStream<int>(streamGuid, streamNamespace);
            StreamSubscriptionHandle<int> subscriptionHandle = await stream.SubscribeAsync((e, t) => count.Increment());

            // produce one message (PubSubRendezvousGrain will have one consumer and one producer)
            await producer.BecomeProducer(streamGuid, streamNamespace, streamProviderName);
            await producer.Produce();

            Assert.AreEqual(count.Value, 1, "Client consumer grain has not received stream message");

            //TODO: trigger deactivation programmatically
            await Task.Delay(TimeSpan.FromMilliseconds(130000)); // wait for the PubSubRendezvousGrain and the SampleStreaming_ProducerGrain to be deactivated

            // deactivating PubSubRendezvousGrain and SampleStreaming_ProducerGrain during the same GC cycle causes a deadlock
            // resume producing after the PubSubRendezvousGrain and the SampleStreaming_ProducerGrain grains have been deactivated:
            await producer.BecomeProducer(streamGuid, streamNamespace, streamProviderName).WithTimeout(Timeout, "BecomeProducer is hung due to deactivation deadlock");
            await producer.Produce().WithTimeout(Timeout, "Produce is hung due to deactivation deadlock");

            Assert.AreEqual(count.Value, 2, "Client consumer grain did not receive stream messages after PubSubRendezvousGrain and SampleStreaming_ProducerGrain reactivation");
        }
		public void ForBreak ()
		{
			var counter = new Counter ();

			var c = Expression.Parameter (typeof (Counter), "c");
			var l = Expression.Parameter (typeof (int), "l");

			var i = Expression.Variable (typeof (int), "i");
			var for_break = Expression.Label ("for_break");

			var hitcounter = Expression.Lambda<Action<Counter, int>> (
				CustomExpression.For (
					i,
					Expression.Constant (0),
					Expression.LessThan (i, l),
					Expression.PreIncrementAssign (i),
					Expression.Block (
						Expression.Condition (
							Expression.LessThan (i, Expression.Constant (10)),
							Expression.Call (c, typeof (Counter).GetMethod ("Hit", Type.EmptyTypes)),
							Expression.Goto (for_break))),
					for_break),
				c, l).Compile ();

			hitcounter (counter, 100);

			Assert.AreEqual (10, counter.Count);
		}
 public FakeCounterFixture(int input, int output)
 {
     this.dio = new DIOCrossConnectFixture(input, output);
     m_allocated = true;
     source = new FakeCounterSource(dio.GetOutput());
     counter = new Counter(dio.GetInput());
 }
Ejemplo n.º 4
0
        public void SetUp(BenchmarkContext context)
        {
            _counter = context.GetCounter(CounterName);

            if (ConfigurationManager.AppSettings["TestKey"] != "42")
                throw new InvalidOperationException("TestKey from AppSettings could not be loaded!");
        }
        public async Task<StreamSubscriptionHandle<int>> BecomeConsumer(Guid streamId, string streamNamespace, string providerToUse)
        {
            logger.Info("BecomeConsumer");

            // new counter for this subscription
            var count = new Counter();

            // get stream
            IStreamProvider streamProvider = GetStreamProvider(providerToUse);
            var stream = streamProvider.GetStream<int>(streamId, streamNamespace);

            // subscribe
            StreamSubscriptionHandle<int> handle = await stream.SubscribeAsync(
                (e, t) =>
                {
                    logger.Info("Got next event {0}", e);
                    count.Increment();
                    return TaskDone.Done;
                });

            // track counter
            consumedMessageCounts.Add(handle, count);

            // return handle
            return handle;
        }
 public FakeCounterFixture(DIOCrossConnectFixture dio)
 {
     this.dio = dio;
     m_allocated = false;
     source = new FakeCounterSource(dio.GetOutput());
     counter = new Counter(dio.GetInput());
 }
Ejemplo n.º 7
0
        public override string Print(Counter counter)
        {
            if (_counter == counter)
                return _expected;

            throw new InvalidOperationException();
        }
Ejemplo n.º 8
0
        static void Main(string[] args)
        {
            try {
            var face = new Face("aleph.ndn.ucla.edu");

            var counter = new Counter();

            // Try to fetch anything.
            var name1 = new Name("/");
            Console.Out.WriteLine("Express name " + name1.toUri());
            face.expressInterest(name1, counter, counter);

            // Try to fetch using a known name.
            var name2 = new Name("/ndn/edu/ucla/remap/demo/ndn-js-test/hello.txt/%FDU%8D%9DM");
            Console.Out.WriteLine("Express name " + name2.toUri());
            face.expressInterest(name2, counter, counter);

            // Expect this to time out.
            var name3 = new Name("/test/timeout");
            Console.Out.WriteLine("Express name " + name3.toUri());
            face.expressInterest(name3, counter, counter);

            // The main event loop.
            while (counter.callbackCount_ < 3) {
              face.processEvents();
              // We need to sleep for a few milliseconds so we don't use 100% of the CPU.
              System.Threading.Thread.Sleep(5);
            }
              } catch (Exception e) {
            Console.Out.WriteLine("exception: " + e.Message);
              }
        }
    static void Main(string[] args)
    {
        Counter c = new Counter();
        c.ThresholdReached += c_ThresholdReached;

        // Provide remaining implementation for the class
    }
Ejemplo n.º 10
0
 private void CreateSut()
 {
     _counterMock = MockRepository.GenerateStrictMock<Counter>();
     _fizzPredicateMock = MockRepository.GenerateStrictMock<FizzPredicate>();
     _buzzPredicateMock = MockRepository.GenerateStrictMock<BuzzPredicate>();
     _sut = new FizzBuzzPrinter(_fizzPredicateMock, _buzzPredicateMock);
 }
Ejemplo n.º 11
0
 public AdvancedTimpexPrinter(TimPrinter timPrinter, PexPrinter pexPrinter, TimpexPrinter timpexPrinter, Counter counter)
 {
     _timPrinter = timPrinter;
     _pexPrinter = pexPrinter;
     _timpexPrinter = timpexPrinter;
     _counter = counter;
 }
Ejemplo n.º 12
0
 public FakeCounterFixture(DioCrossConnectFixture dio)
 {
     m_dio = dio;
     m_allocated = false;
     m_source = new FakeCounterSource(dio.GetOutput());
     m_counter = new Counter(dio.GetInput());
 }
 static void Main()
 {
     Counter c = new Counter();
     c.AddObserver(value => Console.WriteLine("ConsoleHandler = " + value));
     c.AddObserver(value => MessageBox.Show("Item = " + value) );
     c.DoIt(5, 7);
 }
Ejemplo n.º 14
0
 public void TestCounterInvalidEncodingType()
 {
     Assert.Throws<ArgumentOutOfRangeException>(() =>
     {
         Counter cnt = new Counter(EncodingType.K4X, null, null, false);
     });
 }
Ejemplo n.º 15
0
 public virtual string Print(Counter counter)
 {
     _counter = counter;
     if (TryPrintFizzBuzz() || TryPrintBuzz())
         return _returnValue;
     return PrintFizz();
 }
Ejemplo n.º 16
0
        public void should_hold_the_call_while_paused()
        {
            var counter = new Counter();
            var debounceFunction = new Debouncer(counter.Hit, TimeSpan.FromMilliseconds(50));

            debounceFunction.Pause();

            debounceFunction.Execute();
            debounceFunction.Execute();

            Thread.Sleep(100);

            counter.Count.Should().Be(0);

            debounceFunction.Execute();
            debounceFunction.Execute();

            Thread.Sleep(100);

            counter.Count.Should().Be(0);

            debounceFunction.Resume();

            Thread.Sleep(20);

            counter.Count.Should().Be(0);

            Thread.Sleep(100);

            counter.Count.Should().Be(1);
        }
 protected DbConnectionPoolCounters(string categoryName, string categoryHelp)
 {
     AppDomain.CurrentDomain.DomainUnload += new EventHandler(this.UnloadEventHandler);
     AppDomain.CurrentDomain.ProcessExit += new EventHandler(this.ExitEventHandler);
     AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(this.ExceptionEventHandler);
     string instanceName = null;
     if (!System.Data.Common.ADP.IsEmpty(categoryName) && System.Data.Common.ADP.IsPlatformNT5)
     {
         instanceName = this.GetInstanceName();
     }
     string str2 = categoryName;
     this.HardConnectsPerSecond = new Counter(str2, instanceName, CreationData.HardConnectsPerSecond.CounterName, CreationData.HardConnectsPerSecond.CounterType);
     this.HardDisconnectsPerSecond = new Counter(str2, instanceName, CreationData.HardDisconnectsPerSecond.CounterName, CreationData.HardDisconnectsPerSecond.CounterType);
     this.NumberOfNonPooledConnections = new Counter(str2, instanceName, CreationData.NumberOfNonPooledConnections.CounterName, CreationData.NumberOfNonPooledConnections.CounterType);
     this.NumberOfPooledConnections = new Counter(str2, instanceName, CreationData.NumberOfPooledConnections.CounterName, CreationData.NumberOfPooledConnections.CounterType);
     this.NumberOfActiveConnectionPoolGroups = new Counter(str2, instanceName, CreationData.NumberOfActiveConnectionPoolGroups.CounterName, CreationData.NumberOfActiveConnectionPoolGroups.CounterType);
     this.NumberOfInactiveConnectionPoolGroups = new Counter(str2, instanceName, CreationData.NumberOfInactiveConnectionPoolGroups.CounterName, CreationData.NumberOfInactiveConnectionPoolGroups.CounterType);
     this.NumberOfActiveConnectionPools = new Counter(str2, instanceName, CreationData.NumberOfActiveConnectionPools.CounterName, CreationData.NumberOfActiveConnectionPools.CounterType);
     this.NumberOfInactiveConnectionPools = new Counter(str2, instanceName, CreationData.NumberOfInactiveConnectionPools.CounterName, CreationData.NumberOfInactiveConnectionPools.CounterType);
     this.NumberOfStasisConnections = new Counter(str2, instanceName, CreationData.NumberOfStasisConnections.CounterName, CreationData.NumberOfStasisConnections.CounterType);
     this.NumberOfReclaimedConnections = new Counter(str2, instanceName, CreationData.NumberOfReclaimedConnections.CounterName, CreationData.NumberOfReclaimedConnections.CounterType);
     string str3 = null;
     if (!System.Data.Common.ADP.IsEmpty(categoryName))
     {
         TraceSwitch switch2 = new TraceSwitch("ConnectionPoolPerformanceCounterDetail", "level of detail to track with connection pool performance counters");
         if (TraceLevel.Verbose == switch2.Level)
         {
             str3 = categoryName;
         }
     }
     this.SoftConnectsPerSecond = new Counter(str3, instanceName, CreationData.SoftConnectsPerSecond.CounterName, CreationData.SoftConnectsPerSecond.CounterType);
     this.SoftDisconnectsPerSecond = new Counter(str3, instanceName, CreationData.SoftDisconnectsPerSecond.CounterName, CreationData.SoftDisconnectsPerSecond.CounterType);
     this.NumberOfActiveConnections = new Counter(str3, instanceName, CreationData.NumberOfActiveConnections.CounterName, CreationData.NumberOfActiveConnections.CounterType);
     this.NumberOfFreeConnections = new Counter(str3, instanceName, CreationData.NumberOfFreeConnections.CounterName, CreationData.NumberOfFreeConnections.CounterType);
 }
        public async Task<StreamSubscriptionHandle<int>> BecomeConsumer(Guid streamId, string streamNamespace, string providerToUse)
        {
            logger.Info("BecomeConsumer");

            // new counter for this subscription
            var count = new Counter();

            // get stream
            IStreamProvider streamProvider = GetStreamProvider(providerToUse);
            var stream = streamProvider.GetStream<int>(streamId, streamNamespace);

            // subscribe
            StreamSubscriptionHandle<int> handle = await stream.SubscribeAsync(
                (e, t) =>
                {
                    logger.Info("Got next event {0}", e);
                    string contextValue = RequestContext.Get(SampleStreaming_ProducerGrain.RequestContextKey) as string;
                    if (!String.Equals(contextValue, SampleStreaming_ProducerGrain.RequestContextValue))
                    {
                        throw new Exception(String.Format("Got the wrong RequestContext value {0}.", contextValue));
                    }
                    count.Increment();
                    return TaskDone.Done;
                });

            // track counter
            consumedMessageCounts.Add(handle, count);

            // return handle
            return handle;
        }
Ejemplo n.º 19
0
        static void Main(string[] args)
        {
            int pairs = args.Count() == 0 ? 16 : Int32.Parse(args[0]);
            int msgs = args.Count() == 2 ? Int32.Parse(args[1]) : 10;
            int sleepForMax = 20;

            var counters = new Counter[pairs];

            InitCounters(pairs, counters, msgs);

            int sleepFor = sleepForMax;
            while (sleepFor > 0)
            {
                Console.WriteLine("Sleeping for "+sleepFor+" seconds whilst it warms up");
                Thread.Sleep(1000);
                sleepFor--;
            }

            Console.WriteLine("Warm up sent "+ SumCounters(pairs,counters) + " messages. Running for real now...");
            ResetCounters(pairs, counters);

            Thread.Sleep(1000 * sleepForMax);

            shutdownAll();

            var sum = SumCounters(pairs, counters);

            Console.WriteLine("" + sum + " messages sent in "+ sleepForMax + " seconds.");

            decimal sps = ((decimal)sum) / ((decimal)sleepForMax);

            Console.WriteLine("That's " + sps + " messages per second");

            Console.ReadKey();
        }
Ejemplo n.º 20
0
 public Counter Add(string name, string notes, out int counterId)
 {
     var counter = new Counter(name, notes);
     counterId = _counters.Count;
     _counters.Add(counter);
     return counter;
 }
Ejemplo n.º 21
0
        public static AreaType ReadAreaType(XmlReader reader, Counter<string> badTags)
        {
            string type = null;
            int level = 0;
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element && reader.Name == "type")
                {
                    type = reader.ReadElementContentAsString();
                }
                else if (reader.NodeType == XmlNodeType.Element && reader.Name == "level")
                {
                    level = reader.ReadElementContentAsInt();
                }
                else if (reader.NodeType == XmlNodeType.Element)
                {
                    badTags.Increment(reader.Name);
                }
                else if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "area")
                {
                    break;
                }
            }

            if (level == 0 || type == null)
                throw new Exception("Area type or level not specified.");
            return new AreaType(level, type);
        }
Ejemplo n.º 22
0
 public void TestCounterInit1()
 {
     using (Counter ctr = new Counter())
     {
         TestInit(0, 0, 0, false, false, false, false);
     }
 }
Ejemplo n.º 23
0
 private Counter CreateCounter()
 {
     Counter counter = new Counter();
     counter.Id = 1;
     counter.Name = "Foo";
     return counter;
 }
Ejemplo n.º 24
0
	// this function MUST exist
	private static void Setup(Counter obj)
	{
	    AddMethod(obj.Bang);
        AddMethod(0,"reset",obj.Reset);
        AddMethod(0,"set",obj.Set);
        AddMethod(0,"bound",obj.Bound);
	}
 protected override void SetupClient()
 {
     this.sendArgsPool = PrimitiveObjectPool.Create(100, CreateSendAsyncEventArgs);
     this.sentBytesCount = new Counter(MessageSize * MessageCount);
     this.clientSocket = new Socket(EndPoint.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
     this.clientSocket.Connect(EndPoint);
 }
Ejemplo n.º 26
0
        private static void Main(string[] args)
        {
            Console.WriteLine("Incorrect counter");

            var c = new Counter();

            var t1 = new Thread(() => TestCounter(c));
            var t2 = new Thread(() => TestCounter(c));
            var t3 = new Thread(() => TestCounter(c));
            t1.Start();
            t2.Start();
            t3.Start();
            t1.Join();
            t2.Join();
            t3.Join();

            Console.WriteLine("Total count: {0}", c.Count);
            Console.WriteLine("--------------------------");

            Console.WriteLine("Correct counter");

            var c1 = new CounterNoLock();

            t1 = new Thread(() => TestCounter(c1));
            t2 = new Thread(() => TestCounter(c1));
            t3 = new Thread(() => TestCounter(c1));
            t1.Start();
            t2.Start();
            t3.Start();
            t1.Join();
            t2.Join();
            t3.Join();

            Console.WriteLine("Total count: {0}", c1.Count);
        }
Ejemplo n.º 27
0
 public FakeCounterFixture(int input, int output)
 {
     m_dio = new DioCrossConnectFixture(input, output);
     m_allocated = true;
     m_source = new FakeCounterSource(m_dio.GetOutput());
     m_counter = new Counter(m_dio.GetInput());
 }
Ejemplo n.º 28
0
        public void should_call_initializer_methods_in_right_order()
        {
            var counter = new Counter();
            var bus = new TestBus();
            bus.Starting += () => counter.Increment();
            bus.Started += () => counter.Increment();
            bus.Stopping += () => counter.Increment();
            bus.Stopped += () => counter.Increment();
            var testHostInitializer = new TestHostInitializer(counter);
            var host = new Host();
            var container = host.ContainerFactory.Invoke();
            host.ContainerFactory = () =>
            {
                container.Configure(x =>
                {
                    x.ForSingletonOf<IBus>().Use(bus);
                    x.ForSingletonOf<HostInitializer>().Add(testHostInitializer);
                });
                return container;
            };

            host.Start();
            host.Stop();

            testHostInitializer.CapturedContainer.ShouldEqual(container);
            testHostInitializer.ConfigureContainerCounterValue.ShouldEqual(0);
            testHostInitializer.BeforeStartCounterValue.ShouldEqual(0);
            testHostInitializer.AfterStartCounterValue.ShouldEqual(2);
            testHostInitializer.BeforeStopCounterValue.ShouldEqual(2);
            testHostInitializer.AfterStopCounterValue.ShouldEqual(4);
        }
        public MultiContextInstanceMetrics(string instanceName)
        {
            var context = Metric.Context(instanceName);

            this.instanceCounter = context.Counter("Sample Counter", Unit.Errors);
            this.instanceTimer = context.Timer("Sample Timer", Unit.Requests);
        }
        public async Task<StreamSubscriptionHandle<int>> BecomeConsumer(Guid streamId, string streamNamespace, string providerToUse)
        {
            logger.Info("BecomeConsumer");

            // new counter for this subscription
            var count = new Counter();
            var error = new Counter();

            // get stream
            IStreamProvider streamProvider = GetStreamProvider(providerToUse);
            var stream = streamProvider.GetStream<int>(streamId, streamNamespace);

            int countCapture = consumerCount;
            consumerCount++;
            // subscribe
            StreamSubscriptionHandle<int> handle = await stream.SubscribeAsync(
                (e, t) => OnNext(e, t, countCapture, count),
                e => OnError(e, countCapture, error));

            // track counter
            consumedMessageCounts.Add(handle, Tuple.Create(count,error));

            // return handle
            return handle;
        }
Ejemplo n.º 31
0
 public void RegisterMetrics(ICollectorRegistry registry)
 {
     _collectionCount = Metrics.WithCustomRegistry(registry)
                        .CreateCounter("ondemand_counter_example", "This counter is incremented before every data collection.");
 }
Ejemplo n.º 32
0
 public void AddCustomerToChannelsUnassignedUnread(string business_id, string channel_id, Counter entity)
 {
     //var rs = _connectionFactory.GetConnection.Child(business_id).Child(CUSTOMERS_UNREAD).Child(CUSTOMERS_UNREAD + "-data").Child(COUNTERS).Child(COUNTERS_CHANNELS_UNASSIGNED_UNREAD).Child(channel_id).Child(entity.id).PutAsync(entity).ContinueWith((t) =>
     //{
     //    var count = _connectionFactory.GetConnection.Child(business_id).Child(CUSTOMERS_UNREAD).Child(CUSTOMERS_UNREAD + "-data").Child(COUNTERS).Child(COUNTERS_CHANNELS_UNASSIGNED_UNREAD).Child(channel_id).OnceAsync<Counter>().Result;
     //    var rs1 = _connectionFactory.GetConnection.Child(business_id).Child(CUSTOMERS_UNREAD).Child(CUSTOMERS_UNREAD + "-count").Child(COUNTERS).Child(COUNTERS_CHANNELS_UNASSIGNED_UNREAD).Child(channel_id).PutAsync(count == null ? 0: count.Count());
     //});
     var count = _connectionFactory.GetConnection.Child(business_id).Child(CUSTOMERS_UNREAD).Child(CUSTOMERS_UNREAD + "-count").Child(COUNTERS).Child(COUNTERS_CHANNELS_UNASSIGNED_UNREAD).Child(channel_id).OnceSingleAsync <int>().Result;
     var rs1   = _connectionFactory.GetConnection.Child(business_id).Child(CUSTOMERS_UNREAD).Child(CUSTOMERS_UNREAD + "-count").Child(COUNTERS).Child(COUNTERS_CHANNELS_UNASSIGNED_UNREAD).Child(channel_id).PutAsync(count + entity.count);
 }
Ejemplo n.º 33
0
 public void Update(string business_id, Counter entity)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 34
0
 public void Upsert(string business_id, Counter entity)
 {
     var rs = _connectionFactory.GetConnection.Child(business_id).Child(COUNTERS).Child(entity.id).PutAsync(entity);
 }
Ejemplo n.º 35
0
 public void Update(Counter entity)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 36
0
 internal Logger(LoggingPhaseTracker outerInstance, PhaseTracker_Phase phase) : base(outerInstance, phase)
 {
     this._outerInstance = outerInstance;
     PeriodCounter       = new Counter(outerInstance, phase);
     PeriodCounter.reset();
 }
 public BenchmarkActorRef(Counter counter, IRemoteActorRefProvider provider)
 {
     _counter = counter;
     Provider = provider;
     Path     = new RootActorPath(provider.DefaultAddress) / "user" / "tempRef";
 }
Ejemplo n.º 38
0
        public void TestGetCurrent()
        {
            var counter = new Counter();

            Assert.AreEqual(0, counter.GetCurrent);
        }
Ejemplo n.º 39
0
        /// <inheritdoc />
        protected override async Task <PutResult> PutStreamCoreAsync(OperationContext context, HashType hashType, Stream stream, UrgencyHint urgencyHint, Counter retryCounter)
        {
            if (!hashType.IsValidDedup())
            {
                return(new PutResult(
                           new ContentHash(hashType),
                           $"DedupStore client requires a HashType that supports dedup. Given hash type: {hashType}"));
            }

            try
            {
                var tempFile = TempDirectory.CreateRandomFileName().Path;
                using (Stream writer = new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.None, 4096, FileOptions.Asynchronous | FileOptions.SequentialScan))
                {
                    await stream.CopyToAsync(writer);
                }

                // Cast is necessary because ContentSessionBase implements IContentSession explicitly
                return(await(this as IContentSession).PutFileAsync(context, hashType, new AbsolutePath(tempFile), FileRealizationMode.None, context.Token, urgencyHint));
            }
            catch (Exception e)
            {
                return(new PutResult(e, new ContentHash(hashType)));
            }
        }
Ejemplo n.º 40
0
        private async Task <Transaction> NextWithNoTransaction(Counter counter,
                                                               TransControl transControl)
        {
            // Find the special transaction pool, if not found, get the counterpart
            var curTransPool = await _context.TransPools
                               .FirstOrDefaultAsync(x => x.TransControlId == transControl.TransControlId &&
                                                    x.TransactionDate.Date == DateTime.Now.Date &&
                                                    x.IsSpecial == !transControl.IsSpecial) ?? await _context.TransPools
                               .FirstOrDefaultAsync(x => x.TransControlId == transControl.TransControlId &&
                                                    x.TransactionDate.Date == DateTime.Now.Date &&
                                                    x.IsSpecial == transControl.IsSpecial);

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

            // Remove the newTrans from the main chain
            var newTrans = await _context.Transactions
                           .FirstOrDefaultAsync(x => x.TransPoolId == curTransPool.TransPoolId &&
                                                x.PrevId == null &&
                                                !x.IsServed);

            // Add the newTrans to the counter's chain
            // If the next transaction is not found, try getting a transaction from the next pool
            if (newTrans == null)
            {
                var pool = await _context.TransPools
                           .FirstOrDefaultAsync(x => x.TransControlId == transControl.TransControlId &&
                                                x.TransactionDate.Date == DateTime.Now.Date &&
                                                x.IsSpecial == !curTransPool.IsSpecial);

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

                newTrans = await _context.Transactions
                           .FirstOrDefaultAsync(x => x.TransPoolId == pool.TransPoolId &&
                                                !x.IsServed &&
                                                x.PrevId == null);

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

                curTransPool = pool;
            }

            var newNextTrans = await _context.Transactions
                               .FirstOrDefaultAsync(x => x.TransactionId == newTrans.NextId);

            // Remove the new trans from the main chain
            if (newNextTrans != null)
            {
                _context.Entry(newTrans).Property(x => x.RowVersion2).OriginalValue =
                    newTrans.RowVersion2;
                _context.Entry(newNextTrans).Property(x => x.RowVersion2).OriginalValue =
                    newNextTrans.RowVersion2;

                newTrans.NextId     = null;
                newNextTrans.PrevId = null;

                _context.Transactions.Update(newNextTrans);
            }

            newTrans.IsServed = true;

            counter.TransactionId  = newTrans.TransactionId;
            transControl.IsSpecial = curTransPool.IsSpecial;

            _context.TransControls.Update(transControl);
            _context.Counters.Update(counter);
            _context.Transactions.Update(newTrans);

            return(newTrans);
        }
Ejemplo n.º 41
0
        private async Task <Transaction> NextWithExistingTransaction(Counter counter,
                                                                     Transaction curtrans, TransControl transControl)
        {
            // If there's already an existing next transaction
            if (curtrans.NextTrans != null)
            {
                counter.TransactionId = curtrans.NextId;

                _context.Counters.Update(counter);
                await _context.SaveChangesAsync();

                return(curtrans.NextTrans);
            }

            // find the next pool, use the current pool if the next pool is not found
            var nextPool = await _context.TransPools
                           .FirstOrDefaultAsync(x => x.TransControlId == transControl.TransControlId &&
                                                x.TransactionDate.Date == DateTime.Now.Date &&
                                                x.IsSpecial == !transControl.IsSpecial.Value) ??
                           await _context.TransPools
                           .FirstOrDefaultAsync(x => x.TransControlId == transControl.TransControlId &&
                                                x.TransactionDate.Date == DateTime.Now.Date &&
                                                x.IsSpecial == transControl.IsSpecial.Value);


            var newTrans = await _context.Transactions
                           .FirstOrDefaultAsync(x => x.TransPoolId == nextPool.TransPoolId &&
                                                !x.IsServed &&
                                                x.PrevId == null); // Find the transaction at the tail of the main chain

            // Use the current pool instead to get the new transaction
            if (newTrans == null)
            {
                var pool = await _context.TransPools
                           .FirstOrDefaultAsync(x => x.TransControlId == transControl.TransControlId &&
                                                x.TransactionDate.Date == DateTime.Now.Date &&
                                                x.IsSpecial == transControl.IsSpecial.Value);

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

                newTrans = await _context.Transactions
                           .FirstOrDefaultAsync(x => x.TransPoolId == pool.TransPoolId &&
                                                !x.IsServed &&
                                                x.PrevId == null);  // Find the transaction at the tail of the main chain

                nextPool = pool;
            }

            if (newTrans == null) // return null if there's really no transaction
            {
                return(null);
            }

            var newNextTrans = await _context.Transactions
                               .FirstOrDefaultAsync(x => x.TransactionId == newTrans.NextId);

            // The next transaction's next one will be the new tail of the main tail
            if (newNextTrans != null)
            {
                _context.Entry(newTrans).Property(x => x.RowVersion2).OriginalValue =
                    newTrans.RowVersion2;
                _context.Entry(newNextTrans).Property(x => x.RowVersion2).OriginalValue =
                    newNextTrans.RowVersion2;

                newNextTrans.PrevId = null;
                newTrans.NextId     = null;

                _context.Transactions.Update(
                    newNextTrans);
            }

            newTrans.IsServed = true;

            // Link the new trans to the new chain belonging to a window
            curtrans.NextId = newTrans.TransactionId;
            newTrans.PrevId = curtrans.TransactionId;

            counter.TransactionId  = newTrans.TransactionId;
            transControl.IsSpecial = nextPool.IsSpecial;

            _context.TransControls.Update(transControl);
            _context.Counters.Update(counter);
            _context.Transactions.Update(newTrans);
            _context.Transactions.Update(curtrans);

            return(newTrans);
        }
Ejemplo n.º 42
0
 /// <summary>
 /// Returns the guaranteed parsable stable string representation of GDID in the form 'Era:Authority:Counter'
 /// </summary>
 public override string ToString()
 {
     // WARNING!!! returned string representation must be parsable in the original form 'Era:Authority:Counter' and must not change
     return(Era.ToString(INVARIANT) + ":" + SAUTHORITIES[Authority] + ":" + Counter.ToString(INVARIANT));
 }
Ejemplo n.º 43
0
 public ByteTrackingAllocator(Counter bytesUsed)
     : this(Int32BlockPool.INT32_BLOCK_SIZE, bytesUsed)
 {
 }
Ejemplo n.º 44
0
 public ByteTrackingAllocator(int blockSize, Counter bytesUsed)
     : base(blockSize)
 {
     this.bytesUsed = bytesUsed;
 }
Ejemplo n.º 45
0
        /// <summary>重载执行,支持集群</summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="func"></param>
        /// <param name="write">是否写入操作</param>
        /// <returns></returns>
        public override T Execute <T>(String key, Func <RedisClient, T> func, Boolean write = false)
        {
            var node = Cluster?.SelectNode(key);

            // 如果不支持集群,直接返回
            if (node == null)
            {
                return(base.Execute(key, func, write));
            }

            // 统计性能
            var sw = Counter?.StartCount();

            var i = 0;

            do
            {
                var pool = node.Pool;

                // 每次重试都需要重新从池里借出连接
                var client = pool.Get();
                try
                {
                    client.Reset();
                    var rs = func(client);

                    Counter?.StopCount(sw);

                    return(rs);
                }
                catch (InvalidDataException)
                {
                    if (i++ >= Retry)
                    {
                        throw;
                    }
                }
                catch (Exception ex)
                {
                    // 处理MOVED和ASK指令
                    var msg = ex.Message;
                    if (msg.StartsWithIgnoreCase("MOVED", "ASK"))
                    {
                        // 取出地址,找到新的节点
                        var endpoint = msg.Substring(" ");
                        if (!endpoint.IsNullOrEmpty())
                        {
                            // 使用新的节点
                            node = Cluster.Map(endpoint, key);
                            if (node != null)
                            {
                                continue;
                            }
                        }
                    }

                    throw;
                }
                finally
                {
                    pool.Put(client);
                }
            } while (true);
        }
Ejemplo n.º 46
0
        private void GenerateCounter(StringBuilder counterBuilder, Counter counter)
        {
            // encrypt
            if (counterBuilder.Length > 0)
            {
                counterBuilder.Append(",");
            }
            if (SecurityCounter.GetAppCounter(topClient.appKey).GetEncryptPhoneNum() != 0)
            {
                counterBuilder.Append(counter.GetEncryptPhoneNum());
            }
            else
            {
                counterBuilder.Append("0");
            }
            counterBuilder.Append(",");
            if (counter.GetEncryptNickNum() != 0)
            {
                counterBuilder.Append(counter.GetEncryptNickNum());
            }
            else
            {
                counterBuilder.Append("0");
            }
            counterBuilder.Append(",");
            if (counter.GetEncryptReceiverNameNum() != 0)
            {
                counterBuilder.Append(counter.GetEncryptReceiverNameNum());
            }
            else
            {
                counterBuilder.Append("0");
            }
            counterBuilder.Append(",");
            if (counter.GetEncryptSimpleNum() != 0)
            {
                counterBuilder.Append(counter.GetEncryptSimpleNum());
            }
            else
            {
                counterBuilder.Append("0");
            }
            counterBuilder.Append(",");
            if (counter.GetEncryptSearchNum() != 0)
            {
                counterBuilder.Append(counter.GetEncryptSearchNum());
            }
            else
            {
                counterBuilder.Append("0");
            }

            // decrypt
            counterBuilder.Append(",");
            if (counter.GetDecryptPhoneNum() != 0)
            {
                counterBuilder.Append(counter.GetDecryptPhoneNum());
            }
            else
            {
                counterBuilder.Append("0");
            }
            counterBuilder.Append(",");
            if (counter.GetDecryptNickNum() != 0)
            {
                counterBuilder.Append(counter.GetDecryptNickNum());
            }
            else
            {
                counterBuilder.Append("0");
            }
            counterBuilder.Append(",");
            if (counter.GetDecryptReceiverNameNum() != 0)
            {
                counterBuilder.Append(counter.GetDecryptReceiverNameNum());
            }
            else
            {
                counterBuilder.Append("0");
            }
            counterBuilder.Append(",");
            if (counter.GetDecryptSimpleNum() != 0)
            {
                counterBuilder.Append(counter.GetDecryptSimpleNum());
            }
            else
            {
                counterBuilder.Append("0");
            }
            counterBuilder.Append(",");
            if (counter.GetDecryptSearchNum() != 0)
            {
                counterBuilder.Append(counter.GetDecryptSearchNum());
            }
            else
            {
                counterBuilder.Append("0");
            }

            // search
            counterBuilder.Append(",");
            if (counter.GetSearchPhoneNum() != 0)
            {
                counterBuilder.Append(counter.GetSearchPhoneNum());
            }
            else
            {
                counterBuilder.Append("0");
            }
            counterBuilder.Append(",");
            if (counter.GetSearchNickNum() != 0)
            {
                counterBuilder.Append(counter.GetSearchNickNum());
            }
            else
            {
                counterBuilder.Append("0");
            }
            counterBuilder.Append(",");
            if (counter.GetSearchReceiverNameNum() != 0)
            {
                counterBuilder.Append(counter.GetSearchReceiverNameNum());
            }
            else
            {
                counterBuilder.Append("0");
            }
            counterBuilder.Append(",");
            if (counter.GetSearchSimpleNum() != 0)
            {
                counterBuilder.Append(counter.GetSearchSimpleNum());
            }
            else
            {
                counterBuilder.Append("0");
            }
            counterBuilder.Append(",");
            if (counter.GetSearchSearchNum() != 0)
            {
                counterBuilder.Append(counter.GetSearchSearchNum());
            }
            else
            {
                counterBuilder.Append("0");
            }
        }
Ejemplo n.º 47
0
 /// <inheritdoc />
 protected override Task <PutResult> PutStreamCoreAsync(OperationContext operationContext, HashType hashType, Stream stream, UrgencyHint urgencyHint, Counter retryCounter)
 => Task.FromResult(new PutResult(new BoolResult(ErrorMessage)));
Ejemplo n.º 48
0
 public bool CanShoot()
 {
     return(Counter.instance().BulletCount() > 0 && !gameIsPaused);
 }
Ejemplo n.º 49
0
 /// <inheritdoc />
 protected override Task <IEnumerable <Task <Indexed <PlaceFileResult> > > > PlaceFileCoreAsync(OperationContext operationContext, IReadOnlyList <ContentHashWithPath> hashesWithPaths, FileAccessMode accessMode, FileReplacementMode replacementMode, FileRealizationMode realizationMode, UrgencyHint urgencyHint, Counter retryCounter)
 => Task.FromResult(hashesWithPaths.Select((hash, i) => Task.FromResult(new PlaceFileResult(PlaceFileResult.ResultCode.NotPlacedContentNotFound).WithIndex(i))));
Ejemplo n.º 50
0
 /// <inheritdoc />
 protected override Task <PutResult> PutFileCoreAsync(OperationContext operationContext, ContentHash contentHash, AbsolutePath path, FileRealizationMode realizationMode, UrgencyHint urgencyHint, Counter retryCounter)
 => Task.FromResult(new PutResult(contentHash, ErrorMessage));
Ejemplo n.º 51
0
 /// <inheritdoc />
 protected override Task <IEnumerable <Task <Indexed <PinResult> > > > PinCoreAsync(OperationContext operationContext, IReadOnlyList <ContentHash> contentHashes, UrgencyHint urgencyHint, Counter retryCounter, Counter fileCounter)
 => Task.FromResult(contentHashes.Select((hash, i) => Task.FromResult(PinResult.ContentNotFound.WithIndex(i))));
Ejemplo n.º 52
0
 /// <inheritdoc />
 protected override Task <PlaceFileResult> PlaceFileCoreAsync(OperationContext operationContext, ContentHash contentHash, AbsolutePath path, FileAccessMode accessMode, FileReplacementMode replacementMode, FileRealizationMode realizationMode, UrgencyHint urgencyHint, Counter retryCounter)
 => Task.FromResult(new PlaceFileResult(PlaceFileResult.ResultCode.NotPlacedContentNotFound));
Ejemplo n.º 53
0
 /// <inheritdoc />
 protected override Task <OpenStreamResult> OpenStreamCoreAsync(OperationContext operationContext, ContentHash contentHash, UrgencyHint urgencyHint, Counter retryCounter)
 => Task.FromResult(new OpenStreamResult(null));     // Null stream signals failue.
Ejemplo n.º 54
0
        => Task.FromResult(new OpenStreamResult(null));     // Null stream signals failue.

        /// <inheritdoc />
        protected override Task <PinResult> PinCoreAsync(OperationContext operationContext, ContentHash contentHash, UrgencyHint urgencyHint, Counter retryCounter)
        => Task.FromResult(PinResult.ContentNotFound);
Ejemplo n.º 55
0
        public void TestGetUniqueNo()
        {
            var counter = new Counter();

            Assert.AreEqual(1, counter.GetUniqueNo());
        }
        public override void CreateBody()
        {
            // создание стилей ячеек
            XmlStyle textStyle = new XmlStyle();

            textStyle.Alignment = new AlignmentOptions()
            {
                Horizontal = HorizontalAlignment.Left, Vertical = VerticalAlignment.Center, WrapText = true
            };
            textStyle.Border.LineStyle = Borderline.Continuous;
            textStyle.Border.Sides     = BorderSides.All;
            textStyle.Border.Weight    = 1;
            textStyle.Font.Size        = 12;
            textStyle.Font.Name        = "Calibri";

            XmlStyle numbersStyle = new XmlStyle(textStyle);

            numbersStyle.Alignment = new AlignmentOptions()
            {
                Horizontal = HorizontalAlignment.Center, Vertical = VerticalAlignment.Center, WrapText = true
            };
            numbersStyle.Font.Name = "Century Gothic";

            XmlStyle valuesStyle = new XmlStyle(numbersStyle);

            valuesStyle.Alignment = new AlignmentOptions()
            {
                Horizontal = HorizontalAlignment.Right, Vertical = VerticalAlignment.Center, WrapText = false
            };
            valuesStyle.DisplayFormat      = DisplayFormatType.Custom;
            valuesStyle.CustomFormatString = "# ##0";

            int rowCount = 0;

            foreach (var item in this.collectors)
            {
                rowCount += item.CountersCount;
            }

            const int startRow = 7;
            int       rowIndex = startRow;

            int collectorIndex = 0;

            foreach (Collector collector in this.collectors)
            {
                int columnIndex = 1;

                int collectorRowSpan = collector.Objects.Sum(o => o.Counters.Sum(c => c.TarifsCount == 1 ? 1 : 3));

                CreateRange(rowIndex, columnIndex++, collectorRowSpan, 1, collectorIndex + 1, numbersStyle);
                CreateRange(rowIndex, columnIndex++, collectorRowSpan, 1, collector.IsAnswered == true ? "OK" : "не отвечает", textStyle);
                CreateRange(rowIndex, columnIndex++, collectorRowSpan, 1, collector.IsUSPD == true ? "УСПД" : string.Empty, textStyle);
                CreateRange(rowIndex, columnIndex++, collectorRowSpan, 1, collector.NetworkAddress, numbersStyle);
                CreateRange(rowIndex, columnIndex++, collectorRowSpan, 1, collector.PhoneNumber, numbersStyle);

                int oldObjectColumnIndex = columnIndex;
                for (int objectIndex = 0; objectIndex < collector.Objects.Count; objectIndex++)
                {
                    AccountingObject aobject = collector.Objects[objectIndex];
                    int countersCount        = aobject.CountersCount;
                    int objectRowSpan        = aobject.Counters.Sum(c => c.TarifsCount == 1 ? 1 : 3);

                    columnIndex = oldObjectColumnIndex;
                    CreateRange(rowIndex, columnIndex++, objectRowSpan, 1, aobject.City, textStyle);
                    CreateRange(rowIndex, columnIndex++, objectRowSpan, 1, aobject.Contract, textStyle);
                    CreateRange(rowIndex, columnIndex++, objectRowSpan, 1, aobject.Subscriber, textStyle);
                    CreateRange(rowIndex, columnIndex++, objectRowSpan, 1, aobject.Name, textStyle);
                    CreateRange(rowIndex, columnIndex++, objectRowSpan, 1, aobject.Tp, textStyle);

                    bool isCounterMultiTariff = false;

                    int oldCounterColumnIndex = columnIndex;
                    for (int counterIndex = 0; counterIndex < countersCount; counterIndex++)
                    {
                        Counter counter = aobject.Counters[counterIndex];

                        isCounterMultiTariff = aobject.Counters[counterIndex].TarifsCount != 1;
                        int counterRowSpan = isCounterMultiTariff ? 3 : 1;

                        columnIndex = oldCounterColumnIndex;
                        CreateRange(rowIndex + counterIndex, columnIndex++, counterRowSpan, 1, counter.IsAnswered == true ? "OK" : "не отвечает", textStyle);
                        CreateRange(rowIndex + counterIndex, columnIndex++, counterRowSpan, 1, counter.AccountingPoint, textStyle);
                        CreateRange(rowIndex + counterIndex, columnIndex++, counterRowSpan, 1, counter.CounterType, textStyle);
                        CreateRange(rowIndex + counterIndex, columnIndex++, counterRowSpan, 1, counter.CounterNetworkAdress, numbersStyle);
                        CreateRange(rowIndex + counterIndex, columnIndex++, counterRowSpan, 1, counter.SerialNumber, numbersStyle);

                        // тариф
                        if (isCounterMultiTariff)
                        // счётчик многотарифный
                        {
                            // TƩ
                            CreateRange(rowIndex + counterIndex, columnIndex++, 1, 1, "TƩ", textStyle);
                            CreateRange(rowIndex + counterIndex, columnIndex++, 1, 1, GetIndication(counter.PreviousIndications.Tarriff0), valuesStyle);
                            CreateRange(rowIndex + counterIndex, columnIndex++, 1, 1, GetIndication(counter.NextIndications.Tarriff0), valuesStyle);
                            CreateRange(rowIndex + counterIndex, columnIndex++, 1, 1, GetIndication(counter.Difference), valuesStyle);
                            rowIndex++;
                            // T1
                            columnIndex = oldCounterColumnIndex + 5;
                            CreateRange(rowIndex + counterIndex, columnIndex++, 1, 1, "T1", textStyle);
                            CreateRange(rowIndex + counterIndex, columnIndex++, 1, 1, GetIndication(counter.PreviousIndications.Tarriff1), valuesStyle);
                            CreateRange(rowIndex + counterIndex, columnIndex++, 1, 1, GetIndication(counter.NextIndications.Tarriff1), valuesStyle);
                            CreateRange(rowIndex + counterIndex, columnIndex++, 1, 1, GetIndication(counter.DifferenceT1), valuesStyle);
                            rowIndex++;
                            // T2
                            columnIndex = oldCounterColumnIndex + 5;
                            CreateRange(rowIndex + counterIndex, columnIndex++, 1, 1, "T2", textStyle);
                            CreateRange(rowIndex + counterIndex, columnIndex++, 1, 1, GetIndication(counter.PreviousIndications.Tarriff2), valuesStyle);
                            CreateRange(rowIndex + counterIndex, columnIndex++, 1, 1, GetIndication(counter.NextIndications.Tarriff2), valuesStyle);
                            CreateRange(rowIndex + counterIndex, columnIndex++, 1, 1, GetIndication(counter.DifferenceT2), valuesStyle);
                        }
                        // однотарифный
                        else
                        {
                            CreateRange(rowIndex + counterIndex, columnIndex++, 1, 1, "TƩ", textStyle);
                            CreateRange(rowIndex + counterIndex, columnIndex++, 1, 1, GetIndication(counter.PreviousIndication), valuesStyle);
                            CreateRange(rowIndex + counterIndex, columnIndex++, 1, 1, GetIndication(counter.NextIndication), valuesStyle);
                            CreateRange(rowIndex + counterIndex, columnIndex++, 1, 1, GetIndication(counter.Difference), valuesStyle);
                        }
                    }
                    rowIndex += countersCount;
                }
                collectorIndex++;
            }
        }
 public UDPClientASocket(System.Text.Encoding willEncode)
 {
     this.ip    = GetMyIP();
     errCounter = new Counter(20);             //Number of garbage collected to be determined
     encoding   = willEncode;
 }
Ejemplo n.º 58
0
 public void Awake()
 {
     instance = this;
     counter  = GetComponent <Counter>();
 }
Ejemplo n.º 59
0
 /// <nodoc />
 protected abstract Task <OpenStreamResult> OpenStreamCoreAsync(
     OperationContext operationContext,
     ContentHash contentHash,
     UrgencyHint urgencyHint,
     Counter retryCounter);
 public void SetUp(BenchmarkContext context)
 {
     _objCounter = context.GetCounter("ProjectCounter");
 }