Example #1
0
        // TODO: Refactor
        private IEnumerable <IGameObject> CreateLobbyGameObjects(IGameScene gameScene)
        {
            // Guardian Game Object #1
            {
                var id       = idGenerator.GenerateId();
                var position = new Vector2(-14.24f, -2.025f);
                var guardian = new GuardianGameObject(id, position, new IComponent[]
                {
                    new PresenceMapProvider(gameScene),
                    new GuardianIdleBehaviour(text: "Hello", time: 1)
                });

                yield return(guardian);
            }

            // Portal Game Object #2
            {
                var id       = idGenerator.GenerateId();
                var position = new Vector2(-17.125f, -1.5f);
                var portal   = new PortalGameObject(id, position, new IComponent[]
                {
                    new PresenceMapProvider(gameScene),
                    new PortalData(map: (byte)Map.TheDarkForest)
                });

                yield return(portal);
            }
        }
Example #2
0
        /// <inheritdoc/>
        protected override async Task <AuditEventModel> ProtectedHandleAsync(CreateAuditEventCommand request, CancellationToken cancellationToken)
        {
            XDASv2Net.Model.EventType parsedEventType = Enum.TryParse(request.Event.Action.Event.Name, out XDASv2Net.Model.EventType eventType)
                 ? eventType : XDASv2Net.Model.EventType.INVOKE_SERVICE;
            SubEventType parsedSubEventType = Enum.TryParse(request.Event.Action.SubEvent.Name, out SubEventType subEventType)
                 ? subEventType : SubEventType.None;

            var eventEntity = new AuditEventEntity()
            {
                Id              = idGenerator.GenerateId(),
                Timestamp       = DateTime.UtcNow,
                EventType       = (int)parsedEventType,
                SubEventType    = (int)parsedSubEventType,
                EventSerialized = serializer.Serialize(request.Event)
            };

            Context.AuditEventRepository.Add(eventEntity);

            await Context.SaveChangesAsync(cancellationToken);

            var result = AuditEventModel.Create(eventEntity, serializer);

            await Gateway.NotifyGroupsAsync(string.Empty, EventType.AuditEventCreated, result, cancellationToken);

            return(result);
        }
Example #3
0
 private void SetContentId <T>(T content) where T : class, IIdentifiable
 {
     if (string.IsNullOrEmpty(content.Id))
     {
         content.Id = _idGenerator.GenerateId();
     }
 }
Example #4
0
        public CommandResult Execute()
        {
            var playerCount = playerRepository.GetPlayerCount();
            var player      = new Player
            {
                Id   = idGenerator.GenerateId(new int[] { }),
                Name = nameGenerator.GenerateName(new string[] { }),
                X    = random.Next(mapSettings.MapWidth),
                Y    = random.Next(mapSettings.MapHeight),
                IsIt = playerCount == 0
            };

            playerRepository.Save(player);
            return(new CommandResult
            {
                Name = player.Name,
                Id = player.Id,
                IsIt = player.IsIt,
                MapWidth = mapSettings.MapWidth,
                MapHeight = mapSettings.MapHeight,
                X = player.X,
                Y = player.Y,
                Players = new List <PlayerResult>()
            });
        }
Example #5
0
        public int Post()
        {
            var randomId = gameIdGenerator.GenerateId();

            ludoGames.CreateGame(randomId);
            return(randomId);
        }
 private void ArrangeTestAccordingToItem(Item expectedItem)
 {
     _timeManager.GetCurrentTime().Returns(expectedItem.CreationTime);
     _guidGenerator.GenerateId().Returns(expectedItem.Id);
     _repository.AddItemAsync(ArgWrapper.IsItem(expectedItem))
     .Returns(Task.FromResult(expectedItem));
 }
