internal SimpleServer(int port) { TSampleService.Iface remoteService = new SampleService(port); TServerTransport transport = new TServerSocket(port); var processor = new TSampleService.Processor(remoteService); server = new TSimpleServer(processor, transport); }
public void BonusMethod_WithAuthentication_UsesPreAuthentication() { var operation = "ListOfStuff"; var expectedRequest = new TestableWebRequest(new Uri(BaseUri, operation)); expectedRequest.EnqueueResponse(HttpStatusCode.OK, "Success", "Even More Success", false); TestableWebRequestCreateFactory.GetFactory().AddRequest(expectedRequest); var service = new SampleService(BaseUri); var response = service.BonusMethod(operation, "AwesomeUser", "1234"); Assert.IsTrue(expectedRequest.PreAuthenticate); }
public void ListRemoteStuffAsyncAwait_403NoneShallPass_ThrowsExampleOfAnotherUsefulException() { var operation = "ListOfStuff"; var expectedRequest = new TestableWebRequest(new Uri(BaseUri, operation)); expectedRequest.EnqueueResponse(HttpStatusCode.Forbidden, "None shall pass", "Somethign else amusing", true); TestableWebRequestCreateFactory.GetFactory().AddRequest(expectedRequest); var service = new SampleService(BaseUri); var response = service.ListRemoteStuffAsyncAwait(operation); // expect exception }
public void ListRemoteStuffAsyncAwait_404DohickeyNotFound_ThrowsDohickeyNotFoundException() { var operation = "ListOfStuff"; var expectedRequest = new TestableWebRequest(new Uri(BaseUri, operation)); expectedRequest.EnqueueResponse(HttpStatusCode.NotFound, "Dohicky not found", "I couldn't find your dohicky because I don't like you", true); TestableWebRequestCreateFactory.GetFactory().AddRequest(expectedRequest); var service = new SampleService(BaseUri); var response = service.ListRemoteStuffAsyncAwait(operation); // expect exception }
private static void AccessSample() { using (var accessOperation = new AccessOperation()) { //NewDatabase var filePath = Path.Combine(Environment.CurrentDirectory, "sample.accdb"); accessOperation.NewDatabase(filePath); } using (var conn = DbConnectionFactory.Default.CreateConnection()) using (var tran = conn.BeginTransaction()) { try { var service = new SampleService(conn); //CreateDatabase service.CreateTable(tran); //AddSampleData service.AddSampleData(tran); tran.Commit(); } catch (Exception) { tran.Rollback(); throw; } } using (var conn = DbConnectionFactory.Default.CreateConnection()) { var service = new SampleService(conn); //GetAll var records = service.GetAll(); foreach (var r in records) { Console.WriteLine(string.Join(" - ", r.Column1, r.Column2)); } Console.WriteLine("==============================="); //GetById var record = service.GetById("2"); Console.WriteLine(string.Join(" - ", record.Column1, record.Column2)); } }
public IHttpActionResult GradesProcessing(string id) { try { JsonObject json = new JsonObject(); GradeMaterial gra = biz.GetGradeMaterial(id); GradeMaterialDto grade = new GradeMaterialDto(); if (!string.IsNullOrEmpty(gra.SampleName) && !string.IsNullOrEmpty(gra.LOT_NO)) { SampleService sampleDal = new SampleService(); QCSample sample = sampleDal.SelectSample(gra.SampleName); QCMaterial material = sampleDal.GetMaterial(gra.SampleName, gra.LOT_NO); json["SampleName"] = sample.SampleName; json["SampleDescription_EN"] = sample.Description_EN; json["SampleDescription_CN"] = sample.Description_CN; json["SampleDescription_TW"] = sample.Description_TW; json["SampleDescription_VN"] = sample.Description_VN; json["Status"] = gra.Status; json["Grade"] = gra.Grades; json["LOT_NO"] = material.LOT_NO; json["MaterialDescription_EN"] = material.Description_EN; json["MaterialDescription_CN"] = material.Description_CN; json["MaterialDescription_TW"] = material.Description_TW; json["MaterialDescription_VN"] = material.Description_VN; json["Version"] = gra.Version; json["VersionSpc"] = gra.VersionSpc; json["UserID"] = gra.UserID; //json["Remark"] = gra.Remark; DataTable dtGrade = biz.NewestGrades(id); json["Grades"] = helpbiz.ConvertJson(dtGrade); return(Ok(json)); } else { return(BadRequest("NO DATA")); } } catch (Exception ex) { Console.WriteLine(ex); Loger.Error(ex); return(BadRequest(ex.Message + ex.StackTrace)); } }
protected override void RunClient(int repeatedCount, ref bool bStop, int responseSize, out int successful) { successful = 0; using (SampleService client = new SampleService(Connect(Iid))) { for (int count = 0; !bStop && count < repeatedCount; count++) { SampleResponse response = client.Test( SampleRequest.CreateBuilder() .AddRangeData(CreateSampleData(responseSize)) .Build() ); GC.KeepAlive(response); successful++; } } }
public async Task <List <NewsArticle> > FetchDetails() { SampleService toolsData = new SampleService(); var SystemsData = await toolsData.FetchData(); if (SystemsData != null || SystemsData.Count == 0) { NoData = false; IsLoader = false; } else { NoData = true; IsLoader = true; } NewsFields = SystemsData; return(SystemsData); }
public static void Main() { // System.Runtime.Remoting.RemotingServices.Unmarshal // <Snippet2> ChannelServices.RegisterChannel(new HttpChannel()); SampleService objectSample = (SampleService)Activator.GetObject(typeof(SampleService), "http://localhost:9000/MySampleService/SampleService.soap"); // The GetManuallyMarshaledObject() method uses RemotingServices.Marshal() // to create an ObjRef object for a SampleTwo object. ObjRef objRefSampleTwo = objectSample.GetManuallyMarshaledObject(); SampleTwo objectSampleTwo = (SampleTwo)RemotingServices.Unmarshal(objRefSampleTwo); objectSampleTwo.PrintMessage("ObjRef successfuly unmarshaled."); // </Snippet2> }
protected override void RunClient(int repeatedCount, ref bool bStop, int responseSize, out int successful) { successful = 0; using (SampleService client = new SampleService(Connect(Iid))) { for(int count = 0; !bStop && count < repeatedCount; count++) { SampleResponse response = client.Test( SampleRequest.CreateBuilder() .AddRangeData(CreateSampleData(responseSize)) .Build() ); GC.KeepAlive(response); successful++; } } }
public async Task <ActionResult> ImportPedigree() { Guid sampleId = Guid.Parse(Request["sampleId"]); string analysisRequestId = Request["analysisRequestId"]; Guid guidAnalysisRequestId = Guid.Parse(analysisRequestId); List <GNSampleRelationship> sampleRelationships = db.GNSampleRelationships.Where(t => t.GNLeftSampleId.Equals(sampleId)).ToList(); foreach (GNSampleRelationship sampleRel in sampleRelationships) { if (db.GNAnalysisRequestGNSamples.Count(t => t.GNAnalysisRequestId == guidAnalysisRequestId && t.GNSampleId == sampleRel.GNRightSample.Id) == 0) { SampleService ss = new SampleService(db, identityDB); int result = await ss.AddSampleToAnalysisRequest(sampleRel.GNRightSample.Id, analysisRequestId); } } return(RedirectToAction("Edit", "AnalysisRequests", new { id = analysisRequestId })); }
public void EventStub_WireUnwireTests() { var eventStub = new EventStub(typeof(ISampleInterface)); var simpleEventFired = false; var cancelEventFired = false; var actionFired = false; var funcFired = false; // add event handlers eventStub.AddHandler("SimpleEvent", new EventHandler((sender, args) => simpleEventFired = true)); eventStub.AddHandler("CancelEvent", new EventHandler <CancelEventArgs>((sender, args) => cancelEventFired = true)); eventStub.AddHandler("ActionDelegate", new Action(() => actionFired = true)); eventStub.AddHandler("FuncDelegate", new Func <int, string>(a => { funcFired = true; return(a.ToString()); })); eventStub.AddHandler("FuncDelegate", new Func <int, string>(a => { return((a * 2).ToString()); })); // wire up events var component = new SampleService(); eventStub.WireTo(component); // test if it works var result = component.FireHandlers(102030); Assert.AreEqual("204060", result); Assert.IsTrue(simpleEventFired); Assert.IsTrue(cancelEventFired); Assert.IsTrue(actionFired); Assert.IsTrue(funcFired); // unwire simpleEventFired = false; cancelEventFired = false; actionFired = false; funcFired = false; eventStub.UnwireFrom(component); // test if it works result = component.FireHandlers(123); Assert.IsNull(result); Assert.IsFalse(simpleEventFired); Assert.IsFalse(cancelEventFired); Assert.IsFalse(actionFired); Assert.IsFalse(funcFired); }
public async Task <IActionResult> OnPostSubmit() { if (!ModelState.IsValid) { return(Page()); } var result = await SampleService.Save(false, new ReturnResult <SampleViewModel>() { Value = Input }); ModelState.Merge(result); if (!ModelState.IsValid) { return(Page()); } ShowMessage(CoreEnumerations.MessageTypes.info, SharedResources.SaveSuccess); return(RedirectToPage(NavConstants.ManagementAreas.Pages.SamplesIndex, new{ area = NavConstants.ManagementAreas.Area })); }
public async Task PostMethodShouldReturnNotFoundIfFakeDontMatch() { Uri uri = new Uri("http://www.dummyurl.com/api/controller"); var fakeServiceHelper = new FakeServiceHelper(fakeHttpResponseHandler); var sut = new SampleService(fakeServiceHelper); var requestObject = new DummyRequestClass { Id = 1, Name = "POST test", Age = 100 }; var response = await sut.Post(requestObject); var responseBody = await response.Content.ReadAsStringAsync(); Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode); Assert.AreEqual("Not matching fake found", responseBody); }
public void GetAllSamplesByGivenSearchParams_FilteredByBacteriaNameAndGroup_ShouldReturnRelevantSamples() { // Arrange var db = this.GetDatabase(); var mapper = this.GetAutoMapper(); var searchParams = new SearchParametersBindingModel() { BacteriaName = "New Sample" }; var sample = new Sample() { Name = "New Sample" }; var group = new Group() { Name = "group1" }; var sampleGroup = new SampleGroup() { Sample = sample, Group = group, }; db.Samples.Add(sample); db.Groups.Add(group); db.SampleGroups.Add(sampleGroup); db.SaveChanges(); var service = new SampleService(db, mapper); // Act var result = service.GetAllSamplesByGivenSearchParams(searchParams); // Assert Assert.NotNull(result); Assert.IsType <List <SampleViewModel> >(result); var sampleName = result[0].Name; Assert.Equal("New Sample", sampleName); }
public bool Update() { SampleDTO newUser = new SampleDTO(); IUnitOfWork _unitOfWork = new UnitOfWork(_ctx); ISampleRepository _sampleRepository = new SampleRepository(_ctx); var _sampleService = new SampleService(_unitOfWork, _sampleRepository); newUser = _sampleService.GetById(2); // newUser.Name = "Priya B"; Sample userList = Mapper.Map <Sample>(newUser); // _sampleService.Update(userList); // message = _sampleService.Add(newUser); return(_sampleService.UpdateById(1)); }
static async Task Main(string[] args) { var serverHostBuilder = new HostBuilder() .ConfigureAppConfiguration((hostingContext, config) => { var env = hostingContext.HostingEnvironment; config .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true); config.AddEnvironmentVariables(); }) .ConfigureLogging((context, logging) => { logging .AddConfiguration(context.Configuration.GetSection("Logging")) .AddConsole(); }) .ConfigureServices((hostContext, services) => { services .AddScoped <ISampleServiceLogic, RandomSampleServiceLogic>() .AddScopedExecutor() //the most "magic" solution .AddGrpcServer <SampleServiceImplementation>( new[] { new ServerPort("127.0.0.1", 5050, ServerCredentials.Insecure) } ) //a more manual solution if the flexibility is required //also not using the IScopedExecutor (although it could) for a more traditional example .AddGrpcServer(appServices => { var scopeFactory = appServices.GetRequiredService <IServiceScopeFactory>(); var server = new Grpc.Core.Server { Services = { SampleService.BindService(new AnotherSampleServiceImplementation(scopeFactory)) }, Ports = { new ServerPort("127.0.0.1", 5051, ServerCredentials.Insecure) } }; return(server); }); }); await serverHostBuilder.RunConsoleAsync(); }
public static void Main() { ChannelServices.RegisterChannel(new HttpChannel(0)); RemotingConfiguration.RegisterActivatedClientType(typeof(SampleService), "http://localhost:9000/MySampleService"); SampleService myRemoteObject = new SampleService(); bool result = myRemoteObject.SampleMethod(); // System.Runtime.Remoting.RemotingServices.GetObjRefForProxy // <Snippet1> ObjRef objRefSample = RemotingServices.GetObjRefForProxy(myRemoteObject); Console.WriteLine("***ObjRef Details***"); Console.WriteLine("URI:\t{0}", objRefSample.URI); object[] channelData = objRefSample.ChannelInfo.ChannelData; Console.WriteLine("Channel Info:"); foreach (object o in channelData) { Console.WriteLine("\t{0}", o.ToString()); } IEnvoyInfo envoyInfo = objRefSample.EnvoyInfo; if (envoyInfo == null) { Console.WriteLine("This ObjRef does not have envoy information."); } else { IMessageSink envoySinks = envoyInfo.EnvoySinks; Console.WriteLine("Envoy Sink Class: {0}", envoySinks); } IRemotingTypeInfo typeInfo = objRefSample.TypeInfo; Console.WriteLine("Remote type name: {0}", typeInfo.TypeName); Console.WriteLine("Can my object cast to a Bitmap? {0}", typeInfo.CanCastTo(typeof(System.Drawing.Bitmap), objRefSample)); // </Snippet1> }
public void GetContactsAsStream_On401Response_MustThrowUnauthorizedApiAccessException_WithMoq() { var unauthorizedResponseHttpMessageHandlerMock = new Mock <HttpMessageHandler>(); // so we can setup a protected method named SendAsync inside HttpMessageHandler unauthorizedResponseHttpMessageHandlerMock.Protected() .Setup <Task <HttpResponseMessage> >( "SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>() ).ReturnsAsync(new HttpResponseMessage() { StatusCode = HttpStatusCode.Unauthorized }); var httpClient = new HttpClient(unauthorizedResponseHttpMessageHandlerMock.Object); var testableClass = new SampleService(httpClient); Assert.ThrowsAsync <UnauthorizedApiAccessException>(() => testableClass.GetContactsAsStream()); }
public async Task UpdateAsync(string name, bool exits, bool isValid, int code, string message) { //Arrange Mock <ISampleRepository> SampleRepositoryMock = new Mock <ISampleRepository>(); var sampleService = new SampleService(SampleRepositoryMock.Object); SampleRepositoryMock.Setup(it => it.ExistsAsync(It.IsAny <string>())).Returns(Task.FromResult(exits)); IModelResult <FooSample> newFooSampleResult = FooSample.New(name); if ((exits && !isValid) || (!exits && isValid)) { SampleRepositoryMock.Setup(it => it.GetAsync(it => it.IdFooSample == It.IsAny <int>())).Returns(Task.FromResult(newFooSampleResult.Model)); } //Act var sampleModelResult = await sampleService.UpdateAsync(1, name); //Assert Assert.That(sampleModelResult.IsModelResultValid(), Is.EqualTo(isValid)); Assert.That(sampleModelResult.Message, Is.EqualTo(message)); Assert.That(sampleModelResult.ModelStatusCode, Is.EqualTo(code)); }
public override SiteProvisionerStepResponse Execute() { var response = new SiteProvisionerStepResponse(); SampleService sampleService = new SampleService(); sampleService.AssetDirectory = this.Properties.AssetDirectory; try { sampleService.DoSomething(); response.Message = "We did something"; response.Success = true; } catch (Exception ex) { response.Message = ex.Message; response.Success = false; } return(response); }
public void Test_AppHost_IHostedService() { var hostedProcess = new SampleProcess() { Name = "Process1" }; var hostedProcess2 = new SampleProcess() { Name = "Process2" }; var hostedService = new SampleService() { Name = "Service1" }; var hostedService2 = new SampleService() { Name = "Service2" }; var hostBuilder = new AppHostBuilder().CreateDefaultBuilder(); hostBuilder.AddHostedProcess(hostedProcess); hostBuilder.AddHostedProcess(hostedProcess2); hostBuilder.AddHostedProcess <SampleProcess>(); hostBuilder.AddHostedService(hostedService); hostBuilder.AddHostedService(hostedService2); hostBuilder.AddHostedService <SampleService>(); var host = hostBuilder.Build(); host.RunOnce(); //hostedProcess.StartCalls.Should().Be(1); //hostedProcess.StopCalls.Should().Be(1); //hostedProcess.ErrorCalls.Should().Be(1); //hostedService.StartCalls.Should().Be(1); //hostedService.StopCalls.Should().Be(1); }
public async Task GetMethodShouldReturnFakeResponse() { Uri uri = new Uri("http://www.dummyurl.com/api/controller/"); const int dummyParam = 123456; const string expectdBody = "Expected Response"; var expectedHttpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(expectdBody) }; fakeHttpResponseHandler.AddFakeServiceResponse(uri, expectedHttpResponseMessage, dummyParam); var fakeServiceHelper = new FakeServiceHelper(fakeHttpResponseHandler); var sut = new SampleService(fakeServiceHelper); var response = await sut.Get(dummyParam); var responseBody = await response.Content.ReadAsStringAsync(); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); Assert.AreEqual(expectdBody, responseBody); }
public string Post([FromBody] SampleModel loginData, [FromServices] SampleService jwt) { return(jwt.JwtHelper.BuildToken("userId")); }
public void ListRemoteStuff_SixTimeoutsOccur_FinallyThrowsTheException() { var operation = "ListOfStuff"; var expectedRequest = new TestableWebRequest(new Uri(BaseUri, operation)); expectedRequest.EnqueueResponse(new TimeoutException("took too long, so sorry")) .EnqueueResponse(new TimeoutException("took too long, so sorry")) .EnqueueResponse(new TimeoutException("took too long, so sorry")) .EnqueueResponse(new TimeoutException("took too long, so sorry")) .EnqueueResponse(new TimeoutException("took too long, so sorry")) .EnqueueResponse(new TimeoutException("took too long, so sorry")); TestableWebRequestCreateFactory.GetFactory().AddRequest(expectedRequest); var service = new SampleService(BaseUri); var response = service.ListRemoteStuff(operation); // expect exception }
public SampleClient(SampleService service) { }
public void UploadSomething_ServiceOutage_ThrowsSampleServiceOutage() { var operation = "UploadSomething"; var expectedRequest = new TestableWebRequest(new Uri(BaseUri, operation)); expectedRequest.EnqueueResponse(new WebException("I'm broke!", WebExceptionStatus.ConnectFailure)); TestableWebRequestCreateFactory.GetFactory().AddRequest(expectedRequest); var service = new SampleService(BaseUri); var response = service.UploadSomething(operation, System.Text.Encoding.UTF8.GetBytes("My awesome data payload!")); // expect exception }
public void UploadSomething_ValidRequest_ReturnsSuccessfulResponse() { var operation = "UploadSomething"; var expectedRequest = new TestableWebRequest(new Uri(BaseUri, operation)); expectedRequest.EnqueueResponse(HttpStatusCode.OK, "Success", "Even More Success", false); TestableWebRequestCreateFactory.GetFactory().AddRequest(expectedRequest); var service = new SampleService(BaseUri); var response = service.UploadSomething(operation, System.Text.Encoding.UTF8.GetBytes("My awesome data payload!")); Assert.IsTrue(response.IsSuccess); }
public Service1(SampleService sampleService) { _sampleService = sampleService; }
public FrontController() { orderService = new OrderService(); sampleService = new SampleService(); imageFontService = new ImageFontService(); }
public void ListRemoteStuff_ServiceOutage_ThrowsSampleServiceOutage() { var operation = "ListOfStuff"; var expectedRequest = new TestableWebRequest(new Uri(BaseUri, operation)); expectedRequest.EnqueueResponse(new WebException("I'm broke!", WebExceptionStatus.ConnectFailure)); TestableWebRequestCreateFactory.GetFactory().AddRequest(expectedRequest); var service = new SampleService(BaseUri); var response = service.ListRemoteStuff(operation); // expect exception }
public void ListRemoteStuff_ValidRequest_SetsVersionHeader() { var operation = "ListOfStuff"; var expectedRequest = new TestableWebRequest(new Uri(BaseUri, operation)); expectedRequest.EnqueueResponse(HttpStatusCode.OK, "Success", "Even More Success", false); TestableWebRequestCreateFactory.GetFactory().AddRequest(expectedRequest); var service = new SampleService(BaseUri); var response = service.ListRemoteStuff(operation); Assert.AreEqual("123-awesome", expectedRequest.Headers["version"]); }
public void ListRemoteStuff_ValidRequest_ReturnsSuccessfulResponse() { var operation = "ListOfStuff"; var expectedRequest = new TestableWebRequest(new Uri(BaseUri, operation)); expectedRequest.EnqueueResponse(HttpStatusCode.OK, "Success", "Even More Success", false); TestableWebRequestCreateFactory.GetFactory().AddRequest(expectedRequest); var service = new SampleService(BaseUri); var response = service.ListRemoteStuff(operation); Assert.IsTrue(response.IsSuccess); }
public void ListRemoteStuffAsyncAwait_404SomeOtherObjectNotFound_ThrowsGenericNotFoundException() { var operation = "ListOfStuff"; var expectedRequest = new TestableWebRequest(new Uri(BaseUri, operation)); expectedRequest.EnqueueResponse(HttpStatusCode.NotFound, "OtherObjectType not found", "I couldn't find yuor other object because the name was unimaginative", true); TestableWebRequestCreateFactory.GetFactory().AddRequest(expectedRequest); var service = new SampleService(BaseUri); var response = service.ListRemoteStuffAsyncAwait(operation); // expect exception }
public void UploadSomething_403NoneShallPass_ThrowsExampleOfAnotherUsefulException() { var operation = "UploadSomething"; var expectedRequest = new TestableWebRequest(new Uri(BaseUri, operation)); expectedRequest.EnqueueResponse(HttpStatusCode.Forbidden, "None shall pass", "Somethign else amusing", true); TestableWebRequestCreateFactory.GetFactory().AddRequest(expectedRequest); var service = new SampleService(BaseUri); var response = service.UploadSomething(operation, System.Text.Encoding.UTF8.GetBytes("My awesome data payload!")); // expect exception }
public void UploadSomething_404DohickeyNotFound_ThrowsDohickeyNotFoundException() { var operation = "UploadSomething"; var expectedRequest = new TestableWebRequest(new Uri(BaseUri, operation)); expectedRequest.EnqueueResponse(HttpStatusCode.NotFound, "Dohicky not found", "I couldn't find your dohicky because I don't like you", true); TestableWebRequestCreateFactory.GetFactory().AddRequest(expectedRequest); var service = new SampleService(BaseUri); var response = service.UploadSomething(operation, System.Text.Encoding.UTF8.GetBytes("My awesome data payload!")); // expect exception }
public SampleController() { _statusService = new StatusService(); _userService = new UserService(); _sampleService = new SampleService(); }
public void ListRemoteStuffAsyncTPL_ValidRequest_ReturnsResponseContent() { var operation = "ListOfStuff"; var expectedRequest = new TestableWebRequest(new Uri(BaseUri, operation)); expectedRequest.EnqueueResponse(HttpStatusCode.OK, "Success", "Even More Success", false); TestableWebRequestCreateFactory.GetFactory().AddRequest(expectedRequest); var service = new SampleService(BaseUri); var response = service.ListRemoteStuffAsyncTPL(operation); Assert.AreEqual("Even More Success", response.Message); }
public AutomationTester() { _sampleService = new SampleService(); }
public void UploadSomething_TimeoutOccurs_ThrowsRawTimeoutException() { var operation = "UploadSomething"; var expectedRequest = new TestableWebRequest(new Uri(BaseUri, operation)); expectedRequest.EnqueueResponse(new TimeoutException("took too long, so sorry")) .EnqueueResponse(HttpStatusCode.OK, "All Good", "Nothing to see, please move along", false); TestableWebRequestCreateFactory.GetFactory().AddRequest(expectedRequest); var service = new SampleService(BaseUri); var response = service.UploadSomething(operation, System.Text.Encoding.UTF8.GetBytes("My awesome data payload!")); Assert.AreEqual("Nothing to see, please move along", response.Message); }
/// <summary> /// Initializes a new instance of the <see cref="TestController"/> class. /// </summary> /// <param name="Service">The service.</param> public SampleController(SampleService Service) { _Service = Service; }
public HomeController() { _service = new SampleService(); }
public void Setup() { _mockRepository = new Mock <IRepository <string> >(); _mockRepository.Setup(x => x.Get(It.IsAny <int>())).Returns("This works"); _service = new SampleService(_mockRepository.Object); }
public void ListRemoteStuff_TimeoutOccurs_TruesASecondTime() { var operation = "ListOfStuff"; var expectedRequest = new TestableWebRequest(new Uri(BaseUri, operation)); expectedRequest.EnqueueResponse(new TimeoutException("took too long, so sorry")) .EnqueueResponse(HttpStatusCode.OK, "All Good", "Nothing to see, please move along", false); TestableWebRequestCreateFactory.GetFactory().AddRequest(expectedRequest); var service = new SampleService(BaseUri); var response = service.ListRemoteStuff(operation); Assert.AreEqual("Nothing to see, please move along", response.Message); }
public void SamplesCtor_WhenServicesAreNotNull_ShouldBeNotNull() { SampleService sampleService = new SampleService(_unitOfWork.Object, _procedureManager.Object, _mapper.Object); Assert.That(sampleService, Is.Not.Null); }
static void Main(string[] args) { var service = new SampleService(); service.GetCount(); }
public void UploadSomething_ValidRequest_SetsVersionHeader() { var operation = "UploadSomething"; var expectedRequest = new TestableWebRequest(new Uri(BaseUri, operation)); expectedRequest.EnqueueResponse(HttpStatusCode.OK, "Success", "Even More Success", false); TestableWebRequestCreateFactory.GetFactory().AddRequest(expectedRequest); var service = new SampleService(BaseUri); var response = service.UploadSomething(operation, System.Text.Encoding.UTF8.GetBytes("My awesome data payload!")); Assert.AreEqual("123-awesome", expectedRequest.Headers["version"]); }
public void UploadSomething_404SomeOtherObjectNotFound_ThrowsGenericNotFoundException() { var operation = "UploadSomething"; var expectedRequest = new TestableWebRequest(new Uri(BaseUri, operation)); expectedRequest.EnqueueResponse(HttpStatusCode.NotFound, "OtherObjectType not found", "I couldn't find yuor other object because the name was unimaginative", true); TestableWebRequestCreateFactory.GetFactory().AddRequest(expectedRequest); var service = new SampleService(BaseUri); var response = service.UploadSomething(operation, System.Text.Encoding.UTF8.GetBytes("My awesome data payload!")); // expect exception }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); // get the reference to our custom application App = Application as ZyanApplication; // initialize controls var serverEditText = FindViewById <EditText>(Resource.Id.serverEditText); var responseView = FindViewById <TextView>(Resource.Id.responseView); var statusTextView = FindViewById <TextView>(Resource.Id.statusTextView); var connectButton = FindViewById <Button>(Resource.Id.connectButton); var disconnectButton = FindViewById <Button>(Resource.Id.disconnectButton); var queryButton = FindViewById <Button>(Resource.Id.myButton); // enable or disable buttons var connected = App.ZyanConnection != null; serverEditText.Enabled = !connected; connectButton.Enabled = !connected; disconnectButton.Enabled = connected; queryButton.Enabled = connected; if (connected) { statusTextView.Text = "Connected to: " + ZyanConnection.ServerUrl; } // add event handlers connectButton.Click += async(sender, e) => { connectButton.Enabled = false; serverEditText.Enabled = false; ServerAddress = serverEditText.Text; statusTextView.Text = "Connecting to server..."; var address = await RunAsync(() => ZyanConnection.ServerUrl); statusTextView.Text = "Connected to: " + address; disconnectButton.Enabled = true; queryButton.Enabled = true; }; disconnectButton.Click += (sender, e) => { serverEditText.Enabled = true; connectButton.Enabled = true; queryButton.Enabled = false; disconnectButton.Enabled = false; if (App.ZyanConnection != null) { App.ZyanConnection.Dispose(); App.ZyanConnection = null; } }; queryButton.Click += async(sender, e) => { responseView.Text = "..."; responseView.Text = await Task.Factory.StartNew(() => SampleService.GetRandomString()); }; }
public void UploadSomething_ValidRequest_UploadsMyAwesomeDataCorrectly() { var operation = "UploadSomething"; var expectedRequest = new TestableWebRequest(new Uri(BaseUri, operation)); expectedRequest.EnqueueResponse(HttpStatusCode.OK, "Success", "Even More Success", false); TestableWebRequestCreateFactory.GetFactory().AddRequest(expectedRequest); var service = new SampleService(BaseUri); var response = service.UploadSomething(operation, System.Text.Encoding.UTF8.GetBytes("My awesome data payload!")); var uploadedData = ((TestableWebRequest)expectedRequest).GetContent(); Assert.AreEqual("My awesome data payload!", System.Text.Encoding.UTF8.GetString(uploadedData)); }