Exemplo n.º 1
0
        static async Task MainAsync()
        {
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine($"Azure Storage Queue, Lab01 - Producer ({Configs.PID})");

            await QueueHelpers.EnsureQueueCreatedAsync(QueueConst.Lab01QueueName);

            var queue = QueueHelpers.GetQueue(QueueConst.Lab01QueueName);

            for (var i = 0; i < QueueConst.Lab01MessagesToSend; i++)
            {
                var obj = new
                {
                    pid  = Configs.PID,
                    data = i
                };

                var message = new CloudQueueMessage(JsonConvert.SerializeObject(obj));

                Console.WriteLine($"Sending message to queue: {i}");

                await queue.AddMessageAsync(message);
            }

            Console.WriteLine("Done!");
            Console.ResetColor();
        }
Exemplo n.º 2
0
 public async Task <long> GetTotalItemCountAsync()
 {
     try
     {
         return(await _redisCache.ListLengthAsync(QueueHelpers.GetRedisKey <TData>())
                .ConfigureAwait(false));
     }
     catch (Exception e)
     {
         throw HandleException(nameof(GetManyAsync), "Error while fetching queue length.", e);
     }
 }
Exemplo n.º 3
0
 public async Task <IEnumerable <IQueueMessage <TData> > > GetManyAsync(long start = 0, long stop = -1)
 {
     try
     {
         return(await _redisCache.GetRangeAsync <QueueMessage <TData> >(QueueHelpers.GetRedisKey <TData>(), start, stop)
                .ConfigureAwait(false));
     }
     catch (Exception e)
     {
         throw HandleException(nameof(GetManyAsync), "Error while fetching messages from the queue.", e);
     }
 }
Exemplo n.º 4
0
 public async Task <IQueueMessage <TData> > DequeueAsync()
 {
     try
     {
         return(await _redisCache.ListLeftPopAsync <QueueMessage <TData> >(QueueHelpers.GetRedisKey <TData>())
                .ConfigureAwait(false));
     }
     catch (Exception e)
     {
         throw HandleException(nameof(DequeueAsync), "Error while fetching message from the queue.", e);
     }
 }
Exemplo n.º 5
0
        static async Task MainAsync()
        {
            Console.ForegroundColor = ConsoleColor.Magenta;
            Console.WriteLine($"Azure Storage Queue, Lab01 - Consumer ({Configs.PID})");

            await QueueHelpers.EnsureQueueCreatedAsync(QueueConst.Lab01QueueName);

            await Task.Factory.StartNew(ReceiveMessage);

            Console.WriteLine("Press 'enter' to close the app.");
            Console.ReadLine();

            Console.WriteLine("Done!");
            Console.ResetColor();
        }
Exemplo n.º 6
0
        public async Task <string> EnqueueAsync(TData data, string messageId = null)
        {
            try
            {
                var message = _messageFactory.Create(data, messageId);
                var key     = QueueHelpers.GetRedisKey <TData>();

                var count = await _redisCache.ListRightPushAsync(key, message).ConfigureAwait(false);

                _logger.LogDebug($"Current number of elements in the {key} queue: {count}");

                return(message.Id);
            }
            catch (Exception e)
            {
                throw HandleException(nameof(EnqueueAsync), "Error while adding message in the queue.", e);
            }
        }
Exemplo n.º 7
0
        static async Task ReceiveMessage()
        {
            var queue = QueueHelpers.GetQueue(QueueConst.Lab01QueueName);

            while (true)
            {
                var message = await queue.GetMessageAsync();

                if (message != null)
                {
                    Console.WriteLine($"Message received! Content: {message.AsString}");
                    await queue.DeleteMessageAsync(message);
                }
                else
                {
                    Console.WriteLine("No messages in the queue.");
                    await Task.Delay(TimeSpan.FromSeconds(2));
                }
            }
        }