Example #7
0
        /// <inheritdoc/>
        protected override async Task <EventModel> ProtectedHandleAsync(CreateEventCommand request, CancellationToken cancellationToken)
        {
            var appInfo = factory.Create();

            if (appInfo == null)
            {
                throw new UnexpectedNullException("The application information could not be retrieved.");
            }

            var eventEntity = new EventEntity()
            {
                Id              = idGenerator.GenerateId(),
                CreatedDate     = DateTime.UtcNow,
                ModifiedDate    = DateTime.UtcNow,
                ApiVersion      = appInfo.AppVersion,
                EventType       = (int)request.EventType,
                UserId          = request.UserId,
                EventSerialized = serializer.Serialize(request.Event)
            };

            Context.EventRepository.Add(eventEntity);

            await Context.SaveChangesAsync(cancellationToken);

            var result = EventModel.Create(eventEntity, serializer);

            return(result);
        }
Example #8
0
        private IngredientCommand CreateIngredientCommand(IngredientCreateRequest ingredientRequest)
        {
            var ingredientCommand = new IngredientCommand {
                Id = m_idGenerator.GenerateId(), Name = ingredientRequest.Name, Description = ingredientRequest.Description
            };

            return(ingredientCommand);
        }
Example #9
0
        private static TimeSpan Benchmark <T>(IIdGenerator <T> generator, int iterations)
        {
            // warm up
            for (int i = 0; i < 1024 * 16; i++)
            {
                generator.GenerateId();
            }

            Stopwatch stopwatch = Stopwatch.StartNew();

            for (int i = 0; i < iterations; i++)
            {
                generator.GenerateId();
            }
            stopwatch.Stop();
            return(stopwatch.Elapsed);
        }
 private void CreateTestData()
 {
     for (var i = 0; i < __maxNoOfDocuments; i++)
     {
         _collection.Insert(new C {
             Id = i, Guid = (Guid)_generator.GenerateId(null, null)
         });
     }
     _collection.EnsureIndex("Guid");
 }
Example #11
0
 private void EnsureIdExists <T>(params T[] contents) where T : IIdentifiable
 {
     foreach (var content in contents)
     {
         if (string.IsNullOrWhiteSpace(content.Id))
         {
             content.Id = _idGenerator.GenerateId();
         }
     }
 }
Example #12
0
        private TagCommand CreateTagCommand(TagCreateRequest tagRequest)
        {
            var tagCommand = new TagCommand
            {
                Id   = m_idGenerator.GenerateId(),
                Name = tagRequest.Name
            };

            return(tagCommand);
        }
Example #13
0
        private static void GenerateIdIfNeeded(object entity, IEntityConfig entityConfiguration, IIdGenerator idGenerator)
        {
            var id = entityConfiguration.GetId(entity);

            if (id == null)
            {
                var generatedId = idGenerator.GenerateId();
                Debug.Assert(!string.IsNullOrEmpty(generatedId));
                entityConfiguration.SetId(entity, generatedId);
            }
        }
Example #14
0
        /// <inheritdoc/>
        public async Task <IdentityResult> CreateAsync(TUser user, CancellationToken cancellationToken)
        {
            Ensure.ArgumentNotNull(user, nameof(user));

            user.Id           = idGenerator.GenerateId();
            user.CreatedDate  = DateTime.UtcNow;
            user.ModifiedDate = DateTime.UtcNow;

            context.UserRepository.Add(user);
            await context.SaveChangesAsync(cancellationToken);

            return(IdentityResult.Success);
        }
        private Item CreateItem(string text)
        {
            var currentTime = _timeManager.GetCurrentTime();
            var id          = _guidGenerator.GenerateId();

            return(new Item
            {
                Id = id,
                Text = text,
                CreationTime = currentTime,
                LastUpdateTime = currentTime
            });
        }
