Beispiel #1
0
        public async Task <User> CreateUser()
        {
            _user.State.Create(this.GetPrimaryKey());
            await _user.WriteStateAsync();

            return(_user.State);
        }
Beispiel #2
0
        public Task AddUserId(Guid id)
        {
            if (_data.State.Add(id))
            {
                return(_data.WriteStateAsync());
            }

            return(Task.CompletedTask);
        }
Beispiel #3
0
 public async Task RegisterUser(UserAccountState userAccount)
 {
     if (_account.State.Equals(null))
     {
         throw new System.Exception("User Already Registered.");
     }
     _account.State = userAccount;
     await _account.WriteStateAsync();
 }
        public override async Task OnActivateAsync()
        {
            if (_conversationState.State.Phrases == null)
            {
                _conversationState.State.Phrases ??= new List <ConversationPhraseState>();
                await _conversationState.WriteStateAsync();
            }

            await base.OnActivateAsync();
        }
        private Task SaveStateTimer(object arg)
        {
            if (needSaveState)
            {
                needSaveState = false;
                return(state.WriteStateAsync());
            }

            return(Task.CompletedTask);
        }
Beispiel #6
0
 public async Task SetPublishingGrain(Type @interface, string grainId)
 {
     if (publishingGrainInitialized)
     {
         throw new Exception("Publishing grain can only be set once.");
     }
     _pubsub.State.GrainId   = grainId;
     _pubsub.State.Interface = @interface;
     await _pubsub.WriteStateAsync();
 }
Beispiel #7
0
        public async Task <bool> RegisterPatient(PatientInformation information)
        {
            if (state.State.Info != null)
            {
                return(false);
            }

            state.State.Info = information;
            await state.WriteStateAsync();

            return(true);
        }
        public async Task <bool> AddOrUpdate(string value, Guid grainKey)
        {
            if (_index.State.Index.ContainsKey(value))
            {
                return(false);
            }

            _index.State.Index[value] = grainKey;
            await _index.WriteStateAsync();

            return(true);
        }
Beispiel #9
0
        public async Task AddCommand(CommandOptions options)
        {
            options.Id = Guid.NewGuid();
            _logger.LogInformation("Adding bot command {commandId} ({commandAliases} - {commandType})", options.Id, string.Join(",", options.Aliases ?? new string[0]), options.Type);
            _channelBotState.State.Commands.Add(options.Id, options);
            var command = _registeredCommands[options.Type].Processor();

            var registration = _registeredCommands[options.Type];
            await _chatBot.RegisterMessageProcessor(registration.ProcessorType, options);

            await _channelBotState.WriteStateAsync();
        }
Beispiel #10
0
        public async Task <BookingResponse> BookRoom(string guestKey, DateTime fromDate, DateTime toDate, int nbrOfRooms)
        {
            var guest = GrainFactory.GetGrain <IGuestGrain>(guestKey);

            // check availability
            var availableRooms = await GetAvailableRooms(fromDate, toDate);

            if (availableRooms <= nbrOfRooms)
            {
                return new BookingResponse()
                       {
                           Sucessfull = false
                       }
            }
            ;
            //throw new NoRoomException() { HotelKey = this.GetPrimaryKeyString(), Date = toDate, RequestedRooms = nbrOfRooms };

            for (int d = 0; d < (toDate - fromDate).Days; d++)
            {
                DateTime date = fromDate.AddDays(d);
                _hotel.State.AvailableRooms[date] -= nbrOfRooms;
            }

            var bookingId    = Guid.NewGuid();
            var bookingGrain = GrainFactory.GetGrain <IBookingGrain>(bookingId);

            var booking = new Booking()
            {
                HotelKey = this.GetPrimaryKeyString(),
                GuestKey = guestKey,
                From     = fromDate,
                To       = toDate,
                NbrRooms = nbrOfRooms
            };

            await bookingGrain.Initialize(booking);

            await guest.AssignBooking(bookingId);

            if (_hotel.State.Bookings == null)
            {
                _hotel.State.Bookings = new List <Guid>();
            }
            _hotel.State.Bookings.Add(bookingId);

            await _hotel.WriteStateAsync();

            return(new BookingResponse()
            {
                BookingId = bookingId, Sucessfull = true
            });
        }
