예제 #1
0
        public void Compare_Time()
        {
            var times = new DateTimeOffset[]
            {
                new DateTime(2012, 12, 4),
                new DateTime(2011, 12, 31),
                new DateTime(2012, 1, 5),
                new DateTime(2013, 12, 4),
                new DateTime(2016, 12, 4),
            };

            times.Select(x => Ulid.NewUlid(x)).OrderBy(x => x).Select(x => x.Time).Should().BeEquivalentTo(times.OrderBy(x => x));
        }
예제 #2
0
        public UlidTest()
        {
            for (int i = 0; i < TEST_COUNT / 2; ++i)
            {
                ulids[i] = Ulid.NewUlid();
            }

            Thread.Sleep(100); //Ensure not all are at the same millisecond

            for (int i = TEST_COUNT / 2; i < TEST_COUNT; ++i)
            {
                ulids[i] = Ulid.NewUlid();
            }
        }
예제 #3
0
        public void Ulid_GetHashCode_WorksCorrectly()
        {
            var rng       = new FakeUlidRng();
            var hashcodes = new List <int>()
            {
                Ulid.MinValue.GetHashCode(),
                Ulid.MaxValue.GetHashCode(),
                Ulid.NewUlid().GetHashCode(),
            };

            hashcodes.AddRange(Enumerable.Range(0, 1000).Select(i => Ulid.NewUlid(KNOWNTIMESTAMP_DTO.AddMilliseconds(i)).GetHashCode()));
            hashcodes.AddRange(Enumerable.Range(0, 1000).Select(i => Ulid.NewUlid(KNOWNTIMESTAMP_DTO.AddMilliseconds(i), rng).GetHashCode()));

            Assert.AreEqual(3 + 1000 + 1000, hashcodes.Distinct().Count());
        }
예제 #4
0
        public void Ulid_IsSerializable_UsingBinaryFormatter()
        {
            var target = Ulid.NewUlid();

            var formatter = new BinaryFormatter();

            using (var stream = new MemoryStream())
            {
                formatter.Serialize(stream, target);
                stream.Position = 0;
                var result = formatter.Deserialize(stream);

                Assert.AreEqual(target, result);
            }
        }
예제 #5
0
        public void Ulid_IsSerializable_UsingDataContract()
        {
            var target = Ulid.NewUlid();

            var serializer = new DataContractSerializer(target.GetType());

            using (var stream = new MemoryStream())
            {
                serializer.WriteObject(stream, target);
                stream.Position = 0;
                var result = serializer.ReadObject(stream);

                Assert.AreEqual(target, result);
            }
        }
예제 #6
0
        private void PingNode(SwimNode node)
        {
            //  Ping node directly

            PingCorrelationId = Ulid.NewUlid();

            Debug.WriteLine($"Pinging node {node.Endpoint}.");
            Logger.LogInformation($"Pinging node {node.Endpoint}.");

            ProtocolProvider.SendMessage(node, new PingMessage(PingCorrelationId.Value)
            {
                SourceNode = ProtocolProvider.Node
            });

            PingTimer.Start();
        }
예제 #7
0
        public void TestDeserializer()
        {
            var id          = Ulid.NewUlid();
            var byteArray   = new byte[16];
            var startOffset = 0;
            var formatter   = new UlidFormatter();

            formatter.Serialize(ref byteArray, ref startOffset, id);
            startOffset = 0;

            Ulid otherId = new Ulid();

            formatter.Deserialize(byteArray, ref startOffset, ref otherId);

            Assert.That(otherId, Is.EqualTo(id));
        }
        private void HandleSuspectNode()
        {
            lock (_activeNodeLock)
            {
                if (ActiveNode == null)
                {
                    return;
                }

                ActiveNode.SetStatus(SwimNodeStatus.Suspicious);

                AddBroadcastMessage(new SuspectMessage(Ulid.NewUlid(), _swimProtocolProvider.Node, ActiveNode));

                _nodeRepository.Upsert(ActiveNode);
            }
        }
