System.DateTimeOffset.ToUnixTimeMilliseconds()

Here are the examples of the csharp api System.DateTimeOffset.ToUnixTimeMilliseconds() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

656 Examples 7

19 Source : AbstractMainchainState.cs
with GNU Affero General Public License v3.0
from blockbasenetwork

protected virtual bool IsTimeUpForProducer(CurrentProducerTable currentProducer, ContractInformationTable contractInfo)
        {
            return (currentProducer.StartProductionTime + contractInfo.BlockTimeDuration) * 1000 <= DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
        }

19 Source : LibraClient.cs
with MIT License
from blockcoli

public async Task<bool> TransferCoins(Account sender, string receiverAddress, ulong amount, ulong gasUnitPrice = 0, ulong maxGasAmount = 1000000)
        {
            try
            {
                var accountState = await QueryBalance(sender.Address);

                var payloadLCS = new PayloadLCS();
                payloadLCS.Code = Convert.FromBase64String(Constant.ProgamBase64Codes.PeerToPeerTxn);
                payloadLCS.TransactionArguments = new List<TransactionArgumentLCS>();
                payloadLCS.TransactionArguments.Add(new TransactionArgumentLCS 
                {  
                    ArgType = Types.TransactionArgument.Types.ArgType.Address,
                    Address = new AddressLCS { Value = receiverAddress }
                });
                payloadLCS.TransactionArguments.Add(new TransactionArgumentLCS 
                {  
                    ArgType = Types.TransactionArgument.Types.ArgType.U64,
                    U64 = amount
                });

                var transaction = new RawTransactionLCS
                {
                    Sender = new AddressLCS { Value = sender.Address },
                    SequenceNumber = accountState.SequenceNumber,
                    TransactionPayload = TransactionPayloadLCS.FromScript(payloadLCS),
                    MaxGasAmount = maxGasAmount,
                    GasUnitPrice = gasUnitPrice,
                    ExpirationTime = (ulong)Math.Floor((decimal)DateTimeOffset.Now.ToUnixTimeMilliseconds() / 1000) + 100
                }; 

                var transactionLCS = LCSCore.LCSDeserialization(transaction);

                var digestSHA3 = new SHA3_256();
                var saltDigest = digestSHA3.ComputeVariable(Constant.HashSaltValues.RawTransactionHashSalt.ToBytes());
                var saltDigestAndTransaction = saltDigest.Concat(transactionLCS).ToArray();
                var hash = digestSHA3.ComputeVariable(saltDigestAndTransaction);
                var senderSignature = sender.KeyPair.Sign(hash);     
                
                var publicKeyLen = BitConverter.GetBytes((uint)sender.PublicKey.Length);
                var signatureLen = BitConverter.GetBytes((uint)senderSignature.Length);
                var txnBytes = transactionLCS.Concat(publicKeyLen).ToArray();
                txnBytes = txnBytes.Concat(sender.PublicKey).ToArray();
                txnBytes = txnBytes.Concat(signatureLen).ToArray();
                txnBytes = txnBytes.Concat(senderSignature).ToArray();                
                                
                var request = new SubmitTransactionRequest
                {
                    Transaction = new SignedTransaction
                    {                        
                        TxnBytes = txnBytes.ToByteString()
                    }
                };         
                
                var response = await acClient.SubmitTransactionAsync(request);
                return response.AcStatus.Code == AdmissionControlStatusCode.Accepted;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

19 Source : RedisQueueClient.cs
with MIT License
from BookBeat

private async Task<RedisMessage<T>> GetMessageAsync(CancellationTokenSource cancellationsSource)
        {
            if (cancellationsSource.IsCancellationRequested) return null;

            try
            {
                byte[] lisreplacedem = await _db.ListRightPopLeftPushAsync(_queueName, RedisQueueConventions.GetProcessingQueueName(_queueName)).ConfigureAwait(false);
                if (lisreplacedem == null)
                {
                    cancellationsSource.Cancel();
                    return null;
                }

                var message = _serializer.Deserialize<RedisLisreplacedem<T>>(lisreplacedem.replacedpan());
                var hashKey = RedisQueueConventions.GetMessageHashKey(_queueName, message.Id);

                var tasks = new Task[]
                {
                    _db.StringSetAsync(RedisQueueConventions.GetMessageExpirationKey(_queueName, message.Id), DateTimeOffset.Now.ToUnixTimeMilliseconds()),
                    _db.HashIncrementAsync(hashKey, RedisHashKeys.DeliveryCount)
                };
                await Task.WhenAll(tasks).ConfigureAwait(false);
                var hash = await _db.HashGetAllAsync(hashKey).ConfigureAwait(false);

                return new RedisMessage<T>(lisreplacedem, message.Id, message.Body, hash, _queueName);
            }
            catch (RedisTimeoutException e)
            {
                _log.Error(e, "Error retrieving redis message");
                return null;
            }
            catch (RedisException e)
            {
                _log.Error(e, "Error retrieving redis message");
                return null;
            }
        }

19 Source : LostMessageBackgroundService.cs
with MIT License
from BookBeat

private async Task<(bool lost, RedisLisreplacedem<T> message, RedisValue lisreplacedem)> HandlePotentiallyLostMessage(string queueName, byte[] lisreplacedem)
        {
            var message = _serializer.Deserialize<RedisLisreplacedem<T>>(lisreplacedem.replacedpan());
            var lastProcessedKey = RedisQueueConventions.GetMessageExpirationKey(queueName, message.Id);
            var hash = await _db.StringGetAsync(lastProcessedKey).ConfigureAwait(false);

            if (!hash.IsNull)
            {
                var processTimeStamp = DateTimeOffset.FromUnixTimeMilliseconds(long.Parse(hash));
                if (processTimeStamp + _messageTimeout < DateTimeOffset.Now)
                {
                    //Message is lost or has exceeded maximum processing time
                    return (true, message, lisreplacedem);
                }
            }
            else
            {
                await _db.StringSetAsync(lastProcessedKey, DateTimeOffset.Now.Add(-_messageTimeout).ToUnixTimeMilliseconds(), GetDelay()+GetDelay()).ConfigureAwait(false);
            }

            return (false, default, lisreplacedem);
        }

19 Source : LocalTimeProvider.cs
with Apache License 2.0
from bosima

public long GetCurrentUtcMilliseconds()
        {
            return DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
        }

19 Source : RedisTimeProvider.cs
with Apache License 2.0
from bosima

public long GetCurrentUtcMilliseconds()
        {
            DateTimeOffset utcTime = GetCurrentUtcTime();
            return utcTime.ToUnixTimeMilliseconds();
        }

19 Source : RedisTimeProvider.cs
with Apache License 2.0
from bosima

public async Task<long> GetCurrentUtcMillisecondsAsync()
        {
            DateTimeOffset utcTime = await GetCurrentUtcTimeAsync().ConfigureAwait(false);
            return utcTime.ToUnixTimeMilliseconds();
        }

19 Source : LocalTimeProviderTest.cs
with Apache License 2.0
from bosima

[DataTestMethod]
        public async Task TestGetCurrentUtcMillisecondsAsync()
        {
            var currentTs = await GetTimeProvider().GetCurrentUtcMillisecondsAsync();
            replacedert.AreEqual(true, currentTs <= DateTimeOffset.UtcNow.ToUnixTimeMilliseconds());
        }

19 Source : RedisTimeProviderTest.cs
with Apache License 2.0
from bosima

[DataTestMethod]
        public void TestGetCurrentUtcMilliseconds()
        {
            var currentTs = GetTimeProvider().GetCurrentUtcMilliseconds();
            replacedert.AreEqual(true, currentTs > DateTimeOffset.Parse("2021-1-1").ToUnixTimeMilliseconds());
        }

19 Source : RedisTimeProviderTest.cs
with Apache License 2.0
from bosima

[DataTestMethod]
        public async Task TestGetCurrentUtcMillisecondsAsync()
        {
            var currentTs = await GetTimeProvider().GetCurrentUtcMillisecondsAsync();
            replacedert.AreEqual(true, currentTs > DateTimeOffset.Parse("2021-1-1").ToUnixTimeMilliseconds());
        }

19 Source : AlgorithmStartTimeTest.cs
with Apache License 2.0
from bosima

[DataTestMethod]
        public void TestToSpecifiedTypeTime()
        {
            DateTimeOffset startTime = DateTimeOffset.Parse("2021-12-21 21:21:21.211");
            long startTimeTs = startTime.ToUnixTimeMilliseconds();

            var startTime1 = AlgorithmStartTime.ToSpecifiedTypeTime(startTime, TimeSpan.Parse("1"), StartTimeType.FromCurrent);
            replacedert.AreEqual("2021-12-21 21:21:21.211", startTime1.ToString("yyyy-MM-dd HH:mm:ss.fff"));

            var startTime2 = AlgorithmStartTime.ToSpecifiedTypeTime(startTime, TimeSpan.Parse("1"), StartTimeType.FromNaturalPeriodBeign);
            replacedert.AreEqual("2021-12-21 00:00:00.000", startTime2.ToString("yyyy-MM-dd HH:mm:ss.fff"));

            var startTime3 = AlgorithmStartTime.ToSpecifiedTypeTime(startTimeTs, TimeSpan.Parse("1"), StartTimeType.FromCurrent);
            replacedert.AreEqual(startTimeTs, startTime3);

            var startTime4 = AlgorithmStartTime.ToSpecifiedTypeTime(startTimeTs, TimeSpan.Parse("1"), StartTimeType.FromNaturalPeriodBeign);
            replacedert.AreEqual(1640044800000, startTime4);
        }

19 Source : AlgorithmStartTime.cs
with Apache License 2.0
from bosima

public static long ToSpecifiedTypeTime(long startTimeMilliseonds, TimeSpan statWindow, StartTimeType startTimeType)
        {
            if (startTimeType == StartTimeType.FromNaturalPeriodBeign)
            {
                DateTimeOffset startTimeUtc = DateTimeOffset.FromUnixTimeMilliseconds(startTimeMilliseonds);
                DateTimeOffset startTime = AlgorithmStartTime.ToNaturalPeriodBeignTime(startTimeUtc, statWindow);
                return startTime.ToUnixTimeMilliseconds();
            }

            return startTimeMilliseonds;
        }

19 Source : LocalTimeProviderTest.cs
with Apache License 2.0
from bosima

[DataTestMethod]
        public void TestGetCurrentUtcMilliseconds()
        {
            var currentTs = GetTimeProvider().GetCurrentUtcMilliseconds();
            replacedert.AreEqual(true, currentTs <= DateTimeOffset.UtcNow.ToUnixTimeMilliseconds());
        }

19 Source : DateTimeExtensions.cs
with MIT License
from brthor

public static long ToUnixTimeMilliseconds(this DateTime source) 
        {
            return new DateTimeOffset(source).ToUnixTimeMilliseconds();
        }

19 Source : GivenATaskSchedulerInAnotherThread.cs
with MIT License
from brthor

[Fact]
        public async Task ItExecutesScheduledTasksOnlyOnce()
        {
            const int numberOfTasks = 1000;
            const int tasksPerTimeInterval = 25;
            const int timeInterval = 1000;
            const int numberOfSchedulerThreads = 4;
            TimeSpan promotionFrequency = TimeSpan.FromMilliseconds(100);
            ThreadPool.SetMinThreads(numberOfSchedulerThreads * 4, 200);

            var taskQueue = TaskQueueTestFixture.UniqueRedisTaskQueue();
            var taskScheduler = new TaskScheduler(taskQueue, promotionFrequency);

            var canceled = false;
            var taskSchedulerTasks = new List<Task>();
            var taskRunnerTasks = new List<Task>();
            
            for (var s=0; s<numberOfSchedulerThreads; ++s)
            {
                taskSchedulerTasks.Add(Task.Run(async () => {
                    var inThreadTaskScheduler = new TaskScheduler(taskQueue);
                    while (!canceled)
                    {
                        await inThreadTaskScheduler.Tick(forceRunPromotion: true);
                    }
                }));

                taskRunnerTasks.Add(Task.Run(async () => {
                    while (!canceled)
                    {
                        await taskQueue.ExecuteNext();
                    }
                }));
            }

            var tasks = new List<(ScheduledTask, string, string)>();

            System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew();
            for (var i=0; i<numberOfTasks/tasksPerTimeInterval; ++i)
            {
                for (var k=0; k<tasksPerTimeInterval; ++k)
                {
                    var semapreplacedFile = Path.GetTempFileName();
                    File.Delete(semapreplacedFile);
                    semapreplacedFile = semapreplacedFile + Guid.NewGuid().ToString();

                    var semapreplacedValue = Guid.NewGuid().ToString();

                    var scheduledTask = await taskScheduler.AddScheduledTask(
                        () => TaskQueueTestFixture.WriteSemapreplacedValue(semapreplacedFile, semapreplacedValue), 
                        TimeSpan.FromMilliseconds((i+1) * timeInterval));
                    
                    tasks.Add((scheduledTask, semapreplacedFile, semapreplacedValue));
                }
            }

            _testOutputHelper.WriteLine(sw.ElapsedMilliseconds.ToString());
            
            var precisionAllowanceFactorMs = promotionFrequency.TotalMilliseconds + 10;

            long now;
            for (var i=0; i<numberOfTasks/tasksPerTimeInterval; ++i)
            {
                Thread.Sleep(timeInterval);

                // EACH TASK, 3 Cases
                // CASE 1: Scheduled Time should have run, allowing for precision loss
                // CASE 2: Scheduled Time should definitely not have run
                // CASE 3: Scheduled Time is past, but within precision allowance (may have run or not)
                foreach (var task in tasks)
                {
                    now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();

                    if (task.Item1.ScheduledUnixTimeMilliseconds <= (now - precisionAllowanceFactorMs))
                    {
                        File.Exists(task.Item2).Should().BeTrue();
                        File.ReadAllText(task.Item2).Should().Be(task.Item3);
                    }
                    else if (task.Item1.ScheduledUnixTimeMilliseconds > now)
                    {
                        File.Exists(task.Item2).Should().BeFalse();
                    }
                }
            }

            Thread.Sleep((int) precisionAllowanceFactorMs);

            foreach (var task in tasks)
            {
                File.Exists(task.Item2).Should().BeTrue();
                File.ReadAllText(task.Item2).Should().Be(task.Item3);
            }

            canceled = true;
            await Task.WhenAll(taskSchedulerTasks);
            await Task.WhenAll(taskRunnerTasks);
        }

19 Source : TaskScheduler.cs
with MIT License
from brthor

private async Task PromoteDueScheduledTasks() 
        {
            var sw = System.Diagnostics.Stopwatch.StartNew();

            if (LoadedScheduledTaskPromotionScript == null)
            {
                LoadedScheduledTaskPromotionScript = await _taskQueue.Backend.LoadLuaScript(LuaScriptToPromoteScheduledTasks());
            }

            await _taskQueue.Backend.RunLuaScript(LoadedScheduledTaskPromotionScript, 
                new [] {
                    (RedisKey) ScheduledTasksOrderedSetKey,
                    (RedisKey) ScheduledTasksMapKey,
                    (RedisKey) _taskQueue.Config.QueueName,
                    (RedisKey) RecurringTaskRescheduleQueueKey
                },
                new [] {(RedisValue) DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()});

            var profile = $"PROFILE {nameof(PromoteDueScheduledTasks)}: {sw.ElapsedMilliseconds}";
            // Console.WriteLine(profile);
        }

19 Source : TaskScheduler.cs
with MIT License
from brthor

private string UniqueTaskKey()
        {
            return $"{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}::{Guid.NewGuid().ToString()}";
        }

19 Source : CamundaCloudTokenProvider.cs
with Apache License 2.0
from camunda-community-hub

private Task<string> GetValidToken(AccessToken currentAccessToken)
        {
            var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            var dueDate = currentAccessToken.DueDate;
            if (now < dueDate)
            {
                // still valid
                return Task.FromResult(currentAccessToken.Token);
            }

            logger?.LogTrace("Access token is no longer valid (now: {now} > dueTime: {dueTime}), request new one.", now, dueDate);
            return RequestAccessTokenAsync();
        }

19 Source : CamundaCloudTokenProvider.cs
with Apache License 2.0
from camunda-community-hub

private static AccessToken ToAccessToken(string result)
        {
            var jsonResult = JObject.Parse(result);
            var accessToken = (string)jsonResult["access_token"];

            var expiresInMilliSeconds = (long)jsonResult["expires_in"] * 1_000L;
            var dueDate = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + expiresInMilliSeconds;
            var token = new AccessToken(accessToken, dueDate);
            return token;
        }

19 Source : HttpAgentCommon.cs
with MIT License
from catcherwong

public static void BuildSignHeaders(HttpRequestMessage requestMessage, Dictionary<string, string> paramValues, string secretKey)
        {
            var timeStamp = DateTimeOffset.Now.ToUnixTimeMilliseconds().ToString();
            requestMessage.Headers.TryAddWithoutValidation("timeStamp", timeStamp);

            var resource = paramValues.ContainsKey("tenant") && paramValues["tenant"].Length > 0
                ? string.Concat(paramValues["tenant"], "+", paramValues["group"])
                : paramValues["group"];

            var signature = string.IsNullOrWhiteSpace(resource)
                ? HashUtil.GetHMACSHA1(timeStamp, secretKey)
                : HashUtil.GetHMACSHA1($"{resource}+{timeStamp}", secretKey);

            requestMessage.Headers.TryAddWithoutValidation("Spas-Signature", signature);
        }

19 Source : SecurityProxy.cs
with MIT License
from catcherwong

public async Task<bool> LoginAsync(List<string> servers)
        {
            try
            {
                if ((DateTimeOffset.Now.ToUnixTimeSeconds() - _lastRefreshTime) < _tokenTtl - _tokenRefreshWindow)
                {
                    return true;
                }

                foreach (var server in servers)
                {
                    var flag = await LoginAsync(server);
                    if (flag)
                    {
                        _lastRefreshTime = DateTimeOffset.Now.ToUnixTimeMilliseconds();
                        return true;
                    }
                }
            }
            catch
            {
            }

            return false;
        }

19 Source : HttpClientFactoryUtil.cs
with MIT License
from catcherwong

public static void BuildSignHeader(HttpRequestMessage requestMessage, string param, string secretKey)
        {
            if (string.IsNullOrWhiteSpace(param)) return;

            var timeStamp = DateTimeOffset.Now.ToUnixTimeMilliseconds().ToString();
            requestMessage.Headers.TryAddWithoutValidation("timeStamp", timeStamp);
           
            var dict = GetDictFromParam(param);

            var resource = dict.ContainsKey("tenant") && dict["tenant"].Length > 0
                ? string.Concat(dict["tenant"], "+", dict["group"])
                : dict["group"];

            var signature = string.IsNullOrWhiteSpace(resource)
                ? HashUtil.GetHMACSHA1(timeStamp, secretKey)
                : HashUtil.GetHMACSHA1($"{resource}+{timeStamp}", secretKey);

            requestMessage.Headers.TryAddWithoutValidation("Spas-Signature", signature);
        }

19 Source : ValuesController.cs
with MIT License
from catcherwong-archive

[HttpGet("demo4")]
        public async Task<string> GetDemo4()
        {
            var client = _clientFactory.CreateClient("demo3");
            var res = await client.GetAsync("http://localhost:9898/api/values/demo3");
            var str = await res.Content.ReadreplacedtringAsync();

            var traceId = string.Empty;
            if (Request.Headers.TryGetValue("traceId", out var tId)) traceId = tId.ToString();
            Console.WriteLine($"{traceId} demo3 return {str} at {DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}");

            return str;
        }

19 Source : ValuesController.cs
with MIT License
from catcherwong-archive

[HttpGet]
        public async Task<string> GetAsync()
        {
            var traceId = string.Empty;

            if (Request.Headers.TryGetValue("traceId", out var tId))
            {
                traceId = tId.ToString();
                Console.WriteLine($"{traceId} from request {DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}.");
            }
            else
            {
                traceId = System.Guid.NewGuid().ToString("N");
                Request.Headers.Add("traceId", new Microsoft.Extensions.Primitives.StringValues(traceId));
                Console.WriteLine($"{traceId} from generated {DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}.");
            }

            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Clear();
                client.DefaultRequestHeaders.TryAddWithoutValidation("traceId", traceId);

                var res = await client.GetAsync("http://localhost:9898/api/values/demo1");
                var str = await res.Content.ReadreplacedtringAsync();
                Console.WriteLine($"{traceId} demo1 return {str} at {DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}");
                return str;
            }


            //var client = _clientFactory.CreateClient("demo1");
            //var res = await client.GetAsync("http://localhost:9898/api/values/demo1");
            //var str = await res.Content.ReadreplacedtringAsync();

            //var traceId = string.Empty;
            //if (Request.Headers.TryGetValue("traceId", out var tId)) traceId = tId.ToString();
            //Console.WriteLine($"{traceId} demo1 return {str} at {DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}");

            //return str;

        }

19 Source : HeadersPropagationDelegatingHandler.cs
with MIT License
from catcherwong-archive

protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {            
            var traceId = string.Empty;

            if (_accessor.HttpContext.Request.Headers.TryGetValue("traceId", out var tId))
            {
                traceId = tId.ToString();
                Console.WriteLine($"{traceId} from request {DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}.");
            }
            else
            {
                traceId = System.Guid.NewGuid().ToString("N");
                _accessor.HttpContext.Request.Headers.Add("traceId", new Microsoft.Extensions.Primitives.StringValues(traceId));
                Console.WriteLine($"{traceId} from generated {DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}.");
            }

            if (!request.Headers.Contains("trace-id"))
            {
                request.Headers.TryAddWithoutValidation("traceId", traceId);
            }

            return await base.SendAsync(request, cancellationToken);
        }

19 Source : RedisProfilerEntryToSpanConverter.cs
with Apache License 2.0
from census-instrumentation

internal static ISpanData ProfiledCommandToSpanData(ISpanContext context, string name, ISpanId parentSpanId, IProfiledCommand command)
        {
            var hasRemoteParent = false;

            // use https://github.com/opentracing/specification/blob/master/semantic_conventions.md for now

            // Timing example:
            // command.CommandCreated; //2019-01-10 22:18:28Z

            // command.CreationToEnqueued;      // 00:00:32.4571995
            // command.EnqueuedToSending;       // 00:00:00.0352838
            // command.SentToResponse;          // 00:00:00.0060586
            // command.ResponseToCompletion;    // 00:00:00.0002601

            // Total:
            // command.ElapsedTime;             // 00:00:32.4988020

            // TODO: make timestamp with the better precision
            Timestamp startTimestamp = Timestamp.FromMillis(new DateTimeOffset(command.CommandCreated).ToUnixTimeMilliseconds());

            var timestamp = new DateTimeOffset(command.CommandCreated).Add(command.CreationToEnqueued);
            var annotations = TimedEvents<IAnnotation>.Create(
                new List<ITimedEvent<IAnnotation>>()
                {
                    TimedEvent<IAnnotation>.Create(Timestamp.FromMillis(timestamp.ToUnixTimeMilliseconds()), Annotation.FromDescription("Enqueued")),
                    TimedEvent<IAnnotation>.Create(Timestamp.FromMillis((timestamp = timestamp.Add(command.EnqueuedToSending)).ToUnixTimeMilliseconds()), Annotation.FromDescription("Sent")),
                    TimedEvent<IAnnotation>.Create(Timestamp.FromMillis((timestamp = timestamp.Add(command.SentToResponse)).ToUnixTimeMilliseconds()), Annotation.FromDescription("ResponseRecieved")),
                },
                droppedEventsCount: 0);

            Timestamp endTimestamp = Timestamp.FromMillis(new DateTimeOffset(command.CommandCreated.Add(command.ElapsedTime)).ToUnixTimeMilliseconds());

            // TODO: deal with the re-transmission
            // command.RetransmissionOf;
            // command.RetransmissionReason;

            var attributesMap = new Dictionary<string, IAttributeValue>()
            {
                // TODO: pre-allocate constant attribute and reuse
                { "db.type", AttributeValue.StringAttributeValue("redis") },

                // Example: "redis.flags": None, DemandMaster
                { "redis.flags", AttributeValue.StringAttributeValue(command.Flags.ToString()) },
            };

            if (command.Command != null)
            {
                // Example: "db.statement": SET;
                attributesMap.Add("db.statement", AttributeValue.StringAttributeValue(command.Command));
            }

            if (command.EndPoint != null)
            {
                // Example: "db.instance": Unspecified/localhost:6379[0]
                attributesMap.Add("db.instance", AttributeValue.StringAttributeValue(command.EndPoint.ToString() + "[" + command.Db + "]"));
            }

            var attributes = Attributes.Create(attributesMap, 0);

            ITimedEvents<IMessageEvent> messageOrNetworkEvents = null;
            ILinks links = null;
            int? childSpanCount = 0;

            // TODO: this is strange that IProfiledCommand doesn't give the result
            Status status = Status.Ok;
            SpanKind kind = SpanKind.Client;

            return SpanData.Create(context, parentSpanId, hasRemoteParent, name, startTimestamp, attributes, annotations, messageOrNetworkEvents, links, childSpanCount, status, kind, endTimestamp);
        }

19 Source : PrometheusMetricBuilder.cs
with Apache License 2.0
from census-instrumentation

public void Write(StreamWriter writer)
        {
            // https://prometheus.io/docs/instrumenting/exposition_formats/

            if (string.IsNullOrEmpty(this.name))
            {
                throw new InvalidOperationException("Metric name should not be empty");
            }

            this.name = GetSafeMetricName(this.name);

            if (!string.IsNullOrEmpty(this.description))
            {
                // Lines with a # as the first non-whitespace character are comments.
                // They are ignored unless the first token after # is either HELP or TYPE.
                // Those lines are treated as follows: If the token is HELP, at least one
                // more token is expected, which is the metric name. All remaining tokens
                // are considered the docstring for that metric name. HELP lines may contain
                // any sequence of UTF-8 characters (after the metric name), but the backslash
                // and the line feed characters have to be escaped as \\ and \n, respectively.
                // Only one HELP line may exist for any given metric name.

                writer.Write("# HELP ");
                writer.Write(this.name);
                writer.Write(GetSafeMetricDescription(this.description));
                writer.Write("\n");
            }

            if (string.IsNullOrEmpty(this.type))
            {
                // If the token is TYPE, exactly two more tokens are expected. The first is the
                // metric name, and the second is either counter, gauge, histogram, summary, or
                // untyped, defining the type for the metric of that name. Only one TYPE line
                // may exist for a given metric name. The TYPE line for a metric name must appear
                // before the first sample is reported for that metric name. If there is no TYPE
                // line for a metric name, the type is set to untyped.

                writer.Write("# HELP ");
                writer.Write(this.name);
                writer.Write(this.type);
                writer.Write("\n");
            }

            // The remaining lines describe samples (one per line) using the following syntax (EBNF):
            // metric_name [
            //   "{" label_name "=" `"` label_value `"` { "," label_name "=" `"` label_value `"` } [ "," ] "}"
            // ] value [ timestamp ]
            // In the sample syntax:

            foreach (var m in this.values)
            {
                // metric_name and label_name carry the usual Prometheus expression language restrictions.
                writer.Write(this.name);

                // label_value can be any sequence of UTF-8 characters, but the backslash
                // (\, double-quote ("}, and line feed (\n) characters have to be escaped
                // as \\, \", and \n, respectively.

                if (m.Labels.Count > 0)
                {
                    writer.Write(@"{");
                    var isFirst = true;

                    foreach (var l in m.Labels)
                    {
                        if (isFirst)
                        {
                            isFirst = false;
                        }
                        else
                        {
                            writer.Write(",");
                        }

                        var safeKey = GetSafeLabelName(l.Item1);
                        var safeValue = GetSafeLabelValue(l.Item2);
                        writer.Write(safeKey);
                        writer.Write("=\"");
                        writer.Write(safeValue);
                        writer.Write("\"");
                    }

                    writer.Write(@"}");
                }

                // value is a float represented as required by Go's ParseFloat() function. In addition to
                // standard numerical values, Nan, +Inf, and -Inf are valid values representing not a number,
                // positive infinity, and negative infinity, respectively.
                writer.Write(" ");
                writer.Write(m.Value);
                writer.Write(" ");

                // The timestamp is an int64 (milliseconds since epoch, i.e. 1970-01-01 00:00:00 UTC, excluding
                // leap seconds), represented as required by Go's ParseInt() function.
                writer.Write(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString());

                // Prometheus' text-based format is line oriented. Lines are separated
                // by a line feed character (\n). The last line must end with a line
                // feed character. Empty lines are ignored.
                writer.Write("\n");
            }
        }

19 Source : RedisProfilerEntryToSpanConverterTests.cs
with Apache License 2.0
from census-instrumentation

[Fact]
        public void ProfiledCommandToSpanDataUsesTimestampreplacedtartTime()
        {
            var profiledCommand = new Mock<IProfiledCommand>();
            var now = DateTimeOffset.Now;
            profiledCommand.Setup(m => m.CommandCreated).Returns(now.DateTime);
            var result = RedisProfilerEntryToSpanConverter.ProfiledCommandToSpanData(SpanContext.Invalid, "SET", SpanId.Invalid, profiledCommand.Object);
            replacedert.Equal(Timestamp.FromMillis(now.ToUnixTimeMilliseconds()), result.StartTimestamp);
        }

19 Source : Orders.cs
with MIT License
from charlessolar

public async Task Handle(Queries.Orders query, IMessageHandlerContext ctx)
        {
            var builder = new QueryBuilder();

            if (query.OrderStatus != null)
                builder.Add("Status", query.OrderStatus.Value, Operation.Equal);
            
            if (query.From.HasValue)
                builder.Add("Created", new DateTimeOffset(query.From.Value).ToUnixTimeMilliseconds().ToString(), Operation.GreaterThanOrEqual);
            if (query.To.HasValue)
                builder.Add("Created", new DateTimeOffset(query.To.Value).ToUnixTimeMilliseconds().ToString(), Operation.LessThanOrEqual);
            
            var results = await ctx.UoW().Query<Models.OrderingOrderIndex>(builder.Build())
                .ConfigureAwait(false);

            await ctx.Result(results.Records, results.Total, results.ElapsedMs).ConfigureAwait(false);
        }

19 Source : Mutator.cs
with MIT License
from charlessolar

public IMutating MutateOutgoing(IMutating mutating)
        {
            // Make sure UserId and Stamp are transfer from message to message
            if (mutating.Message is StampedCommand)
            {
                if ((mutating.Message as StampedCommand).Stamp != 0) return mutating;

                if (_uow.CurrentMessage is StampedCommand)
                {
                    var command = _uow.CurrentMessage as StampedCommand;
                    ((StampedCommand)mutating.Message).Stamp = command.Stamp;
                }
                else if (_uow.CurrentMessage is IStampedEvent)
                {
                    var @event = _uow.CurrentMessage as IStampedEvent;
                    ((StampedCommand)mutating.Message).Stamp = @event.Stamp;
                }
                else if((mutating.Message as StampedCommand).Stamp == 0)
                {
                    (mutating.Message as StampedCommand).Stamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                }
            }
            else if (mutating.Message is IStampedEvent)
            {
                if ((mutating.Message as IStampedEvent).Stamp != 0) return mutating;

                if (_uow.CurrentMessage is StampedCommand)
                {
                    var command = _uow.CurrentMessage as StampedCommand;
                    ((IStampedEvent)mutating.Message).Stamp = command.Stamp;
                }
                else if (_uow.CurrentMessage is IStampedEvent)
                {
                    var @event = _uow.CurrentMessage as IStampedEvent;
                    ((IStampedEvent)mutating.Message).Stamp = @event.Stamp;
                }
                else if ((mutating.Message as IStampedEvent).Stamp == 0)
                {
                    (mutating.Message as IStampedEvent).Stamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                }
            }

            return mutating;
        }

19 Source : Mutator.cs
with MIT License
from charlessolar

public IMutating MutateOutgoing(IMutating mutating)
        {

            if (!(mutating.Message is StampedCommand) || (mutating.Message as StampedCommand).Stamp != 0) return mutating;

            (mutating.Message as StampedCommand).Stamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();

            return mutating;
        }

19 Source : DateTimeExtensions.cs
with MIT License
from charlessolar

public static long ToUnix(this DateTime datetime)
        {
            return new DateTimeOffset(datetime).ToUnixTimeMilliseconds();
        }

19 Source : Mutator.cs
with MIT License
from charlessolar

public IMutating MutateOutgoing(IMutating mutating)
        {
            if (!(mutating.Message is StampedCommand)) return mutating;

            (mutating.Message as StampedCommand).Stamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();

            return mutating;
        }

19 Source : UtilsHelper.cs
with MIT License
from chatop2020

public static long GetTimeStampMilliseconds()
        {
            return new DateTimeOffset(DateTime.UtcNow).ToUnixTimeMilliseconds();
        }

19 Source : Program.cs
with Apache License 2.0
from cognitedata

static async Task GzipPerformanceTest(Client client)
        {
            try
            {
                var ts = await client.TimeSeries.CreateAsync(
                    Enumerable.Range(0, 100).Select(idx => new TimeSeriesCreate
                    {
                        Name = $"gzip-ts-test-{idx}",
                        ExternalId = $"gzip-ts-test-{idx}"
                    }).ToList());
            } catch (ResponseException rex) when (rex.Duplicated?.Any() ?? false) { }

            var chunks = new[]
            {
                (1, 100), (10, 100), (100, 100), (1, 1000), (10, 1000), (100, 1000), (1, 10000), (10, 10000)
            };


            Console.WriteLine("Gzip: ");

            long start = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeMilliseconds();
            foreach (var pair in chunks)
            {
                var data = new DataPointInsertionRequest();
                for (int i = 0; i < pair.Item1; i++)
                {
                    var req = new NumericDatapoints();
                    for (int j = 0; j < pair.Item2; j++)
                    {
                        req.Datapoints.Add(new NumericDatapoint
                        {
                            Timestamp = start + i * pair.Item2 + j,
                            Value = i * pair.Item2 + j
                        });
                    }
                    data.Items.Add(new DataPointInsertionItem
                    {
                        ExternalId = $"gzip-ts-test-{i}",
                        NumericDatapoints = req
                    });
                }

                var sw = new Stopwatch();
                sw.Start();
                await client.DataPoints.CreateAsync(data, System.IO.Compression.CompressionLevel.Fastest);
                sw.Stop();
                Console.WriteLine($"Inserting {pair.Item2} datapoints for {pair.Item1} timeseries took {sw.ElapsedMilliseconds} ms");
            }

            Console.Write("Non-gzip:");

            foreach (var pair in chunks)
            {
                var data = new DataPointInsertionRequest();
                for (int i = 0; i < pair.Item1; i++)
                {
                    var req = new NumericDatapoints();
                    for (int j = 0; j < pair.Item2; j++)
                    {
                        req.Datapoints.Add(new NumericDatapoint
                        {
                            Timestamp = start + i * pair.Item2 + j,
                            Value = i * pair.Item2 + j
                        });
                    }
                    data.Items.Add(new DataPointInsertionItem
                    {
                        ExternalId = $"gzip-ts-test-{i}",
                        NumericDatapoints = req
                    });
                }

                var sw = new Stopwatch();
                sw.Start();
                await client.DataPoints.CreateAsync(data);
                sw.Stop();
                Console.WriteLine($"Inserting {pair.Item2} datapoints for {pair.Item1} timeseries took {sw.ElapsedMilliseconds} ms");
            }

            await client.TimeSeries.DeleteAsync(new TimeSeriesDelete
            {
                IgnoreUnknownIds = true,
                Items = Enumerable.Range(0, 100).Select(idx => Idenreplacedy.Create($"gzip-ts-test-{idx}"))
            });
        }

19 Source : TimestampHelper.cs
with Apache License 2.0
from Coldairarrow

public static long ToUnixTimeMilliseconds(DateTime dateTime)
        {
            if (dateTime.Kind == DateTimeKind.Unspecified)
            {
                dateTime = new DateTime(dateTime.Ticks, DateTimeKind.Local);
            }

            return new DateTimeOffset(dateTime).ToUnixTimeMilliseconds();
        }

19 Source : TimestampConverter.cs
with Apache License 2.0
from Coldairarrow

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value == null)
            {
                writer.WriteNull();

                return;
            }

            var type = value.GetType();
            if (type == typeof(DateTime) || type == typeof(DateTime?))
            {
                var timeValue = (DateTime)value;

                writer.WriteValue(TimestampHelper.ToUnixTimeMilliseconds(timeValue));
            }
            else
            {
                writer.WriteValue(((DateTimeOffset)value).ToUnixTimeMilliseconds());
            }
        }