Beispiel #11
0
        async Task IChannelGrain.Activate(string userToken)
        {
            var userAuthenticated = Twitch.Authenticate()
                                    .FromOAuthToken(userToken)
                                    .Build();
            var userClient = TwitchAPIClient.CreateFromBase(_appClient, userAuthenticated);
            var validated  = await userClient.ValidateToken();

            if (validated == null || validated.UserId != _channelId || validated.ExpiresIn == 0)
            {
                throw new ArgumentException("Could not validate token");
            }
            _userClient = userClient;

            var channelInfoTask = _userClient.GetChannelInfoAsync(_channelId);
            List <HelixChannelModerator> moderators = new List <HelixChannelModerator>();
            var editorsTask = _userClient.GetHelixChannelEditorsAsync(_channelId);

            await foreach (var moderator in _userClient.EnumerateChannelModeratorsAsync(_channelId))
            {
                moderators.Add(moderator);
            }
            _channelState.State.BroadcasterToken = userToken;
            _channelState.State.Editors          = (await editorsTask).ToList();
            _channelState.State.Moderators       = moderators.ToList();
            await _channelState.WriteStateAsync();

            var editorsTasks = _channelState.State.Editors.Select(editor =>
                                                                  GrainFactory.GetGrain <IUserGrain>(editor.UserId).SetRole(new UserRole
            {
                Role        = ChannelRole.Editor,
                ChannelId   = _channelId,
                ChannelName = _channelInfo.BroadcasterName,
            })
                                                                  );

            var modsTasks = _channelState.State.Moderators.Select(moderator =>
                                                                  GrainFactory.GetGrain <IUserGrain>(moderator.UserId).SetRole(new UserRole
            {
                Role        = ChannelRole.Moderator,
                ChannelId   = _channelId,
                ChannelName = _channelInfo.BroadcasterName,
            })
                                                                  );

            await Task.WhenAll(editorsTasks);

            await Task.WhenAll(modsTasks);

            _channelInfo = await channelInfoTask;
            await RegisterEventSubSubscriptions(CancellationToken.None);
        }
Beispiel #12
0
    public async Task AddMessageAsync(string message)
    {
        _messageState.State.Add(message);
        await _messageState.WriteStateAsync();

        await _subsManager.Notify(s => s.OnMessage(message));
    }
        public async Task WritePlayerDetailAsync(string firstName, string lastName)
        {
            _playerState.State.FirstName = firstName;
            _playerState.State.LastName  = lastName;

            await _playerState.WriteStateAsync();
        }
        public async Task <ExecutionResult> Execute(string yaml, IParametersCollection parameters)
        {
            await _parameters.ReadStateAsync();

            var state = _parameters.State as IParametersCollection;


            var executionResult = new ExecutionResult(ref parameters) as IExecutionResult;

            var controller = new YamlScriptController();

            controller.QuestionCallback = (sender, args) =>
            {
                executionResult.Questions = args;
            };
            var result = controller.Parse(yaml);

            executionResult = new ExecutionResult(ref parameters);
            try
            {
                controller.ExecuteWorkflow(ref state, ref executionResult);
            }
            catch (UnresolvedException) { }
            _parameters.State = executionResult.Parameters as ParametersCollection;
            await _parameters.WriteStateAsync();

            return(executionResult as ExecutionResult);
        }
Beispiel #15
0
        /// <summary>
        /// 检查缓存
        /// </summary>
        /// <param name="forceUpdate"></param>
        /// <returns></returns>
        async Task <bool> IWMS.UpdateCache(bool forceUpdate, string dir)
        {
            await _tileCache.ReadStateAsync();

            if (forceUpdate)
            {
                Helper.OnCacheProcess += (int x, int y, int z, string pngId) =>
                {
                    if (!_tileCache.State.TILECACHE.Exists(t => t.pngId == pngId))
                    {
                        _tileCache.State.VERSION++;
                        _tileCache.State.TILECACHE.Add(new TileCache()
                        {
                            pngId = pngId,
                            x     = x,
                            y     = y,
                            z     = z
                        });
                    }
                };
                Helper.StartCache(dir);
            }
            await _tileCache.WriteStateAsync();

            return(true);
        }
        public async Task AddItem(DirectoryContentsItem item)
        {
            if (item is null)
            {
                throw new ArgumentNullException(nameof(item));
            }

            if (item.GrainId is null)
            {
                throw new ArgumentNullException(nameof(item.GrainId));
            }

            if (item.Interface is null)
            {
                throw new ArgumentNullException(nameof(item.Interface));
            }
            if (item.Created is null)
            {
                item.Created = DateTime.Now;
            }

            if (item.Modified is null)
            {
                item.Modified = item.Created;
            }

            if (item.Modified < item.Created)
            {
                throw new Exception("Content Modified date can not be set earlier than its Created date.");
            }

            _contents.State.Items.Add(item.GrainId, item);
            await _contents.WriteStateAsync();
        }
        public async Task OnNextAsync(UserRegisteredEvent item, StreamSequenceToken token = null)
        {
            var @event = new UserVerificationEvent()
            {
                Email  = item.Email,
                Status = UserVerificationStatusEnum.Verified
            };

            if (_verificationState.State.IsAlreadyVerified)
            {
                @event.Status = UserVerificationStatusEnum.Duplicate;
            }

            if (_blacklistedEmails.Get().Contains(item.Email))
            {
                @event.Status = UserVerificationStatusEnum.Blocked;

                _logger.LogWarning("Blacklisted user {email}", item.Email);
            }

            await _userVerificationStream.OnNextAsync(@event);

            _verificationState.State.IsAlreadyVerified = true;
            await _verificationState.WriteStateAsync();
        }
Beispiel #18
0
        public async Task ClearCustomizedCategoryDescription(string twitchCategory, string locale)
        {
            var key = new CategoryKey {
                TwitchCategoryId = twitchCategory, Locale = locale
            };

            if (_categoriesState.State.Descriptions.TryGetValue(key, out var category))
            {
                _categoriesState.State.Descriptions.Remove(key);
            }
            await _categoriesState.WriteStateAsync();

            if (twitchCategory == _channelInfo.GameId && locale == _channelInfo.BroadcasterLanguage)
            {
                await OnChannelUpdate(_channelInfo);
            }
        }