예제 #9
0
        /// <summary>
        /// Add a message to a specific channel. The message's original ID will be overridden.
        /// </summary>
        /// <param name="message"></param>
        /// <param name="channelId"></param>
        /// <returns></returns>
        public async Task <Ulid> SaveMessageIntoChannel(HatoMessage message, Ulid channelId)
        {
            if (message.MsgId == Ulid.Empty)
            {
                message.MsgId = Ulid.NewUlid();
            }
            if (channelId != Ulid.Empty)
            {
                message.ChannelId = channelId;
            }

            await db.Messages.AddAsync(message);

            await db.SaveChangesAsync();

            return(message.MsgId);
        }
        private void MarkDeadNodes()
        {
            var expiredSuspects = _nodeRepository
                                  .Get()
                                  .Where(x => x.Status == SwimNodeStatus.Suspicious && (DateTime.UtcNow - x.SuspiciousTimestamp) > new TimeSpan(0, 1, 0))
                                  .ToList();

            foreach (var expiredSuspect in expiredSuspects)
            {
                _logger.LogInformation($"Marking {expiredSuspect.Endpoint} as DEAD and Broadcasting");

                expiredSuspect.SetStatus(SwimNodeStatus.Dead);

                AddBroadcastMessage(new DeadMessage(Ulid.NewUlid(), _swimProtocolProvider.Node, expiredSuspect));

                _nodeRepository.Upsert(expiredSuspect);
            }
        }
예제 #11
0
        // Commands

        public virtual async Task <ChatMessage> Post(
            Chat.PostCommand command, CancellationToken cancellationToken = default)
        {
            var(session, chatId, text) = command;
            var context = CommandContext.GetCurrent();

            if (Computed.IsInvalidating())
            {
                var invChatMessage = context.Operation().Items.Get <ChatMessage>();
                PseudoGetTail(chatId, default).Ignore();
                return(null !);
            }

            var user = await AuthService.GetUser(session, cancellationToken);

            user = user.MustBeAuthenticated();
            var userId = long.Parse(user.Id);
            var cp     = await GetPermissions(session, chatId, cancellationToken);

            if ((cp & ChatPermission.Write) != ChatPermission.Write)
            {
                throw new SecurityException("You can't post to this chat.");
            }
            var parsedMessage = await MessageParser.Parse(text, cancellationToken);

            await using var dbContext = await CreateCommandDbContext(cancellationToken);

            var now         = Clock.Now;
            var chatMessage = new ChatMessage(Ulid.NewUlid().ToString(), chatId)
            {
                UserId    = userId,
                CreatedAt = now,
                EditedAt  = now,
                Text      = parsedMessage.Format(),
            };
            var dbChatMessage = new DbChatMessage();

            dbChatMessage.UpdateFrom(chatMessage);
            dbContext.Add(dbChatMessage);
            await dbContext.SaveChangesAsync(cancellationToken);

            context.Operation().Items.Set(chatMessage);
            return(chatMessage);
        }
예제 #12
0
        public void DeserializeExceptionTest()
        {
            var target = Ulid.NewUlid();
            var src    = $"{{\"value\": \"{target.ToString().Substring(1)}\"}}";

            try
            {
                var parsed = JsonSerializer.Deserialize <TestSerializationClass>(src, GetOptions());
                throw new Exception("Test should fail here: no exception were thrown");
            }
            catch (JsonException)
            {
                // silentlly success
            }
            catch (Exception e)
            {
                throw new Exception($"Test should fail here: Got exception {e}");
            }
        }
예제 #13
0
        private ImmutableList <Todo> _store = ImmutableList <Todo> .Empty; // It's always sorted by Id though

        // Commands

        public virtual Task <Todo> AddOrUpdate(AddOrUpdateTodoCommand command, CancellationToken cancellationToken = default)
        {
            var(session, todo) = command;
            if (Computed.IsInvalidating())
            {
                TryGet(session, todo.Id, CancellationToken.None).Ignore();
                PseudoGetAllItems(session).Ignore();
                return(Task.FromResult(default(Todo) !));
            }

            if (string.IsNullOrEmpty(todo.Id))
            {
                todo = todo with {
                    Id = Ulid.NewUlid().ToString()
                }
            }
            ;
            _store = _store.RemoveAll(i => i.Id == todo.Id).Add(todo);
            return(Task.FromResult(todo));
        }
예제 #14
0
        public async Task <IActionResult> UploadAttachment(
            [FromQuery] string filename
            )
        {
            var _contentLength = Request.ContentLength;

            if (_contentLength == null)
            {
                return(StatusCode(StatusCodes.Status411LengthRequired));
            }
            if (_contentLength > MaxAllowedUploadSize)
            {
                return(StatusCode(StatusCodes.Status413PayloadTooLarge));
            }
            long contentLength = _contentLength.Value;

            var contentType = Request.ContentType;

            if (contentType == null)
            {
                contentType = MimeTypes.GetMimeType(filename);
            }

            var  fileStream = Request.Body;
            Ulid id         = Ulid.NewUlid();
            var  path       = await this.oss.PutAttachment(id, filename, fileStream, contentLength, contentType);

            var att = new HatoAttachment()
            {
                AttachmentId = id,
                Filename     = filename,
                Url          = path,
                ContentType  = contentType,
                Size         = contentLength,
                IsAvailable  = true
            };

            await this.db.AddAttachmentEntry(att);

            return(Created(path, att));
        }