Exemplo n.º 8
0
        public APIGatewayQuery(IBusClient queue, QueueHelpers helpers)
        {
            // The 'me' field allows the client to get the details of the
            // current profile based on the token.
            FieldAsync <ProfileType>(
                "me",
                resolve: async context =>
            {
                // Authenticate the user with their token
                var userId = (await helpers.AuthenticateFromContext(context)).UserId;
                // Get the profile object based on the UserId we got from
                // the token
                var thing = await helpers.GetProfileFromAccountId(userId);
                return(thing);
            }
                );

            // Allow the client to query any profile by its ID, UserID, or username
            FieldAsync <ProfileType>(
                "profile",
                arguments: new QueryArguments(
                    new QueryArgument <StringGraphType> {
                Name = "id"
            },
                    new QueryArgument <StringGraphType> {
                Name = "useraccountid"
            },
                    new QueryArgument <StringGraphType> {
                Name = "username"
            }
                    ),
                resolve: async context => {
                ProfileRequestMessage message;
                // Depending on which argument we got, get the Profile
                if (context.HasArgument("id"))
                {
                    message = new ProfileRequestMessage {
                        Id = Guid.Parse(context.GetArgument <string>("id")),
                    };
                }
                else if (context.HasArgument("useraccountid"))
                {
                    message = new ProfileRequestMessage {
                        UserAccountId = Guid.Parse(context.GetArgument <string>("useraccountid")),
                    };
                }
                else if (context.HasArgument("username"))
                {
                    message = new ProfileRequestMessage {
                        Username = context.GetArgument <string>("username"),
                    };
                }
                else
                {
                    throw new ArgumentNullException();
                }

                var responseTask = await queue.RequestAsync <ProfileRequestMessage, ResultMessage>(message);
                var profileData  = responseTask.data as ProfileData;
                // map the ProfileData object to a Profile object
                Profile p         = new Profile();
                p.Id              = profileData.Id;
                p.Username        = profileData.Username;
                p.TrainerCode     = profileData.TrainerCode;
                p.Level           = profileData.Level;
                p.TeamId          = profileData.TeamId;
                p.Gender          = profileData.Gender;
                p.FeaturedPokemon = new List <Guid>();
                p.FeaturedPokemon.Add(profileData.FeaturedPokemon1);
                p.FeaturedPokemon.Add(profileData.FeaturedPokemon2);
                p.FeaturedPokemon.Add(profileData.FeaturedPokemon3);
                return(p);
            }
                );

            // Get a pokemon by id, name or pokedex number
            FieldAsync <PokemonType>(
                "pokemon",
                arguments: new QueryArguments(
                    new QueryArgument <StringGraphType> {
                Name = "id"
            },
                    new QueryArgument <StringGraphType> {
                Name = "name"
            },
                    new QueryArgument <IntGraphType> {
                Name = "pokedexNumber"
            }
                    ),
                resolve: async context => {
                PokemonRequestMessage message;
                // make the request message based on the argument we got
                if (context.HasArgument("id"))
                {
                    message = new PokemonRequestMessage {
                        Id = Guid.Parse(context.GetArgument <string>("id")),
                    };
                }
                else if (context.HasArgument("name"))
                {
                    message = new PokemonRequestMessage {
                        Name = context.GetArgument <string>("name"),
                    };
                }
                else if (context.HasArgument("pokedexNumber"))
                {
                    message = new PokemonRequestMessage {
                        PokedexNumber = context.GetArgument <int>("pokedexNumber"),
                    };
                }
                else
                {
                    throw new ArgumentNullException();
                }
                var responseTask = await queue.RequestAsync <PokemonRequestMessage, ResultMessage>(message);
                var pokemonData  = responseTask.data as PokemonData;
                return(new Pokemon {
                    Id = pokemonData.Id,
                    Name = pokemonData.Name,
                    PokedexNumber = pokemonData.PokedexNumber,
                    SpriteImageUrl = pokemonData.SpriteImageUrl,
                    PogoImageUrl = pokemonData.PogoImageUrl,
                });
            }
                );

            // get a team by ID
            FieldAsync <TeamType>(
                "team",
                arguments: new QueryArguments(new QueryArgument <StringGraphType> {
                Name = "id"
            }),
                resolve: async context => {
                var responseTask = await queue.RequestAsync <TeamRequestMessage, ResultMessage>(
                    new TeamRequestMessage {
                    Id = Guid.Parse(context.GetArgument <string>("id")),
                }
                    );
                var teamData = responseTask.data as TeamData;
                return(new Team {
                    Id = teamData.Id,
                    Name = teamData.Name,
                    Color = teamData.Color,
                    ImageUrl = teamData.ImageUrl,
                });
            }
                );

            // Get a badge by ID
            FieldAsync <BadgeType>(
                "badge",
                arguments: new QueryArguments(new QueryArgument <StringGraphType> {
                Name = "id"
            }),
                resolve: async context => {
                var responseTask = await queue.RequestAsync <BadgeRequestMessage, ResultMessage>(
                    new BadgeRequestMessage {
                    Id = Guid.Parse(context.GetArgument <string>("id")),
                }
                    );
                var badgeData = responseTask.data as BadgeData;
                return(new Badge {
                    Id = badgeData.Id,
                    Name = badgeData.Name,
                    ImageUrl = badgeData.ImageUrl,
                });
            }
                );


            // Get a pokemonType by ID
            FieldAsync <PokemonTypeType>(
                "pokemonType",
                arguments: new QueryArguments(new QueryArgument <StringGraphType> {
                Name = "id"
            }),
                resolve: async context => {
                var responseTask = await queue.RequestAsync <PokemonTypeRequestMessage, ResultMessage>(
                    new PokemonTypeRequestMessage {
                    Id = Guid.Parse(context.GetArgument <string>("id")),
                }
                    );
                var typeData = responseTask.data as PokemonTypeData;
                return(new PokemonTypeInfo {
                    Id = typeData.Id,
                    Name = typeData.Name,
                });
            }
                );

            // Get all badges
            FieldAsync <ListGraphType <BadgeType> >(
                "badges",
                resolve: async context => {
                var responseTask = await queue.RequestAsync <BadgesRequestMessage, ResultMessage>(
                    new BadgesRequestMessage()
                    );
                var badgeDatas = responseTask.data as List <BadgeData>;
                var badges     = badgeDatas
                                 .Select(x => new Badge {
                    Id       = x.Id,
                    Name     = x.Name,
                    ImageUrl = x.ImageUrl,
                })
                                 .ToList();

                return(badges);
            }
                );

            // get all teams
            FieldAsync <ListGraphType <TeamType> >(
                "teams",
                resolve: async context => {
                var responseTask = await queue.RequestAsync <TeamsRequestMessage, ResultMessage>(
                    new TeamsRequestMessage()
                    );
                var teamDatas = responseTask.data as List <TeamData>;
                var teams     = teamDatas
                                .Select(x => new Team {
                    Id       = x.Id,
                    Name     = x.Name,
                    Color    = x.Color,
                    ImageUrl = x.ImageUrl,
                })
                                .ToList();

                return(teams);
            }
                );

            // get all pokemon (pluralized to pokemen)
            FieldAsync <ListGraphType <PokemonType> >(
                "pokemen",
                resolve: async context => {
                var responseTask = await queue.RequestAsync <PokemenRequestMessage, ResultMessage>(
                    new PokemenRequestMessage()
                    );
                var pokemanDatas = responseTask.data as List <PokemonData>;
                var pokemans     = pokemanDatas
                                   .Select(x => new Pokemon {
                    Id             = x.Id,
                    Name           = x.Name,
                    PokedexNumber  = x.PokedexNumber,
                    SpriteImageUrl = x.SpriteImageUrl,
                    PogoImageUrl   = x.PogoImageUrl,
                })
                                   .ToList();

                return(pokemans);
            }
                );

            // Get all pokemon types
            FieldAsync <ListGraphType <PokemonTypeType> >(
                "pokemonTypes",
                resolve: async context => {
                var responseTask = await queue.RequestAsync <PokemonTypesRequestMessage, ResultMessage>(
                    new PokemonTypesRequestMessage()
                    );
                var typeDatas = responseTask.data as List <PokemonTypeData>;
                var types     = typeDatas
                                .Select(x => new PokemonTypeInfo {
                    Id   = x.Id,
                    Name = x.Name,
                })
                                .ToList();

                return(types);
            }
                );
        }
        public APIGatewayMutation(IBusClient queue, QueueHelpers helpers)
        {
            // This field allows the client to update the current user's account
            // according to the token they are using.
            FieldAsync <ProfileType>(
                "updateMe",
                // As argument is a partial Profile object, see the
                // ProfileInputType class for details
                arguments: new QueryArguments(
                    new QueryArgument <NonNullGraphType <ProfileInputType> > {
                Name = "profile"
            }
                    ),
                resolve: async context =>
            {
                // Using the token in the context, authenticate the user and
                // get their UserId
                Guid userId = (await helpers.AuthenticateFromContext(context)).UserId;
                // Get the ProfileInputType argument as a Dictionary
                var newProfile = context.Arguments["profile"] as Dictionary <string, object>;

                // Helper function for getting a value from the argument, or
                // null if it isn't defined
                Func <string, object> getOrNull = prop => newProfile.ContainsKey(prop) ? newProfile[prop] : null;
                // Helper function for getting a Guid of the profile or null
                Func <string, Guid?> maybeGuid = field => getOrNull(field) != null
                                                    ? (Guid?)Guid.Parse(newProfile[field] as string)
                                                    : null;

                // Get the Profile ID of the account based on the UserId we
                // got earlier
                Guid id = (await helpers.GetProfileFromAccountId(userId)).Id;

                // Make a request to update the Profile with the new values.
                // Anything that is null won't be updated by the handler of
                // the message.
                var result = await queue.RequestAsync <ProfileUpdateRequestMessage, ResultMessage>(
                    new ProfileUpdateRequestMessage {
                    Id               = id,
                    PogoUsername     = getOrNull("username") as string,
                    PogoTeamId       = maybeGuid("teamId"),
                    PogoTrainerCode  = getOrNull("trainerCode") as string,
                    Gender           = getOrNull("gender") as int?,
                    PogoLevel        = getOrNull("level") as int?,
                    FeaturedPokemon1 = maybeGuid("featuredPokemon1"),
                    FeaturedPokemon2 = maybeGuid("featuredPokemon2"),
                    FeaturedPokemon3 = maybeGuid("featuredPokemon3"),
                }
                    );
                // If the response doesn't have the status Ok, the data
                // property is an exception object, so we just throw that
                if (result.status != ResultMessage.Status.Ok)
                {
                    throw (Exception)result.data;
                }

                // Get the profile again so we have the updated values and
                // return it so the client can get fields from it
                return(await helpers.GetProfileFromAccountId(userId));
            }
                );
        }