19 Source : CacheTest.cs
with Apache License 2.0
from Coldairarrow

[TestMethod]
        public async Task Test()
        {
            IDistributedCache distributedCache = _serviceProvider.GetService<IDistributedCache>();
            Dto dto = new Dto
            {
                Id = Guid.NewGuid(),
                Name = "小明",
                Time = DateTimeOffset.Now,
                Money = 100
            };

            string key = $"{GetType().FullName}:{nameof(Test)}";

            await distributedCache.RemoveAsync(key);

            await distributedCache.SetObjectAsync(key, dto);

            var newDto = await distributedCache.GetObjectAsync<Dto>(key);
            replacedert.AreEqual(dto.ToJson(), newDto.ToJson());

            await distributedCache.SetObjectAsync(key, dto.Time);
            var cacheString = await distributedCache.GetStringAsync(key);
            replacedert.AreEqual(dto.Time.ToString("o"), cacheString);
            var newTime = await distributedCache.GetObjectAsync<DateTimeOffset>(key);
            replacedert.AreEqual(dto.Time.ToUnixTimeMilliseconds(), newTime.ToUnixTimeMilliseconds());

            await distributedCache.SetObjectAsync(key, dto.Id);
            cacheString = await distributedCache.GetStringAsync(key);
            replacedert.AreEqual(dto.Id.ToString(), cacheString);
            var newId = await distributedCache.GetObjectAsync<Guid>(key);
            replacedert.AreEqual(dto.Id, newId);

            await distributedCache.SetObjectAsync(key, dto.Money);
            cacheString = await distributedCache.GetStringAsync(key);
            replacedert.AreEqual(dto.Money.ToString(), cacheString);
            var newMoney = await distributedCache.GetObjectAsync<decimal>(key);
            replacedert.AreEqual(dto.Money, newMoney);
        }