Example #16
0
        private DishCommand CreateDishCommand(DishCreateRequest dishRequest)
        {
            var dishCommand = new DishCommand {
                Id          = m_idGenerator.GenerateId(),
                Name        = dishRequest.Name,
                Description = dishRequest.Description,
                Recipe      = dishRequest.Recipe,
                Difficulty  = dishRequest.Difficulty,
                Duration    = dishRequest.Duration,
                Author      = dishRequest.Author,
                TimeAdded   = DateTime.Today
            };

            return(dishCommand);
        }
        public async Task <MovieId> AddMovie(MovieToSeeModel movie, CancellationToken cancellationToken)
        {
            var document = movie.ToDocument();

            document.Id = idGenerator.GenerateId();

            var insertOptions = new InsertOneOptions
            {
                BypassDocumentValidation = false,
            };

            await collection.InsertOneAsync(document, insertOptions, cancellationToken);

            return(document.Id.ToMovieId());
        }
Example #18
0
        public async Task AddTagsToDish(DishTagCreateRequest dishTagCreateRequest)
        {
            var dishTagCommands = new List <DishTagCommand>();

            foreach (var tagId in dishTagCreateRequest.TagIds)
            {
                dishTagCommands.Add(new DishTagCommand
                {
                    Id         = m_idGenerator.GenerateId(),
                    Dish_id_fk = dishTagCreateRequest.DishId,
                    Tag_id_fk  = tagId
                });
            }
            await m_commandExecutor.ExecuteAsync(dishTagCommands.AsEnumerable());
        }
Example #19
0
        public async Task <string> CreateRole(string roleName, CancellationToken cancellationToken)
        {
            var newRole = identityRoleFactory.CreateRole(roleName);

            newRole.Id = idGenerator.GenerateId();

            var result = await roleManager.CreateAsync(newRole);

            if (!result.Succeeded)
            {
                throw new UserManagementException($"Failed to create role {roleName}. {result}");
            }

            return(newRole.Id.ToString());
        }
Example #20
0
        public async Task <string> CreateUser(NewUserModel user, CancellationToken cancellationToken)
        {
            var userEmail = user.Email;

            var newUser = identityUserFactory.CreateUser(userEmail);

            newUser.Id    = idGenerator.GenerateId();
            newUser.Email = userEmail;

            var result = await userManager.CreateAsync(newUser, user.Password);

            if (!result.Succeeded)
            {
                throw new UserManagementException($"Failed to create the user. {result}");
            }

            return(newUser.Id.ToString());
        }
Example #21
0
        public async Task AddIngredientsToDish(int dishId, DishIngredientCreateRequest[] dishIngredients)
        {
            List <DishIngredientCommand> dishIngredientCommands = new List <DishIngredientCommand>();

            foreach (var dishIngredient in dishIngredients)
            {
                dishIngredientCommands.Add(new DishIngredientCommand
                {
                    Id               = m_idGenerator.GenerateId(),
                    Dish_id_fk       = dishId,
                    Ingredient_id_fk = dishIngredient.IngredientId,
                    Unit             = dishIngredient.Unit,
                    Amount           = dishIngredient.Amount,
                    Comment          = dishIngredient.Comment
                });
            }

            await m_commandExecutor.ExecuteAsync(dishIngredientCommands.AsEnumerable());
        }
        /// <inheritdoc/>
        protected override async Task <ProcessResultModel> ProtectedHandleAsync(ProcessPathCommand request, CancellationToken cancellationToken)
        {
            var result = await imageService.ProcessAsync(request, cancellationToken);

            var entity = new ResultEntity()
            {
                Id               = idGenerator.GenerateId(),
                CreatedDate      = DateTime.UtcNow,
                ModifiedDate     = DateTime.UtcNow,
                Version          = result.Version,
                JsonFilename     = result.JsonFilename,
                ResultType       = (int)ResultType.ProcessResult,
                ResultSerialized = serializer.Serialize(result)
            };

            Context.ResultRepository.Add(entity);

            await Context.SaveChangesAsync(cancellationToken);

            return(ProcessResultModel.Create(entity, serializer));
        }
        private void Handle(DistributedActorTableMessage <TKey> .Create m)
        {
            if (_stopping)
            {
                return;
            }

            // decide ID (if provided, use it, otherwise generate new one)

            TKey id;

            if (m.Id.Equals(default(TKey)) == false)
            {
                if (_actorMap.ContainsKey(m.Id))
                {
                    Sender.Tell(new DistributedActorTableMessage <TKey> .CreateReply(m.Id, null));
                    return;
                }
                id = m.Id;
            }
            else
            {
                if (_idGenerator == null)
                {
                    _log.Error("I don't have ID Generator.");
                    Sender.Tell(new DistributedActorTableMessage <TKey> .CreateReply(m.Id, null));
                    return;
                }

                id = _idGenerator.GenerateId();
                if (_actorMap.ContainsKey(id))
                {
                    _log.Error($"ID generated by generator is duplicated. ID={id}, Actor={_actorMap[id]}");
                    Sender.Tell(new DistributedActorTableMessage <TKey> .CreateReply(m.Id, null));
                    return;
                }
            }

            CreateActor(RequestType.Create, id, m.Args);
        }