예제 #15
0
        public void Ulid_CompareTo_WorksCorrectly()
        {
            var a = Ulid.NewUlid(KNOWNTIMESTAMP_DTO, new FakeUlidRng());
            var b = Ulid.NewUlid(KNOWNTIMESTAMP_DTO, new FakeUlidRng());

            var c = Ulid.NewUlid(KNOWNTIMESTAMP_DTO.AddMilliseconds(-1), new FakeUlidRng());
            var d = Ulid.NewUlid(KNOWNTIMESTAMP_DTO.AddMilliseconds(+1), new FakeUlidRng());

            Assert.AreEqual(0, a.CompareTo(b));
            Assert.AreEqual(1, a.CompareTo(c));
            Assert.AreEqual(-1, a.CompareTo(d));

            var rmin  = a.ToByteArray(); rmin[15]--;
            var rplus = a.ToByteArray(); rplus[15]++;

            var e = new Ulid(rmin);
            var f = new Ulid(rplus);

            Assert.AreEqual(1, a.CompareTo(e));
            Assert.AreEqual(-1, a.CompareTo(f));
        }
예제 #16
0
        public void Ulid_TryParse_WorksCorrectly()
        {
            Assert.IsFalse(Ulid.TryParse("X", out var r1));
            Assert.AreEqual(Ulid.Empty, r1);

            Assert.IsFalse(Ulid.TryParse(string.Empty, out var r2));
            Assert.AreEqual(Ulid.Empty, r2);

            Assert.IsFalse(Ulid.TryParse(null, out var r3));
            Assert.AreEqual(Ulid.Empty, r3);

            Assert.IsTrue(Ulid.TryParse(Ulid.MinValue.ToString(), out var r4));
            Assert.IsTrue(Ulid.MinValue == r4);

            Assert.IsTrue(Ulid.TryParse(Ulid.MaxValue.ToString(), out var r5));
            Assert.IsTrue(Ulid.MaxValue == r5);

            var target = Ulid.NewUlid(KNOWNTIMESTAMP_DTO, new FakeUlidRng());

            Assert.IsTrue(Ulid.TryParse(KNOWNTIMESTAMP_STRING + KNOWNRANDOMSEQ_STRING, out var r6));
            Assert.AreEqual(r6, target);
        }
예제 #17
0
    private ImmutableList <Todo> _store = ImmutableList <Todo> .Empty; // It's always sorted by Id though

    // Commands

#pragma warning disable 1998
    public virtual async Task <Todo> AddOrUpdate(AddOrUpdateTodoCommand command, CancellationToken cancellationToken = default)
    {
        if (Computed.IsInvalidating())
        {
            return(null !);
        }

        var(session, todo) = command;
        if (string.IsNullOrEmpty(todo.Id))
        {
            todo = todo with {
                Id = Ulid.NewUlid().ToString()
            }
        }
        ;
        _store = _store.RemoveAll(i => i.Id == todo.Id).Add(todo);

        using var invalidating = Computed.Invalidate();
        _ = Get(session, todo.Id, CancellationToken.None);
        _ = PseudoGetAllItems(session);
        return(todo);
    }
예제 #18
0
        public Employee Generate(Company c)
        {
            var name            = RandomName();
            var experience      = RandomExperience();
            var base_efficiency = RandomEfficiency();
            var salary          = (decimal)RandomSalary(experience);
            var liveDuration    = RandomLiveDuration();
            var employee        = new Employee
            {
                id             = Ulid.NewUlid(),
                name           = name,
                baseEfficiency = base_efficiency,
                experience     = experience,
                salary         = salary,
                liveTime       = liveDuration + c.ut,
                abilities      = new Dictionary <string, float>
                {
                    ["java"] = 1.0f
                }
            };

            return(employee);
        }