19 Source : CommentProvider.cs
with GNU General Public License v3.0
from CommentViewerCollection

public static long GetCurrentUnixTimeMillseconds(DateTime now)
        {
            var utcNow = DateTime.SpecifyKind(now, DateTimeKind.Utc);
            DateTimeOffset offset = utcNow;
            return offset.ToUnixTimeMilliseconds();
        }

19 Source : SeedReportController.cs
with MIT License
from ContactAssistApp

[HttpPut]
        [Consumes("application/x-protobuf", "application/json")]
        [Produces("application/x-protobuf", "application/json")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(typeof(RequestValidationResult), StatusCodes.Status400BadRequest)]
        [ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
        public async Task<ActionResult> PutAsync(SelfReportRequest request, CancellationToken cancellationToken = default)
        {
            // Get server timestamp at request immediately
            long serverTimestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();

            try
            {
                // Parse request
                Enreplacedies.Geospatial.Region region = this._map.Map<Enreplacedies.Geospatial.Region>(request.Region);
                IEnumerable<BluetoothSeedMessage> seeds = request.Seeds
                    .Select(s => this._map.Map<BluetoothSeedMessage>(s));

                // Store submitted data
                await this._reportService.PublishAsync(seeds, region, serverTimestamp, cancellationToken);

                return Ok();
            }
            catch (RequestValidationFailedException ex)
            {
                // Only return validation results
                return BadRequest(ex.ValidationResult);
            }
            catch (ArgumentNullException)
            {
                return BadRequest();
            }
        }

19 Source : AreaReportControllerTests.cs
with MIT License
from ContactAssistApp

[TestMethod]
        public async Task PutAsync_OkWithValidInputs()
        {
            // Arrange
            AreaMatch requestObj = new AreaMatch
            {
                UserMessage = "User message content"
            };
            requestObj.Areas.Add(new Area
            {
                BeginTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
                EndTime = DateTimeOffset.UtcNow.AddHours(1).ToUnixTimeMilliseconds(),
                Location = new Location
                {
                    Lareplacedude = 10.1234,
                    Longitude = 10.1234
                },
                RadiusMeters = 100
            });

            // Act
            ActionResult controllerResponse = await this._controller
                .PutAsync(requestObj, CancellationToken.None);

            // replacedert
            replacedert.IsNotNull(controllerResponse);
            replacedert.IsInstanceOfType(controllerResponse, typeof(OkResult));
        }

19 Source : ListControllerTests.cs
with MIT License
from ContactAssistApp

[TestMethod]
        public async Task GetAsync_OkWithMatchedParams()
        {
            // Arrange
            v20200415.Protos.Region requestedRegion = new Region
            {
                LareplacedudePrefix = 10.1234,
                LongitudePrefix = -10.1234,
                Precision = 4
            };

            IEnumerable<MessageContainerMetadata> response = new List<MessageContainerMetadata>
            {
                new MessageContainerMetadata
                {
                    Id = "00000000-0000-0000-0000-0000000001",
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                }
            };

            this._repo
                .Setup(s => s.GetLatestAsync(
                    It.IsAny<Enreplacedies.Geospatial.Region>(),
                    It.IsAny<long>(),
                    CancellationToken.None
                ))
                .Returns(Task.FromResult(response));

            // Act
            ActionResult<MessageListResponse> controllerResponse = await this._controller
                .GetAsync(
                    requestedRegion.LareplacedudePrefix,
                    requestedRegion.LongitudePrefix,
                    requestedRegion.Precision,
                    DateTimeOffset.UtcNow.AddHours(-1).ToUnixTimeMilliseconds(),
                    CancellationToken.None
                );

            // replacedert
            replacedert.IsNotNull(controllerResponse);
            replacedert.IsInstanceOfType(controllerResponse.Result, typeof(OkObjectResult));
            OkObjectResult castedResult = controllerResponse.Result as OkObjectResult;
            replacedert.IsInstanceOfType(castedResult.Value, typeof(MessageListResponse));
            MessageListResponse responseResult = castedResult.Value as MessageListResponse;
            replacedert.AreEqual(responseResult.MessageInfoes.Count(), response.Count());
        }

19 Source : ListControllerTests.cs
with MIT License
from ContactAssistApp

[TestMethod]
        public async Task GetAsync_EmptyOkWithUnmatchedParams()
        {
            // Arrange
            // N/A; empty service layer response will produce no results by default

            // Act
            ActionResult<MessageListResponse> controllerResponse = await this._controller
                .GetAsync(
                    10.1234,
                    -10.1234,
                    4,
                    DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
                    CancellationToken.None
                );

            // replacedert
            replacedert.IsNotNull(controllerResponse);
            replacedert.IsInstanceOfType(controllerResponse.Result, typeof(OkObjectResult));
            OkObjectResult castedResult = controllerResponse.Result as OkObjectResult;
            replacedert.IsInstanceOfType(castedResult.Value, typeof(MessageListResponse));
            MessageListResponse responseResult = castedResult.Value as MessageListResponse;
            replacedert.AreEqual(responseResult.MessageInfoes.Count, 0);
        }

19 Source : ListControllerTests.cs
with MIT License
from ContactAssistApp

[TestMethod]
        public async Task HeadAsync_ContentLengthHeaderSetWithValidParams()
        {
            // Arrange
            long repoResponse = 1024;
            this._repo
                .Setup(
                    r => r.GetLatestRegionSizeAsync(
                        It.IsAny<Enreplacedies.Geospatial.Region>(),
                        It.IsAny<long>(),
                        CancellationToken.None
                    )
                )
                .Returns(Task.FromResult(repoResponse));

            // Act
            ActionResult controllerResponse = await this._controller
                .HeadAsync(
                    10.1234,
                    -10.1234,
                    4,
                    DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
                    CancellationToken.None
                );

            // replacedert
            replacedert.IsNotNull(controllerResponse);
            replacedert.IsNotNull(this._controller.HttpContext.Response.ContentLength);
            replacedert.AreEqual(repoResponse, this._controller.HttpContext.Response.ContentLength);
        }

19 Source : ListControllerTests.cs
with MIT License
from ContactAssistApp

[TestMethod]
        public async Task HeadAsync_ContentLengthHeaderZeroWithInvalidParams()
        {
            // Arrange
            long repoResponse = 0;

            // Act
            ActionResult controllerResponse = await this._controller
                .HeadAsync(
                    10.1234,
                    -10.1234,
                    4,
                    DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
                    CancellationToken.None
                );

            // replacedert
            replacedert.IsNotNull(controllerResponse);
            replacedert.IsNotNull(this._controller.HttpContext.Response.ContentLength);
            replacedert.AreEqual(repoResponse, this._controller.HttpContext.Response.ContentLength);
        }

19 Source : SeedReportControllerTests.cs
with MIT License
from ContactAssistApp

[TestMethod]
        public async Task PutAsync_BadRequestWithNoRegion()
        {
            // Arrange
            SelfReportRequest requestObj = new SelfReportRequest();
            requestObj.Seeds.Add(new BlueToothSeed
            {
                Seed = "00000000-0000-0000-0000-000000000001",
                SequenceEndTime = DateTimeOffset.UtcNow.AddHours(1).ToUnixTimeMilliseconds(),
                SequenceStartTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });

            // Act
            ActionResult controllerResponse = await this._controller
                .PutAsync(requestObj, CancellationToken.None);

            // replacedert
            replacedert.IsNotNull(controllerResponse);
            replacedert.IsInstanceOfType(controllerResponse, typeof(BadRequestResult));
        }

19 Source : SeedReportControllerTests.cs
with MIT License
from ContactAssistApp

[TestMethod]
        public async Task PutAsync_OkWithValidInputs()
        {
            // Arrange
            SelfReportRequest requestObj = new SelfReportRequest
            {
                Region = new Region
                {
                    LareplacedudePrefix = 10.1234,
                    LongitudePrefix = 10.1234,
                    Precision = 4
                }
            };
            requestObj.Seeds.Add(new BlueToothSeed
            {
                SequenceEndTime = DateTimeOffset.UtcNow.AddHours(1).ToUnixTimeMilliseconds(),
                SequenceStartTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
                Seed = "00000000-0000-0000-0000-000000000001"
            });

            // Act
            ActionResult controllerResponse = await this._controller
                .PutAsync(requestObj, CancellationToken.None);

            // replacedert
            replacedert.IsNotNull(controllerResponse);
            replacedert.IsInstanceOfType(controllerResponse, typeof(OkResult));
        }

19 Source : MessageControllerTests.cs
with MIT License
from ContactAssistApp

[TestMethod]
        public async Task PostAsync_OkWithMatchedParameters()
        {
            // Arrange
            IEnumerable<string> ids = new string[]
            {
                "00000000-0000-0000-0000-000000000001",
                "00000000-0000-0000-0000-000000000002"
            };
            MessageContainer result1 = new MessageContainer();
            MessageContainer result2 = new MessageContainer();
            IEnumerable<MessageContainer> toReturn = new List<MessageContainer>
            {
                result1,
                result2
            };

            this._repo
                .Setup(s => s.GetRangeAsync(ids, CancellationToken.None))
                .Returns(Task.FromResult(toReturn));

            MessageRequest request = new MessageRequest();
            request.RequestedQueries.Add(new MessageInfo
            {
                MessageId = ids.ElementAt(0),
                MessageTimestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
            request.RequestedQueries.Add(new MessageInfo
            {
                MessageId = ids.ElementAt(1),
                MessageTimestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });

            // Act
            ActionResult<IEnumerable<MatchMessage>> controllerResponse = await this._controller
                .PostAsync(request, CancellationToken.None);

            // replacedert
            replacedert.IsNotNull(controllerResponse);
            replacedert.IsInstanceOfType(controllerResponse.Result, typeof(OkObjectResult));
            OkObjectResult castedResult = controllerResponse.Result as OkObjectResult;
            replacedert.IsInstanceOfType(castedResult.Value, typeof(List<MatchMessage>));
            List<MatchMessage> listResult = castedResult.Value as List<MatchMessage>;
            replacedert.AreEqual(toReturn.Count(), listResult.Count());
        }

19 Source : MessageControllerTests.cs
with MIT License
from ContactAssistApp

[TestMethod]
        public async Task PostAsync_OkWithPartiallyMatchedParameters()
        {
            // Arrange
            IEnumerable<string> ids = new string[]
            {
                "00000000-0000-0000-0000-000000000001",
                "00000000-0000-0000-0000-000000000002"
            };
            MessageContainer result1 = new MessageContainer();
            IEnumerable<MessageContainer> toReturn = new List<MessageContainer>
            {
                result1
            };

            this._repo
                .Setup(s => s.GetRangeAsync(ids, CancellationToken.None))
                .Returns(Task.FromResult(toReturn));

            MessageRequest request = new MessageRequest();
            request.RequestedQueries.Add(new MessageInfo
            {
                MessageId = ids.ElementAt(0),
                MessageTimestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
            request.RequestedQueries.Add(new MessageInfo
            {
                MessageId = ids.ElementAt(1),
                MessageTimestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });

            // Act
            ActionResult<IEnumerable<MatchMessage>> controllerResponse = await this._controller
                .PostAsync(request, CancellationToken.None);

            // replacedert
            replacedert.IsNotNull(controllerResponse);
            replacedert.IsInstanceOfType(controllerResponse.Result, typeof(OkObjectResult));
            OkObjectResult castedResult = controllerResponse.Result as OkObjectResult;
            replacedert.IsInstanceOfType(castedResult.Value, typeof(List<MatchMessage>));
            List<MatchMessage> listResult = castedResult.Value as List<MatchMessage>;
            replacedert.AreEqual(1, listResult.Count());
        }

19 Source : ListControllerTests.cs
with MIT License
from ContactAssistApp

[TestMethod]
        public async Task GetAsync_OkWithMatchedParams()
        {
            // Arrange
            v20200505.Protos.Region requestedRegion = new Region
            {
                LareplacedudePrefix = 10.1234,
                LongitudePrefix = -10.1234,
                Precision = 4
            };

            IEnumerable<MessageContainerMetadata> response = new List<MessageContainerMetadata>
            {
                new MessageContainerMetadata
                {
                    Id = "00000000-0000-0000-0000-0000000001",
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                }
            };

            this._repo
                .Setup(s => s.GetLatestAsync(
                    It.IsAny<Enreplacedies.Geospatial.Region>(),
                    It.IsAny<long>(),
                    CancellationToken.None
                ))
                .Returns(Task.FromResult(response));

            // Act
            ActionResult<MessageListResponse> controllerResponse = await this._controller
                .GetAsync(
                    requestedRegion.LareplacedudePrefix,
                    requestedRegion.LongitudePrefix,
                    requestedRegion.Precision,
                    DateTimeOffset.UtcNow.AddHours(-1).ToUnixTimeMilliseconds(),
                    CancellationToken.None
                );

            // replacedert
            replacedert.IsNotNull(controllerResponse);
            replacedert.IsInstanceOfType(controllerResponse.Result, typeof(OkObjectResult));
            OkObjectResult castedResult = controllerResponse.Result as OkObjectResult;
            replacedert.IsInstanceOfType(castedResult.Value, typeof(MessageListResponse));
            MessageListResponse responseResult = castedResult.Value as MessageListResponse;
            replacedert.AreEqual(responseResult.MessageInfoes.Count(), response.Count());
        }

See More Examples