public async Task <SemesterStatusDto> GetSemesterStatusAsync(int curriculumId, int studentId)
        {
            _logger.LogInformation("get semester status of curriculum {0}", curriculumId);
            AppContext.SetSwitch(
                "System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);

            using var coreChannel = GrpcChannel.ForAddress(_configuration["CoreGrpc"]);

            var coreClient = new StudentService.StudentServiceClient(coreChannel);

            var semesterStatus = await coreClient.GetSemesterStatusAsync(new SemesterStatusRequest
            {
                CurriculumId = curriculumId,
                StudentId    = studentId
            });

            AppContext.SetSwitch(
                "System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", false);

            return(new SemesterStatusDto
            {
                CanTakeCurriculums = semesterStatus.CanTakeCurriculums,
                IsCurriculumSemesterValid = semesterStatus.IsCurriculumSemesterValid
            });
        }
Beispiel #2
0
        static void Main(string[] args)
        {
            Channel channel = new Channel("127.0.0.1:6789", ChannelCredentials.Insecure);
            var     client  = new StudentService.StudentServiceClient(channel);

            var reply = client.GetStudents(new StudentRequest {
            });

            string[] replyArray = reply.Info.Split(',');
            int      i          = 1;

            foreach (var student in replyArray)
            {
                if (student == "")
                {
                    continue;
                }

                Console.WriteLine($"Student #{i}: " + student);
                i++;
            }



            channel.ShutdownAsync().Wait();
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
Beispiel #3
0
        private async void btn_server_token_Click(object sender, EventArgs e)
        {
            //用于多线程通知
            CancellationTokenSource cts = new CancellationTokenSource();

            //1、创建grpc客户端
            using var channel = GrpcChannel.ForAddress("https://localhost:5001");
            var grpcClient = new StudentService.StudentServiceClient(channel);

            // 获取Token
            var token = await GetToken();

            // 将Token封装为Metadat和请求一起发送过去
            var headers = new Metadata
            {
                { "Authorization", $"Bearer {token}" }
            };

            //2、客户端一次请求,多次返回
            using var respStreamingCall = grpcClient.GetAllStudent(new QueryAllStudentRequest(), headers);
            //3、获取响应流
            var respStreaming = respStreamingCall.ResponseStream;

            //4、循环读取响应流,直到读完为止
            while (await respStreaming.MoveNext(cts.Token))
            {
                //5、取得每次返回的信息,并显示在文本框中
                var student = respStreaming.Current.Student;
                this.txt_result.Text += $"姓名:{student.UserName},年龄:{student.Age},地址:{student.Addr}\r\n";
            }
        }
 public GrpcClient()
 {
     AppContext.SetSwitch(
         "System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
     _channel = GrpcChannel.ForAddress("http://localhost:5000");
     _client  = new StudentService.StudentServiceClient(_channel);
 }
Beispiel #5
0
        public async Task <IEnumerable <MYMA.Models.Student> > GetItemsAsync()
        {
            List <MYMA.Models.Student> studentslist = new List <MYMA.Models.Student>();

            using var channel = GrpcChannel.ForAddress(serverAddress);
            var client = new StudentService.StudentServiceClient(channel);

            var result = await client.GetAllStudentsAsync(new Empty());

            foreach (var item in result.Students)
            {
                studentslist.Add(new Models.Student
                {
                    AdmisstionDate = item.AdmisstionDate.ToDateTime(),
                    DateofBirth    = item.DateofBirth.ToDateTime(),
                    Id             = item.Id,
                    FirstName      = item.FirstName,
                    LastName       = item.LastName,
                    MiddleName     = item.MiddleName,
                    MobileNumber   = item.MobileNumber,
                    UrduName       = item.UrduName
                });
            }
            return(studentslist);
        }
Beispiel #6
0
        public async Task <bool> DeleteItemAsync(string id)
        {
            using var channel = GrpcChannel.ForAddress(serverAddress);
            var client = new StudentService.StudentServiceClient(channel);

            await client.RemoveStudnetAsync(new StudentId { Id = id });

            return(await Task.FromResult(true));
        }
Beispiel #7
0
        private async Task <string> GetToken()
        {
            //1、创建grpc客户端
            using var channel = GrpcChannel.ForAddress("https://localhost:5001");
            var grpcClient = new StudentService.StudentServiceClient(channel);
            //2、发起请求
            var resp = await grpcClient.GetTokenAsync(new TokenRequest {
                UserName = "******",
                UserPwd  = "admin123"
            });

            return(resp.Token);
        }
Beispiel #8
0
        private void btn_sample_Click(object sender, EventArgs e)
        {
            //1、创建grpc客户端
            using var channel = GrpcChannel.ForAddress("https://localhost:5001");
            var grpcClient = new StudentService.StudentServiceClient(channel);
            //2、发起请求
            var resp = grpcClient.GetStudentByUserName(new QueryStudentRequest
            {
                UserName = txt_condition.Text.Trim()
            });

            //3、处理响应结果,将其显示在文本框中
            this.txt_result.Text = $"姓名:{resp.Student.UserName},年龄:{resp.Student.Age},地址:{resp.Student.Addr}";
        }
Beispiel #9
0
        private async void btn_client_Click(object sender, EventArgs e)
        {
            // 用于存放选择的文件路径
            string filePath = string.Empty;

            // 打开文件选择对话框
            if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                filePath = this.openFileDialog1.FileName;
            }
            if (string.IsNullOrEmpty(filePath))
            {
                this.txt_result.Text = "请选择文件";
                return;
            }
            //1、创建grpc客户端
            using var channel = GrpcChannel.ForAddress("https://localhost:5001");
            var grpcClient = new StudentService.StudentServiceClient(channel);
            //2、读取选择的文件
            FileStream fileStream = File.OpenRead(filePath);

            //3、通过客户端请求流将文件流发送的服务端
            using var call = grpcClient.UploadImg();
            var clientStream = call.RequestStream;

            //4、循环发送,指定发送完文件
            while (true)
            {
                // 一次最多发送1024字节
                byte[] buffer = new byte[1024];
                int    nRead  = await fileStream.ReadAsync(buffer, 0, buffer.Length);

                // 直到读不到数据为止,即文件已经发送完成,即退出发送
                if (nRead == 0)
                {
                    break;
                }
                // 5、将每次读取到的文件流通过客户端流发送到服务端
                await clientStream.WriteAsync(new UploadImgRequest { Data = ByteString.CopyFrom(buffer) });
            }
            // 6、发送完成之后,告诉服务端发送完成
            await clientStream.CompleteAsync();

            // 7、接收返回结果,并显示在文本框中
            var res = await call.ResponseAsync;

            this.txt_result.Text = $"上传返回Code:{res.Code},Msg:{res.Msg}";
        }
Beispiel #10
0
        private async void btn_double_Click(object sender, EventArgs e)
        {
            //用于多线程通知
            CancellationTokenSource cts = new CancellationTokenSource();
            //模拟通过请求流方式保存多个Student,同时通过响应流的方式返回存储结果
            List <Student> students = new List <Student> {
                new Student {
                    UserName = "******", Age = 20, Addr = "关注我一块学"
                },
                new Student {
                    UserName = "******", Age = 18, Addr = "关注Code综艺圈和我一块学"
                }
            };

            //1、创建grpc客户端
            using var channel = GrpcChannel.ForAddress("https://localhost:5001");
            var grpcClient = new StudentService.StudentServiceClient(channel);

            //2、分别取得请求流和响应流
            using var call = grpcClient.AddManyStudents();
            var requestStream  = call.RequestStream;
            var responseStream = call.ResponseStream;
            //3、开启一个线程专门用来接收响应流
            var taskResp = Task.Run(async() => {
                while (await responseStream.MoveNext(cts.Token))
                {
                    var student = responseStream.Current.Student;
                    // 将接收到结果在文本框中显示 ,多线程更新UI简单处理一下:Control.CheckForIllegalCrossThreadCalls = false;
                    this.txt_result.Text += $"保存成功,姓名:{student.UserName},年龄:{student.Age},地址:{student.Addr}\r\n";
                }
            });

            //4、通过请求流的方式将多条数据依次传到服务端
            foreach (var student in students)
            {
                // 每次发送一个学生请求
                await requestStream.WriteAsync(new AddStudentRequest
                {
                    Student = student
                });
            }
            //5、传送完毕
            await requestStream.CompleteAsync();

            await taskResp;
        }
Beispiel #11
0
        static async Task Main(string[] args)
        {
            try {
                var httpHandler = new HttpClientHandler
                {
                    ServerCertificateCustomValidationCallback =
                        HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
                };
                var channel = GrpcChannel.ForAddress("https://localhost:5001",
                                                     new GrpcChannelOptions {
                    HttpHandler = httpHandler
                });
                var client = new StudentService.StudentServiceClient(channel);
                await client.InsertStudentAsync(
                    new Student
                {
                    AdmisstionDate = Google.Protobuf.WellKnownTypes.Timestamp.FromDateTime(DateTime.UtcNow),
                    DateofBirth    = Google.Protobuf.WellKnownTypes.Timestamp.FromDateTime(DateTime.UtcNow),
                    FirstName      = "FirstName",
                    LastName       = "LastName",
                    MiddleName     = "MiddleName",
                    UrduName       = "طالب علم",
                    Id             = Guid.NewGuid().ToString(),
                    MobileNumber   = "0300176"
                });


                var result = await client.GetAllStudentsAsync(new Empty());

                foreach (var item in result.Students)
                {
                    //if(string.IsNullOrEmpty(item.UrduName))
                    //{
                    //    item.UrduName = "طالب علم";
                    //}
                    //await client.UpdateStudnetAsync(item);
                    Console.WriteLine($"{item.FirstName} {item.MiddleName} {item.LastName} {item.DateofBirth.ToDateTime()} {item.AdmisstionDate.ToDateTime()} {item.Id}");
                }
                Console.ReadKey();
            }
            catch (RpcException e)
            {
                var err = e.ToString();
            }
        }
Beispiel #12
0
        public async Task <bool> AddItemAsync(Models.Student item)
        {
            using var channel = GrpcChannel.ForAddress(serverAddress);
            var     client   = new StudentService.StudentServiceClient(channel);
            Student toinsert = new Student()
            {
                AdmisstionDate = Google.Protobuf.WellKnownTypes.Timestamp.FromDateTime(item.AdmisstionDate),
                DateofBirth    = Google.Protobuf.WellKnownTypes.Timestamp.FromDateTime(item.DateofBirth),
                Id             = item.Id,
                FirstName      = item.FirstName,
                LastName       = item.LastName,
                MiddleName     = item.MiddleName,
                MobileNumber   = item.MobileNumber,
                UrduName       = item.UrduName
            };
            await client.InsertStudentAsync(toinsert);

            return(await Task.FromResult(true));
        }
Beispiel #13
0
        public ActionResult GetStudentById()
        {
            Student stu = new Student();
            try
            {
                StudentService.StudentServiceClient client = new StudentService.StudentServiceClient();

                StudentService.StudentContract contract = client.GetStudentById(1);
                stu.StudentId = contract.StudentId;
                stu.StudentName = contract.StudentName;
                return View(stu);
            }
            catch (Exception ex)
            {
                stu.StudentId = 0;
                stu.StudentName = "Student name not found... "+ex.Message;
                return View();
            }
        }
Beispiel #14
0
        public async Task <Models.Student> GetItemAsync(string id)
        {
            using var channel = GrpcChannel.ForAddress(serverAddress);
            var client = new StudentService.StudentServiceClient(channel);

            var item = await client.GetStudentAsync(new StudentId { Id = id });

            Models.Student foundstudent = new Models.Student()
            {
                AdmisstionDate = item.AdmisstionDate.ToDateTime(),
                DateofBirth    = item.DateofBirth.ToDateTime(),
                Id             = item.Id,
                FirstName      = item.FirstName,
                LastName       = item.LastName,
                MiddleName     = item.MiddleName,
                MobileNumber   = item.MobileNumber,
                UrduName       = item.UrduName
            };
            return(await Task.FromResult(foundstudent));
        }
Beispiel #15
0
        public async Task <StudentInformationGrpcDto> GetInfoAsync(string userId)
        {
            _logger.LogInformation("get student information of {0}", userId);
            AppContext.SetSwitch(
                "System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);

            using var coreChannel = GrpcChannel.ForAddress(_configuration["CoreGrpc"]);

            var coreClient = new StudentService.StudentServiceClient(coreChannel);

            var studentInfo = await coreClient.GetInfoAsync(new StudentInfoRequest
            {
                UserId = userId
            });

            AppContext.SetSwitch(
                "System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", false);

            return(new StudentInformationGrpcDto
            {
                Code = studentInfo.Code,
                Id = studentInfo.Id,
                CreateTime = DateTime.Parse(studentInfo.CreateTime),
                FieldTitle = studentInfo.FieldTitle,
                FullName = studentInfo.FullName,
                UserId = studentInfo.UserId,
                FieldId = studentInfo.FieldId,
                CurrentSemesterId = studentInfo.CurrentSemesterId,
                CurrentSemesterTitle = studentInfo.CurrentSemesterTitle,
                CanTakeCurriculums = studentInfo.CanTakeCurriculums,
                EndCurriculumScheduleDateTime = studentInfo.CanTakeCurriculums
                    ? DateTime.Parse(studentInfo.EndCurriculumScheduleDateTime)
                    : (DateTime?)null,
                StartCurriculumScheduleDateTime = studentInfo.CanTakeCurriculums
                    ? DateTime.Parse(studentInfo.StartCurriculumScheduleDateTime)
                    : (DateTime?)null
            });
        }
Beispiel #16
0
        static async Task Main(string[] args)
        {
            //AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
            var channel = GrpcChannel.ForAddress("https://localhost:5001");

            var client = new StudentService.StudentServiceClient(channel);

            while (true)
            {
                Console.WriteLine("Enter an argument");

                string line = Console.ReadLine();

                if (line == "exit")
                {
                    break;
                }

                var reply = await client.GetStudentAsync(
                    new GetStudentRequest()
                {
                    Id = line
                }
                    );

                if (reply.Student != null)
                {
                    Console.WriteLine("Reply: " + reply.Student);
                }

                if (reply.Error != null)
                {
                    Console.WriteLine("Reply: " + reply.Error);
                }
            }
            Console.WriteLine("Exiting...");
        }