예제 #19
0
        public void Ulid_RandomIs_Immutable()
        {
            Ulid.MinValue.Random[0] = 42;
            Assert.AreEqual(0, Ulid.MinValue.Random[0]);

            Ulid.MaxValue.Random[0] = 42;
            Assert.AreEqual(255, Ulid.MaxValue.Random[0]);

            Ulid.Empty.Random[0] = 42;
            Assert.AreEqual(0, Ulid.Empty.Random[0]);

            var u = Ulid.NewUlid(new FakeUlidRng());

            u.Random[0] = 42;
            Assert.AreEqual(107, u.Random[0]);

            // Make sure when we pass an array into the constructor we cannot modify the source array (constructor copies, doesn't use reference)
            var x = Ulid.MaxValue.ToByteArray();
            var t = new Ulid(x);

            x[6] = 0;
            Assert.AreEqual(255, t.Random[0]);
        }
예제 #20
0
파일: Program.cs 프로젝트: RobThree/NUlid
        static void Main()
        {
            var simplerng          = new SimpleUlidRng();
            var csrng              = new CSUlidRng();
            var simplemonotonicrng = new MonotonicUlidRng(simplerng);
            var csmonotonicrng     = new MonotonicUlidRng(csrng);
            var plainrng           = new Random();

            var pt = new SimpleBencher(10000000);

            //pt.BenchRunning += (s, e) => Console.WriteLine($"Running {e.Title}, {e.Iterations:N0} iterations...");
            //pt.BenchWarmup += (s, e) => Console.WriteLine($"Warmup {e.Title}, {e.Iterations:N0} iterations...");
            pt.BenchComplete += (s, e) => Console.WriteLine($"Completed {e.Title,-40}: {e.Result.OperationsPerSecond(),15:N0}/sec.");

            var d          = DateTimeOffset.Now;
            var benchtests = new IBench[] {
                new ForBench("Guid.NewGuid()", () => Guid.NewGuid()),
                new ForBench("Ulid.NewUlid(SimpleUlidRng)", () => Ulid.NewUlid(simplerng)),
                new ForBench("Ulid.NewUlid(CSUlidRng)", () => Ulid.NewUlid(csrng)),
                new ForBench("Ulid.NewUlid(SimpleMonotonicUlidRng)", () => Ulid.NewUlid(simplemonotonicrng)),
                new ForBench("Ulid.NewUlid(CSMonotonicUlidRng)", () => Ulid.NewUlid(csmonotonicrng)),
                new ForEachBench <string>("Guid.Parse(string)", (i) => Guid.Parse(i), (i) => Enumerable.Range(0, i).Select(n => Guid.NewGuid().ToString())),
                new ForEachBench <string>("Ulid.Parse(string)", (i) => Ulid.Parse(i), (i) => Enumerable.Range(0, i).Select(n => Ulid.NewUlid().ToString())),
                new ForEachBench <Guid>("Guid.ToString()", (i) => i.ToString(), (i) => Enumerable.Range(0, i).Select(n => Guid.NewGuid())),
                new ForEachBench <Ulid>("Ulid.ToString()", (i) => i.ToString(), (i) => Enumerable.Range(0, i).Select(n => Ulid.NewUlid())),
                new ForEachBench <byte[]>("new Guid(byte[])", (i) => new Guid(i), (i) => Enumerable.Range(0, i).Select(n => { var b = new byte[16]; plainrng.NextBytes(b); return(b); })),
                new ForEachBench <byte[]>("new Ulid(byte[])", (i) => new Ulid(i), (i) => Enumerable.Range(0, i).Select(n => { var b = new byte[16]; plainrng.NextBytes(b); return(b); })),
                new ForEachBench <Guid>("Guid.ToByteArray()", (i) => i.ToByteArray(), (i) => Enumerable.Range(0, i).Select(n => Guid.NewGuid())),
                new ForEachBench <Ulid>("Ulid.ToByteArray()", (i) => i.ToByteArray(), (i) => Enumerable.Range(0, i).Select(n => Ulid.NewUlid())),
                new ForEachBench <Ulid>("Ulid.ToGuid()", (i) => i.ToGuid(), (i) => Enumerable.Range(0, i).Select(n => Ulid.NewUlid())),
                new ForEachBench <Guid>("new Ulid(Guid)", (i) => new Ulid(i), (i) => Enumerable.Range(0, i).Select(n => Guid.NewGuid())),
            };

            var results = pt.BenchMark(benchtests).ToArray();

            Console.WriteLine("Done.");
        }
