static void Main(string[] args) { using (var client = new ExampleServiceClient()) { var airLines = client.GetAllAirlines(); } }
public async Task <ActionResult> Save(EditEmployeeModel employee) { using (var service = new ExampleServiceClient()) { if (this.ModelState.IsValid) { var dto = new EmployeeDTO { Id = employee.Id, FirstName = employee.FirstName, LastName = employee.LastName, MiddleName = employee.MiddleName }; await service.SaveEmployeeAsync(dto, service.GetDepartmentById(employee.DepartmentId)); return(this.RedirectToAction("EmployeeList", "Departments", new { departmentId = employee.CurrentDepartmentId })); } var availableDepartmentsDTO = await service.GetDepartmentsAsync(); employee.AvailableDepartments = availableDepartmentsDTO.Select(x => new Department().MapFrom(x)).ToArray(); return(this.View("Employee", employee)); } }
static void Main(string[] args) { using (Services.ExampleServiceClient proxy = new ExampleServiceClient()) { Stopwatch sw = new Stopwatch(); sw.Start(); try { proxy.DoWork(); } catch (Exception ex) { Console.WriteLine(ex.Message + " "); } sw.Stop(); Console.WriteLine("proxy.DoWork(): Elapsed Time: {0}ms\n", sw.ElapsedMilliseconds); sw.Reset(); sw.Start(); try { proxy.DoOneWayWork(); } catch (Exception ex) { Console.WriteLine(ex.Message + " "); } sw.Stop(); Console.WriteLine("proxy.DoOneWayWork(): Elapsed Time: {0}ms\n", sw.ElapsedMilliseconds); sw.Reset(); sw.Start(); try { proxy.DoWorkAsync(); } catch (Exception ex) { Console.WriteLine(ex.Message + " "); } sw.Stop(); Console.WriteLine("proxy.DoWorkAsync(): Elapsed Time: {0}ms\n", sw.ElapsedMilliseconds); sw.Reset(); } Console.ReadLine(); }
public void SynchronousClientExperiment() { TraceLine(Instructions.WaitForCompletion); // ExampleServiceClient is auto-generated by Visual Studio. using (var client = new ExampleServiceClient( new BasicHttpBinding(), new EndpointAddress(serviceUrl))) { var results = client.GetHttpResponses(new[] { new Uri("http://microsoft.com"), new Uri("http://codeplex.com"), new Uri("http://google.com"), new Uri("http://wikipedia.org") }); foreach (var result in results) { TraceLine(); TraceSuccess(result.Url.ToString()); TraceLine(result.ResponseSummary); } } }
public void Save(Department data) { using (var service = new ExampleServiceClient()) { if (data.Id == Guid.Empty) { service.CreateNewDepartment(data.Name); } else { service.UpdateDepartment(new DepartmentDTO { Id = data.Id, Name = data.Name, Employees = data.Employees.Select(x => new EmployeeDTO { FirstName = x.FirstName, MiddleName = x.MiddleName, LastName = x.LastName, Salary = x.Salary, Id = x.Id }).ToArray() }); } } }
public async Task <ActionResult> EmployeeList(Guid departmentId) { using (var service = new ExampleServiceClient()) { var department = await service.GetDepartmentByIdAsync(departmentId); return(this.View(new Department().MapFrom(department))); } }
public async Task <ActionResult> Departments() { using (var service = new ExampleServiceClient()) { var departments = await service.GetDepartmentsAsync(); return(this.View(departments.Select(x => new Department().MapFrom(x)).ToArray())); } }
public async void GetExampleById_Calls_Correct_Url() { // ARRANGE var handlerMock = new Mock <HttpMessageHandler>(MockBehavior.Strict); handlerMock .Protected() // Setup the PROTECTED method to mock .Setup <Task <HttpResponseMessage> >( "SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>() ) .ReturnsAsync(new HttpResponseMessage() { StatusCode = HttpStatusCode.OK, Content = new StringContent(JsonConvert.SerializeObject(new Example())), }) .Verifiable(); var loggerMock = new Mock <ILogger>(); var httpClient = new HttpClient(handlerMock.Object); IOptions <EnvironmentConfiguration> environmentConfiguration = Options.Create <EnvironmentConfiguration>(new EnvironmentConfiguration()); var configuration = new MapperConfiguration(cfg => { cfg.AddProfile <ExampleProfile>(); }); var mapper = new Mapper(configuration); var tenant = "tenant"; var contentId = "1"; var exampleServiceClient = new ExampleServiceClient( loggerMock.Object, mapper, environmentConfiguration, httpClient); var exampleId = 1; // ACT await exampleServiceClient.GetExampleById(exampleId); // ASSERT var expectedUri = new Uri($"http://localhost/api/v1/examples/{exampleId}"); handlerMock.Protected().Verify( "SendAsync", Times.Exactly(1), ItExpr.Is <HttpRequestMessage>(req => req.Method == HttpMethod.Get && req.RequestUri == expectedUri // to this uri ), ItExpr.IsAny <CancellationToken>() ); }
static void Main(string[] args) { var input = string.Empty; using (var client = new ExampleServiceClient()) { while (input != "quit") { System.Console.WriteLine("Get or save?"); input = System.Console.ReadLine(); var key = string.Empty; var message = string.Empty; switch (input) { case "get": System.Console.WriteLine("Key?"); key = System.Console.ReadLine(); message = client.GetMessage(key); System.Console.WriteLine("Message is: {0}", message); break; case "save": System.Console.WriteLine("Key?"); key = System.Console.ReadLine(); System.Console.WriteLine("Message?"); message = System.Console.ReadLine(); key = client.SaveMessage(key, message); System.Console.WriteLine("Key is: {0}", key); break; default: break; } System.Console.WriteLine("Continue or quit?"); input = System.Console.ReadLine(); } } }
public void AsynchronousClientExperiment() { TraceLine(Instructions.PressAnyKeyToCancel); TraceLine(); // ExampleServiceClient is auto-generated by Visual Studio. using (var client = new ExampleServiceClient( new BasicHttpBinding(), new EndpointAddress(serviceUrl))) { #if WINDOWS_PHONE var invokeAsync = Observable.FromAsyncPattern<Uri[], ExampleServiceResponseReference>( client.BeginGetSlowestHttpResponse, client.EndGetSlowestHttpResponse); var observable = invokeAsync(new[] { new Uri("http://microsoft.com"), new Uri("http://codeplex.com"), new Uri("http://google.com"), new Uri("http://wikipedia.org") }); #else var observable = Task.Factory.FromAsync<Uri[], ExampleServiceResponseReference>( client.BeginGetSlowestHttpResponse, client.EndGetSlowestHttpResponse, new[] { new Uri("http://microsoft.com"), new Uri("http://codeplex.com"), new Uri("http://google.com"), new Uri("http://wikipedia.org") }, state: null) .ToObservable(); #endif using (observable.Subscribe( result => { TraceSuccess(result.Url.ToString()); TraceLine(result.ResponseSummary); TraceLine(); }, ConsoleOutputOnError(), ConsoleOutputOnCompleted())) { WaitForKey(); } } }
public async void GetExampleById_CallsCorrectUrl() { // ARRANGE _handlerMock .Protected() // Setup the PROTECTED method to mock .Setup <Task <HttpResponseMessage> >( "SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>() ) .ReturnsAsync(new HttpResponseMessage() { StatusCode = HttpStatusCode.OK, Content = new StringContent(JsonConvert.SerializeObject(new Example())), }) .Verifiable(); _httpClientFactoryMock.Setup(x => x.CreateClient(string.Empty)).Returns(new HttpClient(_handlerMock.Object)); var environmentConfiguration = Options.Create(new EnvironmentConfiguration() { SERVICE_URL = "https://localhost" }); var configuration = new MapperConfiguration(cfg => { cfg.AddProfile <ExampleProfile>(); }); var mapper = new Mapper(configuration); var exampleServiceClient = new ExampleServiceClient( _loggerMock.Object, mapper, environmentConfiguration, _httpClientFactoryMock.Object); var exampleId = 1; // ACT await exampleServiceClient.GetExampleById(exampleId); // ASSERT var expectedUri = new Uri($"https://localhost/api/v1/examples/{exampleId}"); _handlerMock.Protected().Verify( "SendAsync", Times.Exactly(1), ItExpr.Is <HttpRequestMessage>(req => req.Method == HttpMethod.Get && req.RequestUri == expectedUri ), ItExpr.IsAny <CancellationToken>() ); }
public void Save(Employee data) { using (var service = new ExampleServiceClient()) { if (data.Id == Guid.Empty) { service.CreateNewEmployee(data.FirstName, data.MiddleName, data.LastName, data.Salary, data.DepartmentId); } else { throw new NotImplementedException(); } } }
public ICollection <Department> Get() { using (var service = new ExampleServiceClient()) { return(service.GetDepartments().Select(x => new Department { Id = x.Id, Name = x.Name, Employees = new ObservableCollection <Employee>(x.Employees.Select(e => new Employee { Id = e.Id, FirstName = e.FirstName, MiddleName = e.MiddleName, LastName = e.LastName, }).ToList()) }).ToArray()); } }
public async Task <ActionResult> Employee(Guid?employeeId, Guid departmentId) { using (var service = new ExampleServiceClient()) { var employee = employeeId.HasValue ? new Employee().MapFrom(await service.GetEmployeeAsync(employeeId.Value)) : null; var model = new EditEmployeeModel { Id = employeeId ?? Guid.Empty, FirstName = employee?.FirstName, LastName = employee?.LastName, MiddleName = employee?.MiddleName, DepartmentId = departmentId, AvailableDepartments = service.GetDepartments().Select(x => new Department().MapFrom(x)).ToArray(), CurrentDepartmentId = departmentId }; return(this.View(model)); } }
/// <summary> /// Main entry point /// </summary> /// <param name="args">command line args</param> static void Main(string[] args) { // create client ExampleServiceClient client = new ExampleServiceClient(); // make calls and print results string tmp = client.GetData(17); Console.WriteLine(tmp); CompositeType ct = new ExampleService.CompositeType() { BoolValue = true, StringValue = "goodbye" }; tmp = client.GetDataUsingDataContract(ct).StringValue; Console.WriteLine(tmp); // wait for key string s = Console.ReadLine(); }
public async void GetExampleById_ThrowsException_WhenRequestIsNotSuccessful() { // ARRANGE _handlerMock .Protected() // Setup the PROTECTED method to mock .Setup <Task <HttpResponseMessage> >( "SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>() ) .ReturnsAsync(new HttpResponseMessage() { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent("Big bad thing happened."), RequestMessage = new HttpRequestMessage() }) .Verifiable(); _httpClientFactoryMock.Setup(x => x.CreateClient(string.Empty)).Returns(new HttpClient(_handlerMock.Object)); var environmentConfiguration = Options.Create(new EnvironmentConfiguration() { SERVICE_URL = "https://localhost" }); var configuration = new MapperConfiguration(cfg => { cfg.AddProfile <ExampleProfile>(); }); var mapper = new Mapper(configuration); var exampleServiceClient = new ExampleServiceClient( _loggerMock.Object, mapper, environmentConfiguration, _httpClientFactoryMock.Object); var exampleId = 1; // ACT / ASSERT await Assert.ThrowsAsync <Exception>(async() => await exampleServiceClient.GetExampleById(exampleId)); }
static void Main(string[] args) { try { string data = args.Length > 0 ? args[0] : "Test data from proxy client"; // Create the client object available from the service reference var client = new ExampleServiceClient("appEndpoint"); // Execute the test method Console.WriteLine("Set test data = [{0}]", data); Console.WriteLine("Calling TestService() Method..."); Console.WriteLine(client.TestService(data + Environment.NewLine)); // Get a number to compute a Fibonacci value const string prompt = "Enter an integer (40 or less) to use for calculation: "; Console.WriteLine("{0}{1}", Environment.NewLine, prompt); int number; while (!int.TryParse(Console.ReadLine(), out number) || number > 40) { Console.WriteLine("{0}{0}That entry was invalid!{0}{1}", Environment.NewLine, prompt); } Console.WriteLine("{0}Calculating Fibonacci value of {1}{0}", Environment.NewLine, number); // Create a request using the agreed-upon request data contract var request = new FibonacciRequest { Number = number, UseRecursiveAlgorithm = true }; // Return a result data contract object by calling the operation var result = client.Fibonacci(request); if (result.Errors != null) { Console.WriteLine("The recusrsive calculation resulted in an error: {0}", result.Errors); } else { Console.WriteLine("{0}Using the recursive formula: {1}{0}Calculated that f({2}) = {3}{0}In {4} iterations{0}{0}Press <ENTER> to continue", Environment.NewLine, result.Data.Formula, number, result.Data.Value, result.Data.Iterations); } Console.ReadLine(); // Call the operation again request.UseRecursiveAlgorithm = false; result = client.Fibonacci(request); if (result.Errors != null) { Console.WriteLine("The non-recusrsive calculation resulted in an error: {0}", result.Errors); } else { Console.WriteLine("Using the non-recursive formula: {1}{0}Calculated that f({2}) = {3}{0}In {4} iterations", Environment.NewLine, result.Data.Formula, number, result.Data.Value, result.Data.Iterations); } } catch (Exception ex) { HandleException("General", ex); } finally { Console.WriteLine("{0}Done! Press any key to exit...", Environment.NewLine); // Ensure the console doesn't close until we're done Console.ReadKey(); } }