static void Main(string[] args) { ITradeService proxy = new System.ServiceModel.ChannelFactory<ITradeService>("TradeServiceConfiguration").CreateChannel(); ITradeMonitor monitor = new System.ServiceModel.ChannelFactory<ITradeMonitor>("TradeMonitorConfiguration").CreateChannel(); Console.WriteLine("\nTrade IBM"); Console.WriteLine(monitor.StartMonitoring("IBM")); double result = proxy.TradeSecurity("IBM", 1000); Console.WriteLine("Cost was " + result); Console.WriteLine(monitor.StopMonitoring("IBM")); Console.WriteLine("\nTrade MSFT"); result = proxy.TradeSecurity("MSFT", 2000); Console.WriteLine("Cost was " + result); try { Console.WriteLine("\nTrade ATT"); result = proxy.TradeSecurity("T", 3000); Console.WriteLine("Cost was " + result); } catch (Exception ex) { Console.Write("Exception was: " + ex.Message); } Console.WriteLine("\n\nPress <enter> to exit..."); Console.ReadLine(); }
public IList<Contracts.Entities.Recipe> GetRecentRecipes(int maxcount) { //TODO: call actual WCF service and make call using (System.ServiceModel.ChannelFactory<IRecipeService> factory = new System.ServiceModel.ChannelFactory<IRecipeService>("RecipeServiceHTTP")) { IRecipeService service = factory.CreateChannel(); return service.GetRecentRecipes(maxcount); } }
public void InitializeTest() { System.Threading.Monitor.Enter(mobileStagingServiceProxyTable); try { mobileStagingServiceProxyTable.TryGetValue(System.Threading.Thread.CurrentThread.ManagedThreadId, out mobileStagingServiceClient); if (((mobileStagingServiceClient == null) || (((System.ServiceModel.ICommunicationObject)(mobileStagingServiceClient)).State == System.ServiceModel.CommunicationState.Faulted))) { // The following line may need to be customised to select the appropriate binding from the configuration file System.ServiceModel.ChannelFactory<on.the.dot.IMobileStagingService> mobileStagingServiceFactory = new System.ServiceModel.ChannelFactory<on.the.dot.IMobileStagingService>("BasicHttpBinding_IMobileStagingService"); mobileStagingServiceClient = mobileStagingServiceFactory.CreateChannel(); ((System.ServiceModel.ICommunicationObject)(mobileStagingServiceClient)).Open(); mobileStagingServiceProxyTable[System.Threading.Thread.CurrentThread.ManagedThreadId] = mobileStagingServiceClient; } } finally { System.Threading.Monitor.Exit(mobileStagingServiceProxyTable); } }
public void InstanceProviderReleaseCalledWithCorrectObjectTest() { var instanceProvider = new TestInstanceProvider(); var behavior = new TestServiceBehavior { InstanceProvider = instanceProvider }; System.ServiceModel.ChannelFactory <ISimpleService> factory = ExtensibilityHelper.CreateChannelFactory <SimpleService, ISimpleService>(behavior); factory.Open(); ISimpleService channel = factory.CreateChannel(); ((System.ServiceModel.Channels.IChannel)channel).Open(); string echo = channel.Echo("hello"); Assert.Equal("hello", echo); instanceProvider.WaitForReleaseAsync(TimeSpan.FromSeconds(10)).Wait(); Assert.True(instanceProvider.InstanceHashCode > 0);; Assert.Equal(instanceProvider.ReleasedInstanceHashCode, instanceProvider.InstanceHashCode); ((System.ServiceModel.Channels.IChannel)channel).Close(); factory.Close(); TestHelper.CloseServiceModelObjects((System.ServiceModel.Channels.IChannel)channel, factory); }
public static void InstanceContextMode_PerCall_NoInjection() { PerCallInstanceContextSimpleService.ClearCounts(); System.ServiceModel.ChannelFactory <ISimpleService> factory = DispatcherHelper.CreateChannelFactory <PerCallInstanceContextSimpleService, ISimpleService>(); factory.Open(); ISimpleService channel = factory.CreateChannel(); ((System.ServiceModel.Channels.IChannel)channel).Open(); // Instance shouldn't be created as part of service startup as type isn't available in DI Assert.Equal(0, PerCallInstanceContextSimpleService.CreationCount); Assert.Equal(0, PerCallInstanceContextSimpleService.DisposalCount); string echo = channel.Echo("hello"); echo = channel.Echo("hello"); PerCallInstanceContextSimpleService.WaitForDisposalCount(2, TimeSpan.FromSeconds(30)); Assert.Equal(2, PerCallInstanceContextSimpleService.CreationCount); Assert.Equal(2, PerCallInstanceContextSimpleService.DisposalCount); ((System.ServiceModel.Channels.IChannel)channel).Close(); factory.Close(); TestHelper.CloseServiceModelObjects((System.ServiceModel.Channels.IChannel)channel, factory); }
public static void InjectedSingletonInstanceWithServiceBehaviorSingle_NotDisposed() { DisposableSimpleService.InstantiationCount = 0; var serviceInstance = new DisposableSimpleServiceWithServiceBehaviorSingle(); System.ServiceModel.ChannelFactory <ISimpleService> factory = DispatcherHelper.CreateChannelFactory <DisposableSimpleServiceWithServiceBehaviorSingle, ISimpleService>( (services) => { services.AddSingleton(serviceInstance); }); factory.Open(); ISimpleService channel = factory.CreateChannel(); ((System.ServiceModel.Channels.IChannel)channel).Open(); string echo = channel.Echo("hello"); ((System.ServiceModel.Channels.IChannel)channel).Close(); Assert.False(serviceInstance.IsDisposed, "Service instance shouldn't be disposed"); factory.Close(); TestHelper.CloseServiceModelObjects((System.ServiceModel.Channels.IChannel)channel, factory); Assert.Equal(1, DisposableSimpleService.InstantiationCount); }
public static void ServiceSendFaultMessage() { var fault = new TestFault { Message = Guid.NewGuid().ToString() }; var reason = new FaultReason(Guid.NewGuid().ToString()); var code = new FaultCode(nameof(ServiceSendFaultMessage)); System.ServiceModel.ChannelFactory <IFaultingService> factory = DispatcherHelper.CreateChannelFactory <FaultingService, IFaultingService>( (services) => { services.AddSingleton(new FaultingService(fault, reason, code)); }); factory.Open(); IFaultingService channel = factory.CreateChannel(); Exception exceptionThrown = null; try { channel.FaultingOperation(); } catch (Exception e) { exceptionThrown = e; } Assert.NotNull(exceptionThrown); Assert.IsType <System.ServiceModel.FaultException <TestFault> >(exceptionThrown); var faultException = (System.ServiceModel.FaultException <TestFault>)exceptionThrown; Assert.Equal(fault.Message, faultException.Detail.Message); Assert.Equal(reason.ToString(), faultException.Reason.ToString()); Assert.Equal(code.Name, faultException.Code.Name); // Empty string FaultCode namespace becomes default soap envelope ns Assert.Equal("http://www.w3.org/2003/05/soap-envelope", faultException.Code.Namespace); ((System.ServiceModel.Channels.IChannel)channel).Close(); factory.Close(); TestHelper.CloseServiceModelObjects((System.ServiceModel.Channels.IChannel)channel, factory); }
public static void OperationInvokerCalledMultiple() { TestDispatchOperationInvoker.ClearCounts(); var behavior = new TestServiceBehavior { OperationInvokerFactory = TestDispatchOperationInvoker.Create }; System.ServiceModel.ChannelFactory <ISimpleService> factory = ExtensibilityHelper.CreateChannelFactory <SimpleService, ISimpleService>(behavior); factory.Open(); ISimpleService channel = factory.CreateChannel(); ((System.ServiceModel.Channels.IChannel)channel).Open(); foreach (int dummy in Enumerable.Range(0, 10)) { string echo = channel.Echo("hello"); Assert.Equal("hello", echo); } Assert.Equal(10, TestDispatchOperationInvoker.InvokeCount); Assert.Equal(1, TestDispatchOperationInvoker.InstanceCount); ((System.ServiceModel.Channels.IChannel)channel).Close(); factory.Close(); TestHelper.CloseServiceModelObjects((System.ServiceModel.Channels.IChannel)channel, factory); }
public void Variation_PollingMethod() { var host = ServiceHelper.CreateWebHostBuilder <Startup>(_output).Build(); using (host) { host.Start(); var httpBinding = ClientHelper.GetBufferedModeBinding(); var factory = new System.ServiceModel.ChannelFactory <IClientAsync_767311>(httpBinding, new System.ServiceModel.EndpointAddress(new Uri("http://localhost:8080/BasicWcfService/SyncService.svc"))); IClientAsync_767311 clientAsync_ = factory.CreateChannel(); _output.WriteLine("Testing [Variation_PollingMethod]"); IAsyncResult asyncResult = clientAsync_.BeginEchoString(clientString, null, null); _output.WriteLine("Message sent via Async"); _output.WriteLine("Start polling for IsCompleted != true"); while (!asyncResult.IsCompleted) { } _output.WriteLine("IsCompleted == true"); string text = clientAsync_.EndEchoString(asyncResult); _output.WriteLine(text); Assert.Equal(clientResult, text); } }
public static async Task AsyncServiceThrowsTimeoutExceptionAfterAwait() { System.ServiceModel.ChannelFactory <ISimpleAsyncService> factory = DispatcherHelper.CreateChannelFactory <ThrowingAsyncService, ISimpleAsyncService>( (services) => { services.AddSingleton(new ThrowingAsyncService(new TimeoutException(), beforeAwait: false)); }); factory.Open(); ISimpleAsyncService channel = factory.CreateChannel(); ((System.ServiceModel.IClientChannel)channel).Open(); System.ServiceModel.FaultException exceptionThrown = await Assert.ThrowsAsync <System.ServiceModel.FaultException>(async() => { _ = await channel.EchoAsync("hello"); }); Assert.NotNull(exceptionThrown); Assert.True(exceptionThrown.Code.IsReceiverFault); Assert.Equal("InternalServiceFault", exceptionThrown.Code.SubCode.Name); ((System.ServiceModel.Channels.IChannel)channel).Close(); factory.Close(); TestHelper.CloseServiceModelObjects((System.ServiceModel.Channels.IChannel)channel, factory); }
public async Task VerifyPathRestoredAsync() { string testString = new string('a', 100); IWebHost host = ServiceHelper.CreateWebHostBuilder <Startup>(_output).Build(); using (host) { host.Start(); System.ServiceModel.BasicHttpBinding httpBinding = ClientHelper.GetBufferedModeBinding(); var factory = new System.ServiceModel.ChannelFactory <ClientContract.IEchoService>(httpBinding, new System.ServiceModel.EndpointAddress(new Uri("http://localhost:8080/BasePath/BasicHttp/basichttp.svc"))); ClientContract.IEchoService channel = factory.CreateChannel(); string result = channel.EchoString(testString); Assert.Equal(testString, result); HttpClient httpClient = new HttpClient(); var responseMessage = await httpClient.GetAsync("http://localhost:8080/BasePath/SomeOtherUrl/GetRequest"); Assert.True(responseMessage.Headers.Contains("Test_Path")); Assert.Equal("/SomeOtherUrl/GetRequest", responseMessage.Headers.GetValues("Test_Path").SingleOrDefault()); Assert.True(responseMessage.Headers.Contains("Test_PathBase")); Assert.Equal("/BasePath", responseMessage.Headers.GetValues("Test_PathBase").SingleOrDefault()); } }
public static void MultipleClientsNonConcurrentNetTcpClientConnection() { string testString = new string('a', 3000); var host = CreateWebHostBuilder(new string[0]).Build(); using (host) { host.Start(); var binding = new System.ServiceModel.NetTcpBinding(); var factory = new System.ServiceModel.ChannelFactory <ClientContract.ITestService>(binding, new System.ServiceModel.EndpointAddress(new Uri("net.tcp://localhost:8808/nettcp.svc"))); var channel = factory.CreateChannel(); ((IChannel)channel).Open(); var result = channel.EchoString(testString); ((IChannel)channel).Close(); Assert.Equal(testString, result); channel = factory.CreateChannel(); ((IChannel)channel).Open(); result = channel.EchoString(testString); ((IChannel)channel).Close(); Assert.Equal(testString, result); } }
public void WSHttpRequestReplyEchoStringTransportSecurity() { ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateCertificate); string testString = new string('a', 3000); var host = ServiceHelper.CreateHttpsWebHostBuilder <WSHttpTransportSecurityOnly>(_output).Build(); using (host) { host.Start(); var wsHttpBinding = ClientHelper.GetBufferedModeWSHttpBinding(System.ServiceModel.SecurityMode.Transport); wsHttpBinding.Security.Message.ClientCredentialType = System.ServiceModel.MessageCredentialType.None; var factory = new System.ServiceModel.ChannelFactory <ClientContract.IEchoService>(wsHttpBinding, new System.ServiceModel.EndpointAddress(new Uri("https://localhost:8443/WSHttpWcfService/basichttp.svc"))); factory.Credentials.ServiceCertificate.SslCertificateAuthentication = new System.ServiceModel.Security.X509ServiceCertificateAuthentication(); factory.Credentials.ServiceCertificate.SslCertificateAuthentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None; ClientContract.IEchoService channel = factory.CreateChannel(); ((IChannel)channel).Open(); var result = channel.EchoString(testString); Assert.Equal(testString, result); Console.WriteLine("read "); ((IChannel)channel).Close(); } }
public void BasicHttpRequestReplyEchoString() { string testString = new string('a', 3000); IWebHost host = ServiceHelper.CreateHttpSysBuilder <Startup>(_output).Build(); using (host) { host.Start(); System.ServiceModel.BasicHttpBinding httpBinding = ClientHelper.GetBufferedModeBinding(); var factory = new System.ServiceModel.ChannelFactory <ClientContract.IEchoService>(httpBinding, new System.ServiceModel.EndpointAddress(new Uri("http://localhost/Temporary_Listen_Addresses/CoreWCFTestServices/BasicWcfService/basichttp.svc"))); ClientContract.IEchoService channel = factory.CreateChannel(); string result = channel.EchoString(testString); Assert.Equal(testString, result); // Work around HttpSys host bug where it doesn't cancel a callback timer // and causes the host to write to the ILogger after the test has ended // which causes xunit to abort the test run. See dotnet/aspnetcore#30828 var cts = new CancellationTokenSource(); host.StopAsync(cts.Token).GetAwaiter().GetResult(); cts.Cancel(); cts.Dispose(); } }
public static void MessageContract() { var host = CreateWebHostBuilder(new string[0]).Build(); using (host) { host.Start(); var binding = new System.ServiceModel.NetTcpBinding(); var factory = new System.ServiceModel.ChannelFactory <ClientContract.ITestService>(binding, new System.ServiceModel.EndpointAddress(new Uri("net.tcp://localhost:8808/nettcp.svc"))); var channel = factory.CreateChannel(); ((IChannel)channel).Open(); var message = new ClientContract.TestMessage() { Header = "Header", Body = new MemoryStream(Encoding.UTF8.GetBytes("Hello world")) }; var result = channel.TestMessageContract(message); ((IChannel)channel).Close(); Assert.Equal("Header from server", result.Header); Assert.Equal("Hello world from server", new StreamReader(result.Body, Encoding.UTF8).ReadToEnd()); } }
public static void EndpointBehaviorUsed() { var endpointBehavior = new TestEndpointBehavior(); System.ServiceModel.ChannelFactory <ISimpleService> factory = ExtensibilityHelper.CreateChannelFactory <SimpleService, ISimpleService>((CoreWCF.ServiceHostBase serviceHostBase) => { foreach (var endpoint in serviceHostBase.Description.Endpoints) { endpoint.EndpointBehaviors.Add(endpointBehavior); } }); factory.Open(); ISimpleService channel = factory.CreateChannel(); string echo = channel.Echo("hello"); Assert.Equal("hello", echo); Assert.True(endpointBehavior.AddBindingParametersCalled); Assert.False(endpointBehavior.ApplyClientBehaviorCalled); Assert.True(endpointBehavior.ApplyDispatchBehaviorCalled); Assert.True(endpointBehavior.ValidateCalled); ((System.ServiceModel.Channels.IChannel)channel).Close(); factory.Close(); TestHelper.CloseServiceModelObjects((System.ServiceModel.Channels.IChannel)channel, factory); }
public async Task NetTCPRequestReplyWithTransportMessageEchoStringDemuxFailure() { string testString = new string('a', 3000); IWebHost host = ServiceHelper.CreateWebHostBuilder <StartUpPermissionBaseForTCDemuxFailure>(_output).Build(); using (host) { host.Start(); System.ServiceModel.NetTcpBinding binding = ClientHelper.GetBufferedModeBinding(System.ServiceModel.SecurityMode.TransportWithMessageCredential); binding.Security.Message.ClientCredentialType = System.ServiceModel.MessageCredentialType.UserName; UriBuilder uriBuilder = new UriBuilder(host.GetNetTcpAddressInUse() + Startup.WindowsAuthRelativePath); uriBuilder.Host = "localhost"; // Replace 127.0.0.1 with localhost so Identity has correct value var factory = new System.ServiceModel.ChannelFactory <ClientContract.ITestService>(binding, new System.ServiceModel.EndpointAddress(uriBuilder.ToString())); System.ServiceModel.Description.ClientCredentials clientCredentials = (System.ServiceModel.Description.ClientCredentials)factory.Endpoint.EndpointBehaviors[typeof(System.ServiceModel.Description.ClientCredentials)]; factory.Credentials.ServiceCertificate.SslCertificateAuthentication = new System.ServiceModel.Security.X509ServiceCertificateAuthentication { CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None }; clientCredentials.UserName.UserName = "******"; clientCredentials.UserName.Password = RandomString(10); var channel = factory.CreateChannel(); try { ((IChannel)channel).Open(); await Task.Delay(6000); string result = channel.EchoString(testString); } catch (Exception ex) { Assert.IsAssignableFrom <System.ServiceModel.FaultException>(ex.InnerException); Assert.Contains("expired security context token", ex.InnerException.Message); } } }
public void RemoteEndpointMessageProperty() { IWebHost host = ServiceHelper.CreateWebHostBuilder <Startup>(_output).Build(); using (host) { host.Start(); System.ServiceModel.NetTcpBinding nettcpBinding = ClientHelper.GetBufferedModeBinding(); var factory = new System.ServiceModel.ChannelFactory <ClientContract.IRemoteEndpointMessageProperty>(nettcpBinding, new System.ServiceModel.EndpointAddress(new Uri(host.GetNetTcpAddressInUse() + "/RemoteEndpointMessagePropertyService.svc"))); ClientContract.IRemoteEndpointMessageProperty channel = factory.CreateChannel(); Message request = Message.CreateMessage(nettcpBinding.MessageVersion, "echo", "PASS"); Message response = channel.Echo(request); string[] results = response.GetBody <string>().Split(';'); Assert.Equal(3, results.Length); Assert.Equal("PASS", results[0]); string clientIP = results[1]; CheckIP(clientIP); NetstatResults(results[2], host.GetNetTcpPortInUse().ToString()); } }
public static void InjectedTransientInstanceInjectedServiceBehaviorPerCall_Succeeds() { DisposableSimpleService.InstantiationCount = 0; var serviceBehaviorAttr = new CoreWCF.ServiceBehaviorAttribute(); serviceBehaviorAttr.InstanceContextMode = CoreWCF.InstanceContextMode.PerCall; serviceBehaviorAttr.ConcurrencyMode = CoreWCF.ConcurrencyMode.Multiple; System.ServiceModel.ChannelFactory <ISimpleService> factory = DispatcherHelper.CreateChannelFactory <DisposableSimpleService, ISimpleService>( (services) => { services.AddTransient <DisposableSimpleService>(); services.AddSingleton <IServiceBehavior>(serviceBehaviorAttr); }); factory.Open(); ISimpleService channel = factory.CreateChannel(); ((System.ServiceModel.Channels.IChannel)channel).Open(); string echo = channel.Echo("hello"); ((System.ServiceModel.Channels.IChannel)channel).Close(); factory.Close(); TestHelper.CloseServiceModelObjects((System.ServiceModel.Channels.IChannel)channel, factory); Assert.Equal(1, DisposableSimpleService.InstantiationCount); }
public void RemoteEndpointMessageProperty() { var host = ServiceHelper.CreateWebHostBuilder <Startup>(_output).Build(); using (host) { host.Start(); var nettcpBinding = ClientHelper.GetBufferedModeBinding(); var factory = new System.ServiceModel.ChannelFactory <ClientContract.IRemoteEndpointMessageProperty>(nettcpBinding, new System.ServiceModel.EndpointAddress(new Uri("net.tcp://localhost:8808/RemoteEndpointMessagePropertyService.svc"))); var channel = factory.CreateChannel(); Message request = Message.CreateMessage(nettcpBinding.MessageVersion, "echo", "PASS"); Message response = channel.Echo(request); string[] results = response.GetBody <string>().Split(';'); Assert.Equal(3, results.Length); Assert.Equal("PASS", results[0]); string clientIP = results[1]; CheckIP(clientIP); ThreadPool.QueueUserWorkItem(NetstatResults, results[2]); } }
public void ByRefParams() { IWebHost host = ServiceHelper.CreateWebHostBuilder <Startup>(_output).Build(); using (host) { host.Start(); System.ServiceModel.BasicHttpBinding httpBinding = ClientHelper.GetBufferedModeBinding(); var factory = new System.ServiceModel.ChannelFactory <ClientContract.IByRefService>( httpBinding, new System.ServiceModel.EndpointAddress( new Uri("http://localhost:8080/BasicWcfService/IByRefService.svc"))); ClientContract.IByRefService channel = factory.CreateChannel(); // Test that out param behaves as expected channel.SetNumber(33); channel.GetNumber(out int num1); Assert.Equal(33, num1); // Test that InAttribute makes no difference channel.SetNumberIn(41); channel.GetNumber(out int num2); Assert.Equal(41, num2); // Test that the out param is correctly decided by the input channel.GetOutParam("test", out Guid guidA, true); channel.GetOutParam("test", out Guid guidB, false); Assert.Equal(Services.ByRefService.GuidA, guidA); Assert.Equal(Services.ByRefService.GuidB, guidB); // Test that the ref param is changed between ResultA and ResultB and the return value is correct Guid refGuid = Services.ByRefService.GuidA; bool exchangeResult1 = channel.ExchangeRefParam(ref refGuid); Assert.True(exchangeResult1); Assert.Equal(Services.ByRefService.GuidB, refGuid); bool exchangeResult2 = channel.ExchangeRefParam(ref refGuid); Assert.True(exchangeResult2); Assert.Equal(Services.ByRefService.GuidA, refGuid); Guid unknownGuid = Guid.Parse("11112222-3333-4444-5555-666677778888"); refGuid = unknownGuid; bool exchangeResult3 = channel.ExchangeRefParam(ref refGuid); Assert.False(exchangeResult3); Assert.Equal(unknownGuid, refGuid); // Test with both out and ref params. Chose which value is set using the bool argument. string resultA = "unknown"; channel.SelectParam("test1", true, ref resultA, out string resultB); Assert.Equal("test1", resultA); Assert.Null(resultB); string resultC = "test3"; channel.SelectParam("test2", false, ref resultC, out string resultD); Assert.Equal("test2", resultD); Assert.Equal("test3", resultC); } }
public ClientChannelFactory() { this.factory = new System.ServiceModel.ChannelFactory <TChannel>("BasicHttpBinding_IService"); }
//구성정보 없이 코드로 Endpoint 구성후 호출 private void CallServiceWithoutConfig() { try { // 1. 클라이언트 상에 서비스 endpoint 정의하기 System.ServiceModel.Description.ServiceEndpoint httpEndpoint = new System.ServiceModel.Description.ServiceEndpoint( System.ServiceModel.Description.ContractDescription.GetContract( typeof(IEchoService)),new System.ServiceModel.WSHttpBinding(), new System.ServiceModel.EndpointAddress("http://xdn-dcpark/Server_Console/EchoService")); System.ServiceModel.Description.ServiceEndpoint tcpEndpoint= new System.ServiceModel.Description.ServiceEndpoint( System.ServiceModel.Description.ContractDescription.GetContract( typeof(IEchoService)), new System.ServiceModel.NetTcpBinding(), new System.ServiceModel.EndpointAddress("net.tcp://xdn-dcpark:20000/Server_Console/EchoService")); System.ServiceModel.Description.ServiceEndpoint namedPipeEndpoint= new System.ServiceModel.Description.ServiceEndpoint( System.ServiceModel.Description.ContractDescription.GetContract( typeof(IEchoService)), new System.ServiceModel.NetNamedPipeBinding(), new System.ServiceModel.EndpointAddress("net.pipe://xdn-dcpark/Server_Console/EchoService")); IEchoService svc = null; // 2. Endpoint 에 기반한 Channel Factory 생성 using (System.ServiceModel.ChannelFactory<IEchoService> httpFactory = new System.ServiceModel.ChannelFactory<IEchoService>(httpEndpoint)) { // 3. Endpoint에 대한 Chennel proxy 생성 svc = httpFactory.CreateChannel(); // 4. 서비스 오퍼레이션 호출 this.txtStatus.Text += String.Format("Invoking HTTP endpoint(ONLY CODE): {0}\r\n", svc.Echo("Duck Chang Park")); } // 2. Endpoint 에 기반한 Channel Factory 생성 using (System.ServiceModel.ChannelFactory<IEchoService> tcpFactory = new System.ServiceModel.ChannelFactory<IEchoService>(tcpEndpoint)) { // 3. Endpoint에 대한 Chennel proxy 생성 svc = tcpFactory.CreateChannel(); // 4. 서비스 오퍼레이션 호출 this.txtStatus.Text += String.Format("Invoking TCP endpoint(ONLY CODE): {0}\r\n", svc.Echo("Duck Chang Park")); } // 2. Endpoint 에 기반한 Channel Factory 생성 using (System.ServiceModel.ChannelFactory<IEchoService> namedPipeFactory = new System.ServiceModel.ChannelFactory<IEchoService>(namedPipeEndpoint)) { // 3. Endpoint에 대한 Chennel proxy 생성 svc = namedPipeFactory.CreateChannel(); // 4. 서비스 오퍼레이션 호출 this.txtStatus.Text += String.Format("Invoking NAMED PIPE endpoint(ONLY CODE): {0}\r\n", svc.Echo("Duck Chang Park")); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { this.txtStatus.Text += String.Format("--------------------------------------\r\n"); } }
public void TypedContractCollectionTest() { IWebHost host = ServiceHelper.CreateWebHostBuilder <TypedContractCollectionServiceStartup>(_output).Build(); using (host) { host.Start(); System.ServiceModel.BasicHttpBinding httpBinding = ClientHelper.GetBufferedModeBinding(); var factory = new System.ServiceModel.ChannelFactory <ITypedContract_Collection>(httpBinding, new System.ServiceModel.EndpointAddress(new Uri("http://localhost:8080/BasicWcfService/TypedContract_CollectionService.svc"))); ITypedContract_Collection channel = factory.CreateChannel(); foreach (int numItems in new int[] { 1, 5, 15, 50 }) { //arraylist var outgoingAL = new ArrayList(); for (int item = 0; item < numItems; item++) { outgoingAL.Add(item); } ArrayList responseAL = channel.ArrayListMethod(outgoingAL); Assert.Equal(outgoingAL.Count, responseAL.Count); for (int item = 0; item < responseAL.Count; item++) { if ((int)responseAL[item] != (int)outgoingAL[item]) { Assert.True(false, "ArrayList item validation failed"); } } //Collection var outgoingCL = new Collection <string>(); for (int item = 0; item < numItems; item++) { string s = string.Format("Item " + item); outgoingCL.Add(s); } Collection <string> responseCL = channel.CollectionOfStringsMethod(outgoingCL); Assert.Equal(outgoingCL.Count, responseCL.Count); for (int item = 0; item < responseCL.Count; item++) { if (responseCL[item].CompareTo(outgoingCL[item]) != 0) { Assert.True(false, "Collection item validation failed"); } } //CollecitonBase MyCollection outgoingCB = new MyCollection(); for (int item = 0; item < numItems; item++) { outgoingCB.Add((short)item); } MyCollection responseCB = channel.CollectionBaseMethod(outgoingCB); Assert.Equal(outgoingCB.Count, responseCB.Count); for (int item = 0; item < responseCB.Count; item++) { if (responseCB[item] != outgoingCB[item]) { Assert.True(false, "MyCollection:CollectionBase item validation failed"); } } } } }
public void FaultOnDiffContractAndOps() { var host = ServiceHelper.CreateWebHostBuilder <Startup>(_output).Build(); using (host) { host.Start(); var httpBinding = ClientHelper.GetBufferedModeBinding(); var factory = new System.ServiceModel.ChannelFactory <ClientContract.ITestFaultOpContract>(httpBinding, new System.ServiceModel.EndpointAddress(new Uri("http://localhost:8080/BasicWcfService/FaultOnDiffContractsAndOpsService.svc"))); var channel = factory.CreateChannel(); var factory2 = new System.ServiceModel.ChannelFactory <ClientContract.ITestFaultOpContractTypedClient>(httpBinding, new System.ServiceModel.EndpointAddress(new Uri("http://localhost:8080/BasicWcfService/FaultOnDiffContractsAndOpsService.svc"))); var channel2 = factory2.CreateChannel(); //test variations count int count = 9; string faultToThrow = "Test fault thrown from a service"; //Variation_TwoWayMethod try { string s = channel.TwoWay_Method(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //Variation_TwoWayVoidMethod try { channel.TwoWayVoid_Method(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //Variation_TwoWayStreamMethod try { string testValue = "This is a string that will be converted to a byte array"; Stream inputStream = new MemoryStream(); byte[] bytes = Encoding.UTF8.GetBytes(testValue.ToCharArray()); foreach (byte b in bytes) { inputStream.WriteByte(b); } inputStream.Position = 0; Stream outputStream = channel.TwoWayStream_Method(inputStream); StreamReader sr = new StreamReader(outputStream, Encoding.UTF8); sr.ReadToEnd(); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //Variation_TwoWayAsyncMethod try { string response = channel.TwoWayAsync_MethodAsync("").GetAwaiter().GetResult(); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //Variation_MessageContractMethod // Send the two way message var fmc = new ClientContract.FaultMsgContract(); fmc.ID = 123; fmc.Name = ""; try { ClientContract.FaultMsgContract fmcResult = channel.MessageContract_Method(fmc); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //Variation_UntypedMethod System.ServiceModel.Channels.MessageVersion mv = System.ServiceModel.Channels.MessageVersion.Soap11; System.ServiceModel.Channels.Message msgOut = System.ServiceModel.Channels.Message.CreateMessage(mv, "http://tempuri.org/ITestFaultOpContract/Untyped_Method"); System.ServiceModel.Channels.Message msgIn = channel.Untyped_Method(msgOut); if (msgIn.IsFault) { count--; System.ServiceModel.Channels.MessageFault mf = System.ServiceModel.Channels.MessageFault.CreateFault(msgIn, int.MaxValue); Assert.Equal(faultToThrow, mf.GetDetail <string>()); } //Variation_UntypedMethodReturns msgOut = System.ServiceModel.Channels.Message.CreateMessage(mv, "http://tempuri.org/ITestFaultOpContract/Untyped_MethodReturns"); msgIn = channel.Untyped_MethodReturns(msgOut); if (msgIn.IsFault) { count--; System.ServiceModel.Channels.MessageFault mf = System.ServiceModel.Channels.MessageFault.CreateFault(msgIn, int.MaxValue); Assert.Equal(faultToThrow, mf.GetDetail <string>()); } //Variation_TypedToUntypedMethod try { channel2.Untyped_Method(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //Variation_TypedToUntypedMethodReturns try { channel2.Untyped_MethodReturns(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } Assert.Equal(0, count); } }
public void DatacontractFaults(string f) { var host = ServiceHelper.CreateWebHostBuilder <Startup>(_output).Build(); using (host) { host.Start(); var httpBinding = ClientHelper.GetBufferedModeBinding(); var factory = new System.ServiceModel.ChannelFactory <ClientContract.ITestDataContractFault>(httpBinding, new System.ServiceModel.EndpointAddress(new Uri("http://localhost:8080/BasicWcfService/DatacontractFaults.svc"))); var channel = factory.CreateChannel(); var factory2 = new System.ServiceModel.ChannelFactory <ClientContract.ITestDataContractFaultTypedClient>(httpBinding, new System.ServiceModel.EndpointAddress(new Uri("http://localhost:8080/BasicWcfService/DatacontractFaults.svc"))); var channel2 = factory2.CreateChannel(); //test variations int count = 9; try { channel.TwoWayVoid_Method(f); } catch (Exception e) { count--; FaultExceptionValidation(f, e); } try { string s = channel.TwoWay_Method(f); } catch (Exception e) { count--; FaultExceptionValidation(f, e); } try { Stream inputStream = new MemoryStream(); byte[] bytes = Encoding.UTF8.GetBytes(f.ToCharArray()); foreach (byte b in bytes) { inputStream.WriteByte(b); } inputStream.Position = 0; Stream outputStream = channel.TwoWayStream_Method(inputStream); StreamReader sr = new StreamReader(outputStream, Encoding.UTF8); string outputText = sr.ReadToEnd(); Assert.False(true, $"Error, Received Input: {outputText}"); } catch (Exception e) { count--; FaultExceptionValidation(f, e); } try { string response = channel.TwoWayAsync_Method(f).GetAwaiter().GetResult(); Assert.False(true, $"Error, Client received: {response}"); } catch (Exception e) { count--; FaultExceptionValidation(f, e); } try { var fmc = new ClientContract.FaultMsgContract(); fmc.ID = 123; fmc.Name = f; ClientContract.FaultMsgContract fmcResult = channel.MessageContract_Method(fmc); Assert.False(true, $"Error, Client received: {fmcResult.Name}"); } catch (Exception e) { count--; FaultExceptionValidation(f, e); } System.ServiceModel.Channels.Message msgOut = System.ServiceModel.Channels.Message.CreateMessage(System.ServiceModel.Channels.MessageVersion.Soap11, "http://tempuri.org/ITestDataContractFault/Untyped_Method", f); System.ServiceModel.Channels.Message msgIn = channel.Untyped_Method(msgOut); if (msgIn.IsFault) { System.ServiceModel.Channels.MessageFault mf = System.ServiceModel.Channels.MessageFault.CreateFault(msgIn, int.MaxValue); switch (f.ToLower()) { case "somefault": count--; ClientContract.SomeFault sf = mf.GetDetail <ClientContract.SomeFault>(); Assert.Equal(123456789, sf.ID); Assert.Equal("SomeFault", sf.message); break; case "outerfault": count--; ClientContract.OuterFault of = mf.GetDetail <ClientContract.OuterFault>(); sf = of.InnerFault; Assert.Equal(123456789, sf.ID); Assert.Equal("SomeFault as innerfault", sf.message); break; case "complexfault": count--; ClientContract.ComplexFault cf = mf.GetDetail <ClientContract.ComplexFault>(); string exp = "50:This is a test error string for fault tests.:123456789:SomeFault in complexfault:0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127:2147483647-214748364801-150-50:123456789:SomeFault in complexfaultnull234:Second somefault in complexfault"; Assert.Equal(exp, ComplexFaultToString(cf)); break; default: break; } } msgOut = System.ServiceModel.Channels.Message.CreateMessage(System.ServiceModel.Channels.MessageVersion.Soap11, "http://tempuri.org/ITestDataContractFault/Untyped_MethodReturns", f); msgIn = channel.Untyped_MethodReturns(msgOut); if (msgIn.IsFault) { System.ServiceModel.Channels.MessageFault mf = System.ServiceModel.Channels.MessageFault.CreateFault(msgIn, int.MaxValue); switch (f) { case "somefault": count--; ClientContract.SomeFault sf = mf.GetDetail <ClientContract.SomeFault>(); Assert.Equal(123456789, sf.ID); Assert.Equal("SomeFault", sf.message); break; case "outerfault": count--; ClientContract.OuterFault of = mf.GetDetail <ClientContract.OuterFault>(); sf = of.InnerFault; Assert.Equal(123456789, sf.ID); Assert.Equal("SomeFault as innerfault", sf.message); break; case "complexfault": count--; ClientContract.ComplexFault cf = mf.GetDetail <ClientContract.ComplexFault>(); string exp = "50:This is a test error string for fault tests.:123456789:SomeFault in complexfault:0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127:2147483647-214748364801-150-50:123456789:SomeFault in complexfaultnull234:Second somefault in complexfault"; Assert.Equal(exp, ComplexFaultToString(cf)); break; default: break; } } try { string response = channel2.Untyped_Method(f); } catch (Exception e) { count--; FaultExceptionValidation(f, e); } try { string response = channel2.Untyped_MethodReturns(f); } catch (Exception e) { count--; FaultExceptionValidation(f, e); } Assert.Equal(0, count); } }
private void SetConnection() { System.ServiceModel.BasicHttpBinding basicHttpBinding = new System.ServiceModel.BasicHttpBinding(); basicHttpBinding.MaxReceivedMessageSize = 2147483647; basicHttpBinding.MaxBufferSize = 2147483647; System.ServiceModel.EndpointAddress address = new System.ServiceModel.EndpointAddress("http://bi.syncfusion.com/OlapUWPTestService/OlapManager.svc/"); System.ServiceModel.ChannelFactory <Syncfusion.SampleBrowser.UWP.PivotClient.OlapManagerService.IOlapDataProvider> clientFactory = new System.ServiceModel.ChannelFactory <Syncfusion.SampleBrowser.UWP.PivotClient.OlapManagerService.IOlapDataProvider>(basicHttpBinding, address); clientChannel = clientFactory.CreateChannel(); }
private string Variation_Service_BaseDataContractMethod(string clientString) { // Create the proxy var httpBinding = ClientHelper.GetBufferedModeBinding(); System.ServiceModel.ChannelFactory <ClientContract.ISanityAParentB_857419_ContractBase> channelFactory = new System.ServiceModel.ChannelFactory <ClientContract.ISanityAParentB_857419_ContractBase>(httpBinding, new System.ServiceModel.EndpointAddress(new Uri("http://localhost:8080/BasicWcfService/basichttp.svc"))); // var clientProxy = this.GetProxy<ClientContract.ISanityAParentB_857419_ContractBase>(); foreach (var operation in channelFactory.Endpoint.Contract.Operations) { DataContractSerializerOperationBehavior behavior = operation.OperationBehaviors.FirstOrDefault( x => x.GetType() == typeof(DataContractSerializerOperationBehavior)) as DataContractSerializerOperationBehavior; behavior.DataContractResolver = new ManagerDataContractResolver <ClientContract.MyBaseDataType>(); } var clientProxy = channelFactory.CreateChannel(); // Send the two way message _output.WriteLine("Testing [Variation_Service_BaseTwoWayMethod]"); var dataObj = new ClientContract.MyBaseDataType(); dataObj.data = clientString; var result = (ClientContract.MyBaseDataType)clientProxy.DataContractMethod(dataObj); string response = result.data; _output.WriteLine($"Testing [Variation_Service_BaseTwoWayMethod] returned <{response}>"); return(response); }
public void DuplexEcho() { string testString = new string('a', 3000); IWebHost host = ServiceHelper.CreateWebHostBuilder <Startup>(_output).Build(); using (host) { System.ServiceModel.ChannelFactory <ServiceContract.IDuplexTestService> factory = null; ServiceContract.IDuplexTestService channel = null; host.Start(); try { System.ServiceModel.NetTcpBinding binding = ClientHelper.GetBufferedModeBinding(); var callback = new ServiceContract.DuplexTestCallback(); factory = new System.ServiceModel.DuplexChannelFactory <ServiceContract.IDuplexTestService>( new System.ServiceModel.InstanceContext(callback), binding, new System.ServiceModel.EndpointAddress(host.GetNetTcpAddressInUse() + Startup.DuplexRelativeAddress)); channel = factory.CreateChannel(); ((IChannel)channel).Open(); var registerSuccess = channel.RegisterDuplexChannel(); Assert.True(registerSuccess, "Registration was not successful"); channel.SendMessage(testString); Assert.Equal(1, callback.ReceivedMessages.Count); Assert.Equal(testString, callback.ReceivedMessages[0]); ((IChannel)channel).Close(); factory.Close(); } finally { ServiceHelper.CloseServiceModelObjects((IChannel)channel, factory); } } }
public void FaultOnDiffString() { var host = ServiceHelper.CreateWebHostBuilder <Startup>(_output).Build(); using (host) { host.Start(); var httpBinding = ClientHelper.GetBufferedModeBinding(); var factory = new System.ServiceModel.ChannelFactory <ClientContract.ITestFaultContractName>(httpBinding, new System.ServiceModel.EndpointAddress(new Uri("http://localhost:8080/BasicWcfService/TestFaultContractNameService.svc"))); var channel = factory.CreateChannel(); //test variations count int count = 21; string faultToThrow = "Test fault thrown from a service"; //variation method1 try { string s = channel.Method1(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method2 try { string s = channel.Method2(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method3 try { string s = channel.Method3(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method4 try { string s = channel.Method4(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method5 try { string s = channel.Method5(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method6 try { string s = channel.Method6(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method7 try { string s = channel.Method7(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method8 try { string s = channel.Method8(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method9 try { string s = channel.Method9(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method10 try { string s = channel.Method10(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method11 try { string s = channel.Method11(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method12 try { string s = channel.Method12(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method13 try { string s = channel.Method13(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method14 try { string s = channel.Method14(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method15 try { string s = channel.Method15(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method16 try { string s = channel.Method16(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method17 try { string s = channel.Method17(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method18 try { string s = channel.Method18(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method19 try { string s = channel.Method19(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method20 try { string s = channel.Method20(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } //variation method21 try { string s = channel.Method21(""); } catch (Exception e) { count--; Assert.NotNull(e); Assert.IsType <System.ServiceModel.FaultException <string> >(e); var ex = (System.ServiceModel.FaultException <string>)e; Assert.Equal(faultToThrow, ex.Detail.ToString()); } Assert.Equal(0, count); } }
public void VariousCollections() { var host = ServiceHelper.CreateWebHostBuilder <Startup>(_output).Build(); using (host) { ClientContract.ITaskCollectionsTest collectionsTest = null; System.ServiceModel.ChannelFactory <ClientContract.ITaskCollectionsTest> channelFactory = null; host.Start(); var httpBinding = ClientHelper.GetBufferedModeBinding(); channelFactory = new System.ServiceModel.ChannelFactory <ClientContract.ITaskCollectionsTest>(httpBinding, new System.ServiceModel.EndpointAddress(new Uri("http://localhost:8080/BasicWcfService/TaskCollectionsTest.svc"))); collectionsTest = channelFactory.CreateChannel(); Task[] array; array = new Task[5]; array[0] = collectionsTest.GetDictionary(); array[1] = collectionsTest.GetList(); array[2] = collectionsTest.GetSet(); array[3] = collectionsTest.GetQueue(); array[4] = collectionsTest.GetStack(); Task.WaitAll(array, TimeSpan.FromSeconds(30)); bool flag = true; Task <Dictionary <string, int> > task = array[0] as Task <Dictionary <string, int> >; Assert.True(task.Result.ContainsKey("Sam")); Assert.True(task.Result.ContainsKey("Sara")); if (!task.Result.ContainsKey("Sam") || !task.Result.ContainsKey("Sara")) { flag = false; _output.WriteLine("Expected collection to contain Sara and Sam."); _output.WriteLine("Actual Result"); foreach (string text in task.Result.Keys) { _output.WriteLine(text); } } Task <LinkedList <int> > task2 = array[1] as Task <LinkedList <int> >; Assert.Contains(100, task2.Result); Assert.Contains(40, task2.Result); if (!task2.Result.Contains(100) || !task2.Result.Contains(40)) { flag = false; _output.WriteLine("Expected collection to contain 100 and 40."); _output.WriteLine("Actual Result"); foreach (int num in task2.Result) { _output.WriteLine(num.ToString()); } } Task <HashSet <Book> > task3 = array[2] as Task <HashSet <Book> >; foreach (Book book in task3.Result) { Assert.False(!book.Name.Equals("Whoa") && !book.Name.Equals("Dipper")); if (!book.Name.Equals("Whoa") && !book.Name.Equals("Dipper")) { _output.WriteLine("Expected collection to contain Whoa and Dipper."); _output.WriteLine(string.Format("Actual Result {0}", book.Name)); flag = false; } } Task <Queue <string> > task4 = array[3] as Task <Queue <string> >; Assert.True(task4.Result.Contains("Panasonic")); Assert.True(task4.Result.Contains("Kodak")); if (!task4.Result.Contains("Panasonic") || !task4.Result.Contains("Kodak")) { flag = false; _output.WriteLine("Expected collection to contain Panasonic and Kodak."); _output.WriteLine("Actual Result"); foreach (string text2 in task4.Result) { _output.WriteLine(text2); } } Task <Stack <byte> > task5 = array[4] as Task <Stack <byte> >; Assert.True(task5.Result.Contains(45)); Assert.True(task5.Result.Contains(10)); if (!task5.Result.Contains(45) || !task5.Result.Contains(10)) { flag = false; _output.WriteLine("Expected collection to contain 45 and 10."); _output.WriteLine("Actual Result"); foreach (byte b in task5.Result) { _output.WriteLine(b.ToString()); } } if (!flag) { throw new Exception("Test Failed"); } } }
static void call() { using (var f = new System.ServiceModel.ChannelFactory<IServiceT>(new System.ServiceModel.NetTcpBinding(), addr)) { IServiceT proxy = f.CreateChannel(); WriteLine(proxy.gettime(1)); } }
public static void AttributeWithNameNamespaceActionReplyActionContract() { System.ServiceModel.ChannelFactory <IServiceModelServiceWithPropertiesSet> factory = DispatcherHelper.CreateChannelFactory <ServiceModelSimpleService, IServiceModelServiceWithPropertiesSet>(); factory.Open(); IServiceModelServiceWithPropertiesSet channel = factory.CreateChannel(); ((System.ServiceModel.Channels.IChannel)channel).Open(); string echo = channel.Echo("hello"); Assert.Equal("hello", echo); ((System.ServiceModel.Channels.IChannel)channel).Close(); factory.Close(); TestHelper.CloseServiceModelObjects((System.ServiceModel.Channels.IChannel)channel, factory); }
protected override Core.Services.ServiceOutcome DoWork() { string fileConflictBehavior = "Abort"; if (!String.IsNullOrEmpty(this.Instance.Configuration.Options["FileConflictBehavior"])) { fileConflictBehavior = this.Instance.Configuration.Options["FileConflictBehavior"]; } #region FTP Configuration /*===============================================================================================*/ if (String.IsNullOrEmpty(this.Instance.Configuration.Options["FtpServer"])) { throw new Exception("Missing Configuration Param , FtpServer"); } string FtpServer = this.Instance.Configuration.Options["FtpServer"]; //Get AllowedExtensions if (String.IsNullOrEmpty(this.Instance.Configuration.Options["AllowedExtensions"])) { throw new Exception("Missing Configuration Param , AllowedExtensions"); } string[] AllowedExtensions = this.Instance.Configuration.Options["AllowedExtensions"].Split('|'); if (String.IsNullOrEmpty(this.Instance.Configuration.Options["UsePassive"])) { throw new Exception("Missing Configuration Param , UsePassive"); } bool UsePassive = bool.Parse(this.Instance.Configuration.Options["UsePassive"]); if (String.IsNullOrEmpty(this.Instance.Configuration.Options["UseBinary"])) { throw new Exception("Missing Configuration Param , UsePassive"); } bool UseBinary = bool.Parse(this.Instance.Configuration.Options["UseBinary"]); //Get Permissions if (String.IsNullOrEmpty(this.Instance.Configuration.Options["UserID"])) { throw new Exception("Missing Configuration Param , UserID"); } string UserId = this.Instance.Configuration.Options["UserID"]; if (String.IsNullOrEmpty(this.Instance.Configuration.Options["Password"])) { throw new Exception("Missing Configuration Param , Password"); } string Password = Core.Utilities.Encryptor.Dec(this.Instance.Configuration.Options["Password"]); /*===============================================================================================*/ #endregion FtpWebRequest request; int filesCounter = 0; try { request = (FtpWebRequest)FtpWebRequest.Create(new Uri(FtpServer + "/")); request.UseBinary = UseBinary; request.UsePassive = UsePassive; request.Credentials = new NetworkCredential(UserId, Password); request.Method = WebRequestMethods.Ftp.ListDirectoryDetails; FtpWebResponse response = (FtpWebResponse)request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream()); string fileInfoAsString = reader.ReadLine(); while (fileInfoAsString != null) { //Checking AllowedExtensions Dictionary <string, string> fileInfo = GetFileInfo(fileInfoAsString); if ((fileConflictBehavior.Equals("Ignore")) || (!CheckFileConflict(fileInfo))) { //Get files with allowed extensions only. if (AllowedExtensions.Contains(Path.GetExtension(fileInfo["Name"]), StringComparer.OrdinalIgnoreCase)) { string SourceUrl = FtpServer + "/" + fileInfo["Name"]; System.ServiceModel.ChannelFactory <Edge.Core.Scheduling.IScheduleManager> c = new System.ServiceModel.ChannelFactory <Core.Scheduling.IScheduleManager>("shaybarchen"); c.Open(); IScheduleManager s = c.CreateChannel(); Core.SettingsCollection options = new Core.SettingsCollection(); this.Instance.Configuration.Options[Const.DeliveryServiceConfigurationOptions.SourceUrl] = SourceUrl; this.Instance.Configuration.Options["FileSize"] = fileInfo["Size"]; this.Instance.Configuration.Options["DeliveryFileName"] = fileInfo["Name"]; this.Instance.Configuration.Options["FileModifyDate"] = fileInfo["ModifyDate"]; s.AddToSchedule(this.Instance.Configuration.Options["FtpService"], this.Instance.AccountID, this.Instance.TimeScheduled, this.Instance.Configuration.Options); } } fileInfoAsString = reader.ReadLine(); filesCounter++; } reader.Close(); response.Close(); if (filesCounter == 0) { Core.Utilities.Log.Write("No files in FTP directory for account id " + this.Instance.AccountID.ToString(), Core.Utilities.LogMessageType.Information); } } catch (Exception e) { Core.Utilities.Log.Write( string.Format("Cannot connect FTP server for account ID:{0} Exception: {1}", this.Instance.AccountID.ToString(), e.Message), Core.Utilities.LogMessageType.Information); return(Edge.Core.Services.ServiceOutcome.Failure); } return(Core.Services.ServiceOutcome.Success); }
public void InitializeTest() { System.Threading.Monitor.Enter(arithmeticProxyTable); try { arithmeticProxyTable.TryGetValue(System.Threading.Thread.CurrentThread.ManagedThreadId, out arithmeticClient); if (((arithmeticClient == null) || (((System.ServiceModel.ICommunicationObject)(arithmeticClient)).State == System.ServiceModel.CommunicationState.Faulted))) { // The following line may need to be customised to select the appropriate binding from the configuration file System.ServiceModel.ChannelFactory <Contracts.IArithmetic> arithmeticFactory = new System.ServiceModel.ChannelFactory <Contracts.IArithmetic>("Arithmetic"); arithmeticClient = arithmeticFactory.CreateChannel(); ((System.ServiceModel.ICommunicationObject)(arithmeticClient)).Open(); arithmeticProxyTable[System.Threading.Thread.CurrentThread.ManagedThreadId] = arithmeticClient; } } finally { System.Threading.Monitor.Exit(arithmeticProxyTable); } System.Threading.Monitor.Enter(collectionsProxyTable); try { collectionsProxyTable.TryGetValue(System.Threading.Thread.CurrentThread.ManagedThreadId, out collectionsClient); if (((collectionsClient == null) || (((System.ServiceModel.ICommunicationObject)(collectionsClient)).State == System.ServiceModel.CommunicationState.Faulted))) { // The following line may need to be customised to select the appropriate binding from the configuration file System.ServiceModel.ChannelFactory <Contracts.ICollections> collectionsFactory = new System.ServiceModel.ChannelFactory <Contracts.ICollections>("Collections"); collectionsClient = collectionsFactory.CreateChannel(); ((System.ServiceModel.ICommunicationObject)(collectionsClient)).Open(); collectionsProxyTable[System.Threading.Thread.CurrentThread.ManagedThreadId] = collectionsClient; } } finally { System.Threading.Monitor.Exit(collectionsProxyTable); } System.Threading.Monitor.Enter(customContractsProxyTable); try { customContractsProxyTable.TryGetValue(System.Threading.Thread.CurrentThread.ManagedThreadId, out customContractsClient); if (((customContractsClient == null) || (((System.ServiceModel.ICommunicationObject)(customContractsClient)).State == System.ServiceModel.CommunicationState.Faulted))) { // The following line may need to be customised to select the appropriate binding from the configuration file System.ServiceModel.ChannelFactory <Contracts.Custom.ICustomContracts> customContractsFactory = new System.ServiceModel.ChannelFactory <Contracts.Custom.ICustomContracts>("Custom"); customContractsClient = customContractsFactory.CreateChannel(); ((System.ServiceModel.ICommunicationObject)(customContractsClient)).Open(); customContractsProxyTable[System.Threading.Thread.CurrentThread.ManagedThreadId] = customContractsClient; } } finally { System.Threading.Monitor.Exit(customContractsProxyTable); } System.Threading.Monitor.Enter(customContracts2ProxyTable); try { customContracts2ProxyTable.TryGetValue(System.Threading.Thread.CurrentThread.ManagedThreadId, out customContracts2Client); if (((customContracts2Client == null) || (((System.ServiceModel.ICommunicationObject)(customContracts2Client)).State == System.ServiceModel.CommunicationState.Faulted))) { // The following line may need to be customised to select the appropriate binding from the configuration file System.ServiceModel.ChannelFactory <Contracts.Custom.ICustomContracts2> customContracts2Factory = new System.ServiceModel.ChannelFactory <Contracts.Custom.ICustomContracts2>("Custom2"); customContracts2Client = customContracts2Factory.CreateChannel(); ((System.ServiceModel.ICommunicationObject)(customContracts2Client)).Open(); customContracts2ProxyTable[System.Threading.Thread.CurrentThread.ManagedThreadId] = customContracts2Client; } } finally { System.Threading.Monitor.Exit(customContracts2ProxyTable); } System.Threading.Monitor.Enter(bufferedStreamServiceProxyTable); try { bufferedStreamServiceProxyTable.TryGetValue(System.Threading.Thread.CurrentThread.ManagedThreadId, out bufferedStreamServiceClient); if (((bufferedStreamServiceClient == null) || (((System.ServiceModel.ICommunicationObject)(bufferedStreamServiceClient)).State == System.ServiceModel.CommunicationState.Faulted))) { // The following line may need to be customised to select the appropriate binding from the configuration file System.ServiceModel.ChannelFactory <Contracts.IBufferedStreamService> bufferedStreamServiceFactory = new System.ServiceModel.ChannelFactory <Contracts.IBufferedStreamService>("BufferedStreams"); bufferedStreamServiceClient = bufferedStreamServiceFactory.CreateChannel(); ((System.ServiceModel.ICommunicationObject)(bufferedStreamServiceClient)).Open(); bufferedStreamServiceProxyTable[System.Threading.Thread.CurrentThread.ManagedThreadId] = bufferedStreamServiceClient; } } finally { System.Threading.Monitor.Exit(bufferedStreamServiceProxyTable); } System.Threading.Monitor.Enter(streamedStreamServiceProxyTable); try { streamedStreamServiceProxyTable.TryGetValue(System.Threading.Thread.CurrentThread.ManagedThreadId, out streamedStreamServiceClient); if (((streamedStreamServiceClient == null) || (((System.ServiceModel.ICommunicationObject)(streamedStreamServiceClient)).State == System.ServiceModel.CommunicationState.Faulted))) { // The following line may need to be customised to select the appropriate binding from the configuration file System.ServiceModel.ChannelFactory <Contracts.IStreamedStreamService> streamedStreamServiceFactory = new System.ServiceModel.ChannelFactory <Contracts.IStreamedStreamService>("StreamedStreams"); streamedStreamServiceClient = streamedStreamServiceFactory.CreateChannel(); ((System.ServiceModel.ICommunicationObject)(streamedStreamServiceClient)).Open(); streamedStreamServiceProxyTable[System.Threading.Thread.CurrentThread.ManagedThreadId] = streamedStreamServiceClient; } } finally { System.Threading.Monitor.Exit(streamedStreamServiceProxyTable); } System.Threading.Monitor.Enter(shapeServiceProxyTable); try { shapeServiceProxyTable.TryGetValue(System.Threading.Thread.CurrentThread.ManagedThreadId, out shapeServiceClient); if (((shapeServiceClient == null) || (((System.ServiceModel.ICommunicationObject)(shapeServiceClient)).State == System.ServiceModel.CommunicationState.Faulted))) { // The following line may need to be customised to select the appropriate binding from the configuration file System.ServiceModel.ChannelFactory <Contracts.IShapeService> shapeServiceFactory = new System.ServiceModel.ChannelFactory <Contracts.IShapeService>("Shape"); shapeServiceClient = shapeServiceFactory.CreateChannel(); ((System.ServiceModel.ICommunicationObject)(shapeServiceClient)).Open(); shapeServiceProxyTable[System.Threading.Thread.CurrentThread.ManagedThreadId] = shapeServiceClient; } } finally { System.Threading.Monitor.Exit(shapeServiceProxyTable); } System.Threading.Monitor.Enter(serviceKnownTypeProxyTable); try { serviceKnownTypeProxyTable.TryGetValue(System.Threading.Thread.CurrentThread.ManagedThreadId, out serviceKnownTypeClient); if (((serviceKnownTypeClient == null) || (((System.ServiceModel.ICommunicationObject)(serviceKnownTypeClient)).State == System.ServiceModel.CommunicationState.Faulted))) { // The following line may need to be customised to select the appropriate binding from the configuration file System.ServiceModel.ChannelFactory <Contracts.IServiceKnownType> serviceKnownTypeFactory = new System.ServiceModel.ChannelFactory <Contracts.IServiceKnownType>("ServiceKnownType"); serviceKnownTypeClient = serviceKnownTypeFactory.CreateChannel(); ((System.ServiceModel.ICommunicationObject)(serviceKnownTypeClient)).Open(); serviceKnownTypeProxyTable[System.Threading.Thread.CurrentThread.ManagedThreadId] = serviceKnownTypeClient; } } finally { System.Threading.Monitor.Exit(serviceKnownTypeProxyTable); } System.Threading.Monitor.Enter(sharePricesProxyTable); try { sharePricesProxyTable.TryGetValue(System.Threading.Thread.CurrentThread.ManagedThreadId, out sharePricesClient); if (((sharePricesClient == null) || (((System.ServiceModel.ICommunicationObject)(sharePricesClient)).State == System.ServiceModel.CommunicationState.Faulted))) { // The following line may need to be customised to select the appropriate binding from the configuration file System.ServiceModel.DuplexChannelFactory <Contracts.ISharePrices> sharePricesFactory = new System.ServiceModel.DuplexChannelFactory <Contracts.ISharePrices>(new InstanceContext(new SharePricesCallback()), "SharePrices"); sharePricesClient = sharePricesFactory.CreateChannel(); ((System.ServiceModel.ICommunicationObject)(sharePricesClient)).Open(); sharePricesProxyTable[System.Threading.Thread.CurrentThread.ManagedThreadId] = sharePricesClient; } } finally { System.Threading.Monitor.Exit(sharePricesProxyTable); } System.Threading.Monitor.Enter(dataSetsProxyTable); try { dataSetsProxyTable.TryGetValue(System.Threading.Thread.CurrentThread.ManagedThreadId, out dataSetsClient); if (((dataSetsClient == null) || (((System.ServiceModel.ICommunicationObject)(dataSetsClient)).State == System.ServiceModel.CommunicationState.Faulted))) { // The following line may need to be customised to select the appropriate binding from the configuration file System.ServiceModel.ChannelFactory <Contracts.IDataSets> dataSetsFactory = new System.ServiceModel.ChannelFactory <Contracts.IDataSets>("DataSets"); dataSetsClient = dataSetsFactory.CreateChannel(); ((System.ServiceModel.ICommunicationObject)(dataSetsClient)).Open(); dataSetsProxyTable[System.Threading.Thread.CurrentThread.ManagedThreadId] = dataSetsClient; } } finally { System.Threading.Monitor.Exit(dataSetsProxyTable); } }