Esempio n. 1
0
        public async Task <PaginatedItemsDto <UserViewModel> > GetUsersAsync(int pageIndex, int pageSize)
        {
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
            var channel = GrpcChannel.ForAddress(_grpcServerAddress);
            var client  = new Users.UsersClient(channel);
            PaginatedItemsResponse response;

            try
            {
                response = await client.GetUsersAsync(
                    new UsersRequest { PageIndex = pageIndex - 1, PageSize = pageSize });
            }
            finally
            {
                AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", false);
            }
            return(new PaginatedItemsDto <UserViewModel>
            {
                Count = response.Count,
                Data = response.Data
                       .Select(u => new UserViewModel {
                    Id = u.Id, UserName = u.UserName
                }),
                PageIndex = response.PageIndex,
                PageSize = response.PageSize
            });
        }
Esempio n. 2
0
        internal async Task <bool> LoginAsync(GrpcChannel channel, string userName, string password)
        {
            var client = new Users.UsersClient(channel);
            var input  = new LoginInput
            {
                Email    = userName,
                Password = password
            };
            var result = await client.LoginRequsetAsync(input);

            if (result.Id == 0)
            {
                return(false);
            }

            LoggedInUser.Instance.Id            = result.Id;
            LoggedInUser.Instance.FirstName     = result.FirstName;
            LoggedInUser.Instance.LastName      = result.LastName;
            LoggedInUser.Instance.Email         = result.Email;
            LoggedInUser.Instance.DirectManager = result.DirectManager;

            if (result.Permission.Equals(System.Enum.GetName(typeof(PermissionsEnum), PermissionsEnum.Employee)))
            {
                LoggedInUser.Instance.Permission = PermissionsEnum.Employee;
            }
            else
            {
                LoggedInUser.Instance.Permission = PermissionsEnum.Manager;
            }

            return(true);
        }