예제 #21
0
        public void AddRemoveEmployeeTest()
        {
            var newEmployee = new Employee()
            {
                id             = Ulid.NewUlid(),
                name           = "Someone Else",
                baseEfficiency = 1,
                abilities      = new Dictionary <string, float>()
                {
                    ["csharp"] = 1.0f
                },
                isWorking = false
            };
            var oldEmployeeCount = mockCompany.employees.Count;

            mockCompany.AddEmployee(newEmployee);

            Assert.That(mockCompany.employees.Count, Is.EqualTo(oldEmployeeCount + 1), "Employee count should increase after adding");
            Assert.That(mockCompany.employees.Contains(newEmployee), "The employee should be added");

            Assert.That(mockCompany.RemoveEmployee(newEmployee.id), Is.True, "The employee should be removed by this call");
            Assert.That(!mockCompany.employees.Contains(newEmployee), "The employee should be removed");
            Assert.That(mockCompany.RemoveEmployee(newEmployee.id), Is.False, "The employee should not be avaliable");
        }
예제 #22
0
        public override Task <RegisterResponse> Register(RegisterRequest request, ServerCallContext context)
        {
            User user = _userService.GetFromUsername(request.Username);

            if (user != null)
            {
                throw new RpcException(new Status(StatusCode.AlreadyExists, "Username already exists"));
            }
            user = new User()
            {
                Id        = ObjectId.GenerateNewId().ToString(),
                Hash      = request.Hash,
                Publickey = request.Publickey,
                Salt      = request.Salt,
                Token     = Ulid.NewUlid().ToString(),
                Username  = request.Username
            };
            _userService.Create(user);
            return(Task.FromResult(new RegisterResponse
            {
                Id = user.Id,
                Token = user.Token
            }));
        }
예제 #23
0
        public void New_ByteEquals_ToString_Equals()
        {
            for (int i = 0; i < 100; i++)
            {
                {
                    var ulid  = Ulid.NewUlid();
                    var nulid = new NUlid.Ulid(ulid.ToByteArray());

                    ulid.ToByteArray().Should().BeEquivalentTo(nulid.ToByteArray());
                    ulid.ToString().Should().Be(nulid.ToString());
                    ulid.Equals(ulid).Should().BeTrue();
                    ulid.Equals(Ulid.NewUlid()).Should().BeFalse();
                }
                {
                    var nulid = NUlid.Ulid.NewUlid();
                    var ulid  = new Ulid(nulid.ToByteArray());

                    ulid.ToByteArray().Should().BeEquivalentTo(nulid.ToByteArray());
                    ulid.ToString().Should().Be(nulid.ToString());
                    ulid.Equals(ulid).Should().BeTrue();
                    ulid.Equals(Ulid.NewUlid()).Should().BeFalse();
                }
            }
        }
        public Contract Generate(Company c)
        {
            var contractor = RandomContractor();
            // var nameDescriptionPair = RandomNameDescription(contractor);
            var contract = new Contract
            {
                id                      = Ulid.NewUlid(),
                status                  = ContractStatus.Open,
                contractor              = contractor,
                name                    = title.Replace("$contractor", contractor),
                description             = description.Replace("$contractor", contractor),
                startTime               = c.ut,
                LiveDuration            = RandomLiveDuration(),
                LimitDuration           = durationCurve.Evaluate(c.reputation),
                totalWorkload           = workloadCurve.Evaluate(c.reputation),
                depositReward           = baseDepositReward.Copy(),
                breakContractPunishment = baseAbortPunishment.Copy(),
                completeReward          = baseFinishReward.Copy(),
                techStack               = "java",
            };

            // MultiplyPow(ref contract.depositReward.reputation, );
            return(contract);
        }
예제 #25
0
        public void Create_Entity_Custom_Base_Success()
        {
            var person = new Grape(new GrapeId(Ulid.NewUlid()));

            Assert.NotNull(person);
        }
예제 #26
0
        public string GenerateNew <T>()
        {
            var id = Ulid.NewUlid().ToString();

            return(this.AddCollectionName <T>(id));
        }
예제 #27
0
 public string Ulid_()
 {
     return(Ulid.NewUlid().ToString());
 }
예제 #28
0
 public BaseEntity()
 {
     Id = Ulid.NewUlid().ToString();
 }
예제 #29
0
파일: IdFactory.cs 프로젝트: haefele/Helpo
 public string GenerateId()
 {
     return(Ulid.NewUlid().ToString());
 }
예제 #30
0
        public void NewUlid_Uses_SpecifiedRNG()
        {
            var target = Ulid.NewUlid(new FakeUlidRng());

            CollectionAssert.AreEqual(FakeUlidRng.DEFAULTRESULT.ToArray(), target.Random);
        }