Example #24
0
        /// <inheritdoc/>
        protected override async Task <TokenModel> ProtectedHandleAsync(CreateRefreshTokenCommand request, CancellationToken cancellationToken)
        {
            processMutex = new Mutex(false, this.GetMethodName());

            return(await processMutex.Execute(new TimeSpan(0, 0, 2), async() =>
            {
                var userId = Guid.Parse(request.UserId);

                var user = await Context.UserRepository.GetFirstOrDefaultAsync(e => e.Id == userId, cancellationToken);
                if (user == null)
                {
                    throw new UnexpectedNullException("User not found.");
                }

                // Make sure the amount of valid refresh tokens for a single user don't exceed the limit
                var tokens = Context.TokenRepository.GetQuery().Where(e => e.UserId == userId);
                if (tokens.Count() >= configuration.Options.AuthOptions.MaxRefreshTokens)
                {
                    var unusedToken = tokens.OrderBy(e => e.LastUsedDate).FirstOrDefault();
                    Context.TokenRepository.Remove(unusedToken);
                }

                var token = new TokenEntity()
                {
                    Id = idGenerator.GenerateId(),
                    CreatedDate = DateTime.UtcNow,
                    LastUsedDate = DateTime.UtcNow,
                    UserId = Guid.Parse(request.UserId),
                    TokenValue = request.Token
                };

                Context.TokenRepository.Add(token);

                await Context.SaveChangesAsync(cancellationToken);

                return TokenModel.Create(token);
            }));
        }
Example #25
0
        public async Task <StoredUrl> PostUrlAsync(string value)
        {
            if (InMemoryStore == null)
            {
                throw new Exception("Internal Memory invalid state");
            }

            var    retryCount = 0;
            string id;
            bool   unique = false;

            do
            {
                id = IdGenerator.GenerateId();
                if (!InMemoryStore.ContainsKey(id))
                {
                    unique = true;
                    break;
                }
                retryCount++;
            } while (retryCount < IdCreationRetryCount);

            if (!unique)
            {
                throw new Exception("unable to generate unique ID. all of them are used up :/");
            }

            var internalUrl = new StoredUrl()
            {
                Url          = value,
                Id           = id,
                LastAccessed = DateTime.Now
            };

            InMemoryStore[id] = internalUrl;
            return(internalUrl);
        }
 public string GenerateId()
 {
     return(prefix + converter(baseGenerator.GenerateId()));
 }
Example #27
0
 public OrderResult CreateOrder(Order order)
 {
     return(_executionEngines[_idGenerator.GetIdPrefix(order.Security)].CreateOrder(_idGenerator.GenerateId(order.Security), order));
 }
 public Guid GenerateSequentialGuid()
 {
     return(idGeneratorGuid.GenerateId());
 }
 public long GenerateSequential64Bit()
 {
     return(idGenerator64.GenerateId());
 }
 public int GenerateSequential32Bit()
 {
     return(idGenerator32.GenerateId());
 }