Esempio n. 3
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Calling a gRPC Service");
            var HttpClientHandler = new HttpClientHandler();

            HttpClientHandler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
            var httpClient = new HttpClient(HttpClientHandler);
            var channel    = GrpcChannel.ForAddress("https://localhost:5001", new GrpcChannelOptions {
                HttpClient = httpClient
            });
            var client = new Users.UsersClient(channel);

            try
            {
                UserRequest request = new UserRequest()
                {
                    CompanyId = 1
                };
                using (var call = client.getUsers(request))
                {
                    //stream
                    while (await call.ResponseStream.MoveNext(CancellationToken.None))
                    {
                        var currentUser = call.ResponseStream.Current;
                        Console.WriteLine(currentUser.FirstName + " " + currentUser.LastName + " is being fetched from the service.");
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Esempio n. 4
0
 public RealDataProvider()
 {
     _channel        = new Channel("127.0.0.1:50051", ChannelCredentials.Insecure);
     _authClient     = new Auth.AuthClient(_channel);
     _projectsClient = new Projects.ProjectsClient(_channel);
     _tasksClient    = new Tasks.TasksClient(_channel);
     _usersClient    = new Users.UsersClient(_channel);
 }
        public EventStoreUserManagerClient(CallInvoker callInvoker)
        {
            if (callInvoker == null)
            {
                throw new ArgumentNullException(nameof(callInvoker));
            }

            _client = new Users.UsersClient(callInvoker);
        }
Esempio n. 6
0
        internal async Task AddUpdateEventAsync(GrpcChannel channel, int employeeId)
        {
            var client = new Users.UsersClient(channel);
            var input  = new Int32Value
            {
                Value = employeeId
            };

            await client.AddUpdateEventAsync(input);
        }
Esempio n. 7
0
        internal async Task DeleteEmployeeAsync(GrpcChannel channel, int employeeId)
        {
            var client = new Users.UsersClient(channel);
            var input  = new PersonIdInput
            {
                PersonId = employeeId
            };

            await client.DeleteEmployeeAsync(input);
        }
Esempio n. 8
0
        internal async Task SendUpdateEventAsync(GrpcChannel channel, int userId)
        {
            var client       = new Users.UsersClient(channel);
            var updatesInput = new Int32Value
            {
                Value = userId
            };

            await client.AddUpdateEventAsync(updatesInput);
        }
        public async Task GetUsers_ReturnsAllUsers()
        {
            // Arrange
            var client = new Users.UsersClient(this.Channel);

            // Act
            GetUsersResponse response = await client.GetUsersAsync(new Empty());

            // Assert
            response.Users.Count.Should().Be(0);
        }
Esempio n. 10
0
        internal async Task <bool> IsMailExistAsync(GrpcChannel channel, string email)
        {
            var client = new Users.UsersClient(channel);
            var input  = new StringValue
            {
                Value = email
            };
            var result = await client.IsMailExistAsync(input);

            return(result.Value);
        }
Esempio n. 11
0
        internal async Task <bool> RequestUserUpdateAsync(GrpcChannel channel, int userId)
        {
            var client = new Users.UsersClient(channel);
            var input  = new Int32Value
            {
                Value = userId
            };
            var result = await client.RequestUserUpdateAsync(input);

            return(result.Value);
        }
Esempio n. 12
0
        public void TestUserService()
        {
            using var channel = GrpcChannel.ForAddress("http://localhost:7200");
            var client = new Users.UsersClient(channel);
            var reply  = client.GetUser(new UserRequest {
                UserName = "******", Password = "******"
            });

            Console.WriteLine("Users: " + reply.Id);
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
Esempio n. 13
0
        //public IQueryable<TUser> Users => _usersTable;

        #endregion

        #region | Constructors

        public UserStore(
            //TSession session,
            Users.UsersClient usersClient,
            ILogger <UserStore <TUser> > logger,
            IdentityErrorDescriber errorDescriber = null,
            GrpcErrorDescriber grpcErrorDescriber = null)
        {
            ErrorDescriber     = errorDescriber;
            GrpcErrorDescriber = grpcErrorDescriber;
            //Session = session ?? throw new ArgumentNullException(nameof(session));
            _client = usersClient;
            _logger = logger;
        }
Esempio n. 14
0
        static void Main(string[] args)
        {
            var channel = GrpcChannel.ForAddress("https://localhost:5001");
            var client  = new Users.UsersClient(channel);

            var res = client.GetUsers(new Empty());

            foreach (var user in res.Users)
            {
                Console.WriteLine($" User Id: {user.Id} | User Name: {user.Name}");
            }
            Console.ReadKey();
        }
Esempio n. 15
0
 public RoleStore(
     //TSession session,
     Users.UsersClient usersClient,
     ILoggerFactory loggerFactory,
     IdentityErrorDescriber errorDescriber = null,
     GrpcErrorDescriber grpcErrorDescriber = null)
 {
     ErrorDescriber     = errorDescriber;
     GrpcErrorDescriber = grpcErrorDescriber;
     //Session = session ?? throw new ArgumentNullException(nameof(session));
     _client = usersClient;
     //_logger = loggerFactory.CreateLogger(typeof(RoleStore<,>).GetTypeInfo().Name);
 }
Esempio n. 16
0
        public UserServiceRemote(ChannelBase channel)
        {
            _client = new Users.UsersClient(channel);

            var config = new MapperConfiguration(
                cfg =>
            {
                cfg.CreateMap <UserMessage, User>();
                cfg.CreateMap <User, UserMessage>();
                cfg.CreateMap <GetPaginatedUsersReply, PaginatedResponse <User> >();
            });

            _mapper = config.CreateMapper();
        }
Esempio n. 17
0
        internal async Task <ObservableCollection <IPerson> > GetEmployeesAsync(GrpcChannel channel, int managerId)
        {
            var client = new Users.UsersClient(channel);
            var input  = new PersonIdInput
            {
                PersonId = managerId
            };

            using var result = client.GetEmployees(input);
            var employees = new ObservableCollection <IPerson>();

            while (await result.ResponseStream.MoveNext())
            {
                if (result.ResponseStream.Current.Id == 0)
                {
                    return(null);
                }

                var permission = ConvertStringToPermissionsEnum(result.ResponseStream.Current.Permission);

                switch (permission)
                {
                case PermissionsEnum.Manager:
                    employees.Add(new Manager(permission,
                                              result.ResponseStream.Current.Id,
                                              result.ResponseStream.Current.DirectManager,
                                              result.ResponseStream.Current.FirstName,
                                              result.ResponseStream.Current.LastName,
                                              result.ResponseStream.Current.Email));
                    break;

                case PermissionsEnum.Employee:
                    employees.Add(new Employee(permission,
                                               result.ResponseStream.Current.Id,
                                               result.ResponseStream.Current.DirectManager,
                                               result.ResponseStream.Current.FirstName,
                                               result.ResponseStream.Current.LastName,
                                               result.ResponseStream.Current.Email));
                    break;
                }
            }

            return(employees);
        }
Esempio n. 18
0
        public static async Task <List <User> > GetUsersAsync(string deptName)
        {
            var usersChannel = GrpcChannel.ForAddress("https://localhost:5001");
            var usersClient  = new Users.UsersClient(usersChannel);

            // for some reason the async version never returns on my end in a class library
            //var usersReply = await usersClient.GetUsersAsync(
            //    new UsersRequest { DepartmentName = deptName });

            var usersReply = usersClient.GetUsers(new UsersRequest {
                DepartmentName = deptName
            });

            List <User> users = new List <User>();

            foreach (var item in usersReply.ListOfUsers)
            {
                users.Add(item);
            }

            return(await Task.FromResult(users));
        }
Esempio n. 19
0
        internal async Task <int> EmployeeRegisterAsync(GrpcChannel channel,
                                                        string firstName,
                                                        string lastName,
                                                        string email,
                                                        string hashedPassword,
                                                        PermissionsEnum permission,
                                                        int directManager)
        {
            var client = new Users.UsersClient(channel);
            var input  = new RegisterInput
            {
                FirstName     = firstName,
                LastName      = lastName,
                Email         = email,
                Password      = hashedPassword,
                Permission    = permission.ToString(),
                DirectManager = directManager
            };
            var result = await client.RegisterAsync(input);

            return(result.Value);
        }
Esempio n. 20
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            var channel = GrpcChannel.ForAddress("https://localhost:5001");
            var client  = new Greeter.GreeterClient(channel);
            var reply   = await client.SayHelloAsync(
                new HelloRequest { Name = "GreeterClient" });

            Console.WriteLine("Greeting: " + reply.Message);

            var usersChannel = GrpcChannel.ForAddress("https://localhost:5001");
            var usersClient  = new Users.UsersClient(usersChannel);
            var usersReply   = await usersClient.GetUsersAsync(
                new UsersRequest { DepartmentName = "sales" });

            foreach (var item in usersReply.ListOfUsers)
            {
                Console.WriteLine(item.Name);
            }

            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
Esempio n. 21
0
 internal LoginClient()
 {
     channel = new Channel(server, ChannelCredentials.Insecure);
     client  = new Users.UsersClient(channel);
 }
Esempio n. 22
0
        static async Task Vote(bool interactive)
        {
            var usersHost    = GetEnvVariableOrDefault("USERS_SERVICE_HOST", "localhost");
            var usersPort    = GetEnvVariableOrDefault("USERS_SERVICE_PORT", "50000");
            var recordHost   = GetEnvVariableOrDefault("RECORD_SERVICE_HOST", "localhost");
            var recordPort   = GetEnvVariableOrDefault("RECORD_SERVICE_PORT", "50000");
            var summaryHost  = GetEnvVariableOrDefault("SUMMARY_SERVICE_HOST", "localhost");
            var summaryPort  = GetEnvVariableOrDefault("SUMMARY_SERVICE_PORT", "50000");
            var channelUsers = GrpcChannel.ForAddress($"http://{usersHost}:{usersPort}", new GrpcChannelOptions()
            {
                Credentials = ChannelCredentials.Insecure
            });
            var channelRecord  = GrpcChannel.ForAddress($"http://{recordHost}:{recordPort}");
            var channelSummary = GrpcChannel.ForAddress($"http://{summaryHost}:{summaryPort}");
            var clientUsers    = new Users.UsersClient(channelUsers);
            var clientRecord   = new RecordingService.RecordingServiceClient(channelRecord);
            var clientSummary  = new PollSummaryService.PollSummaryServiceClient(channelSummary);


            var userName = "";

            if (interactive)
            {
                PrintPrompt("Enter a unique display name :");
                userName = Console.ReadLine();
            }
            else
            {
                var nameGenerator = new PersonNameGenerator();
                var firstName     = nameGenerator.GenerateRandomFirstName();
                var lastName      = nameGenerator.GenerateRandomLastName();
                userName = $"{firstName.Substring(0, 1).ToUpper()}. {lastName}";
                PrintInfo($"Using username : {userName}");
            }
            Console.WriteLine();

            PrintInfo($"Calling users service to create a new user {userName}");
            var userRequest = new UserRequest
            {
                Name = userName
            };
            var cts = new CancellationTokenSource();

            cts.CancelAfter(TimeSpan.FromSeconds(1));
            var userResponse = clientUsers.CreateUser(userRequest, new CallOptions(cancellationToken: cts.Token));

            if (userResponse.Error)
            {
                PrintError("Error while calling users service");
                PrintErrorAndExit(userResponse.ErrorMessage);
                return;
            }
            PrintInfo($"User created with code {userResponse.User.Code}");

            var userCode = userResponse.User.Code;

            PrintInfo("Getting open polls from record service");
            var pollsResponse = await clientRecord.GetPollsAsync(new Empty());

            if (pollsResponse.Error)
            {
                PrintErrorAndExit("Error while getting polls");
                return;
            }
            PrintInfo($"Got {pollsResponse.Polls.Count}");

            if (pollsResponse.Polls.Count == 0)
            {
                PrintInfo("Nothing to vote on :(");
                Console.WriteLine();
            }

            var random = new Random();

            foreach (var poll in pollsResponse.Polls)
            {
                Voting.Models.Option selectedOption;
                if (!interactive)
                {
                    PrintInfo($"Considering Poll : {poll.Summary}");
                    var randomOptionIdx = random.Next(poll.Options.Count);
                    selectedOption = poll.Options[randomOptionIdx];
                }
                else
                {
                    PrintInfo($"Cast your vote");
                    PrintPrompt(poll.Summary);
                    for (var i = 0; i < poll.Options.Count; i++)
                    {
                        PrintPrompt($"{i}) {poll.Options[i].Name}");
                    }
                    var selectedOptionInput = Console.ReadLine();
                    var selectedOptionIdx   = 0;
                    if (!int.TryParse(selectedOptionInput, out selectedOptionIdx))
                    {
                        PrintErrorAndExit("Invalid input");
                        return;
                    }

                    if (selectedOptionIdx < 0 && selectedOptionIdx >= poll.Options.Count)
                    {
                        PrintErrorAndExit("Invalid input");
                        return;
                    }

                    selectedOption = poll.Options[selectedOptionIdx];
                }

                var vote = new Voting.Models.Vote()
                {
                    OptionId = selectedOption.Id,
                    PollId   = poll.Id,
                    UserCode = userCode,
                    UserId   = userName,
                };
                PrintInfo($"Voting for option : {selectedOption.Name}");
                PrintInfo("Recording vote");

                var recordVoteResponse = await clientRecord.RecordVoteAsync(vote);

                if (recordVoteResponse.Error)
                {
                    PrintErrorAndExit($"Error while recording vote : {recordVoteResponse.ErrorMessage}");
                    return;
                }

                var response = await clientSummary.GetPollSummaryAsync(poll);

                // PrintInfo($"{response.Value.Poll.Summary} : {response.Value.TotalVotes}");
                Console.WriteLine();
            }
        }