Beispiel #19
0
        private async Task AcquireNewIdRangeAsync()
        {
            _state.State.JobId++;
            await _state.WriteStateAsync();

            Current     = _options.Value.IdGeneratorConfig.ScaleSize * (_state.State.JobId - 1);
            _idRangeEnd = _options.Value.IdGeneratorConfig.ScaleSize * _state.State.JobId;
        }
Beispiel #20
0
        public async Task AddMessage(string message)
        {
            _log.LogInformation("Adding message: " + message);

            _state.State.Messages.Add(message);

            await _state.WriteStateAsync().ConfigureAwait(false);
        }
    public async Task <string> SayHello(string greeting)
    {
        _archive.State.Greetings.Add(greeting);

        await _archive.WriteStateAsync();

        return($"You said: '{greeting}', I say: Hello!");
    }
        async Task <int> IVote.CountMyVote()
        {
            _profile.State.Votes++;

            await _profile.WriteStateAsync();

            return(_profile.State.Votes);
        }
Beispiel #23
0
        public async Task OnConnect(Guid serverId)
        {
            _clientState.State.ServerId = serverId;
            _serverStream                   = _streamProvider.GetStream <ClientMessage>(_clientState.State.ServerId, Constants.SERVERS_STREAM);
            _serverDisconnectedStream       = _streamProvider.GetStream <Guid>(_clientState.State.ServerId, Constants.SERVER_DISCONNECTED);
            _serverDisconnectedSubscription = await _serverDisconnectedStream.SubscribeAsync(_ => OnDisconnect("server-disconnected"));

            await _clientState.WriteStateAsync();
        }
Beispiel #24
0
        /// <summary>
        /// 系统初始化校验
        /// </summary>
        /// <returns></returns>
        async Task <bool> ICustomer.InitialCheck()
        {
            try
            {
                await _groupManager.ReadStateAsync();

                //内部初始化最高级管理组
                if (!_groupManager.State.GropuCollection.Any())
                {
                    _groupManager.State.GropuCollection = new List <Group>()
                    {
                        new Group()
                        {
                            groupName   = "系统管理员",
                            description = "系统自动初始化新建的管理员,具有最高权限",
                            level       = 99,
                            apiList     = new List <string>()
                        }
                    };
                    await _groupManager.WriteStateAsync();
                }
                await _customerManager.ReadStateAsync();

                //内部初始化最高级管理员
                if (!_customerManager.State.CustomerCollection.Any())
                {
                    _customerManager.State.CustomerCollection = new List <Customer>()
                    {
                        new Customer()
                        {
                            userName      = "******",
                            userPwd       = "admin1",
                            groupObjectId = _groupManager.State.GropuCollection.Find(p => p.level == 99)?.objectId
                        }
                    };
                    await _customerManager.WriteStateAsync();
                }
                return(true);
            }
            catch
            {
                return(false);
            }
        }
        public async Task <string> SayHello(string name)
        {
            var now = DateTime.UtcNow;

            _helloWorldState.State.GreetingTimeUtc = now;

            await _helloWorldState.WriteStateAsync();

            return($@"Hello {name}! Sent at {now}.");
        }
Beispiel #26
0
        async Task <string> IHello.SayHello(string greeting)
        {
            _state.State.Counter++;

            await _state.WriteStateAsync();

            _logger.LogInformation($"\n SayHello message received: greeting = '{greeting}'");

            return($"\n Client said: '{greeting}', so HelloGrain says: Hello for the {_state.State.Counter} time.");
        }
Beispiel #27
0
        public async Task AddAsync(int count, string type = Constants.DefaultCounterType)
        {
            if (!_state.State.CountMap.TryGetValue(type, out _))
            {
                _state.State.CountMap[type] = 0;
            }

            _state.State.CountMap[type] += count;
            await _state.WriteStateAsync();
        }
        public async Task State_WriteAsync()
        {
            _state_poll = _state_poll.Clean();

            State.Primes = State.Primes.OrderBy(x => x).ToList();
            await WriteStateAsync();

            _aggregate.State.Order();
            await _aggregate.WriteStateAsync();
        }
        public Task Deposit(Operation operation)
        {
            if (operation.Amount <= 0)
            {
                throw new InvalidValueException(nameof(operation.Amount));
            }

            _account.State.Balance += operation.Amount;
            var operationHistory = new OperationHistoryEntry
            {
                Date        = _time.Now,
                Amount      = operation.Amount,
                Description = "Deposit",
                Tags        = operation.Tags
            };

            _account.State.History.Add(operationHistory);
            return(_account.WriteStateAsync());
        }
Beispiel #30
0
        public async Task <bool> RegisterUser(UserInformation info)
        {
            if (state.State.Information != null)
            {
                return(false);
            }
            state.State.Information = info;
            await state.WriteStateAsync();

            return(true);
        }