internal WebHttpSecurity () { // there is no public constructor for transport ... #if !NET_2_1 Transport = new BasicHttpBinding ().Security.Transport; #endif }
public void FlowRequiredButNotSupported() { ServiceHost host = new ServiceHost(typeof(TestService2)); BasicHttpBinding binding = new BasicHttpBinding(); // Does not support transactions string address = "http://localhost:8080/" + Guid.NewGuid().ToString(); host.AddServiceEndpoint(typeof(ITestContract2), binding, address); host.Open(); }
public MainViewModel() { this.PropertyChanged += MainViewModel_PropertyChanged; this.Productos = new ObservableCollection <Models.ProductoItem>(); this.Productos.CollectionChanged += Productos_CollectionChanged; this.AddCommand = new Command(() => { var com = new Helpers.CommonHelper(); var ser = com.PrepareSerie(this.Serie); var item = _proxy.ScanProducto(ser, this.Sucursal); if (item != null) { this.Serie = null; this.Productos.Add(new Models.ProductoItem { Item = new Models.Producto { Id = item.Id, Serie = item.Serie, //public string Marca { get; set; } //public string Modelo { get; set; } Precio = item.Precio, HasImage = item.HasImage } }); } //this.ImageUrl = String.Format($"{Constants.Parameters.ServiceUrl}/Images/Producto?marca={0}&modelo={1}", "CTA", 83); }, () => !String.IsNullOrEmpty(this.Serie)); this.SaleCommand = new Command(() => { var request = new SirCoPOS.Contracts.Entities.SaleRequest { Sucursal = this.Sucursal, Pagar = this.Pagar, Series = this.Productos.Select(i => i.Item.Serie) }; var res = _proxy.Sale(request); if (res != null) { MessagingCenter.Send(new Messages.Alert { Message = $"Folio: {res.Folio}" }, ""); } else { MessagingCenter.Send(new Messages.Alert { Message = "error" }, ""); } this.Productos.Clear(); this.Pagar = null; }, () => (this.Total ?? 0) > 0 && this.Pagar == this.Total); if (this.IsInDesignMode) { this.Productos.Add(new Models.ProductoItem { Item = new Models.Producto { Serie = "123" } }); this.Productos.Add(new Models.ProductoItem { Item = new Models.Producto { Serie = "456" } }); this.Productos.Add(new Models.ProductoItem { Item = new Models.Producto { Serie = "789" } }); } if (!this.IsInDesignMode) { var myBinding = new BasicHttpBinding(); var myEndpoint = new EndpointAddress($"{Constants.Parameters.ServiceUrl}/Service.svc"); _proxy = new System.ServiceModel.ChannelFactory <Contracts.Services.IService>(myBinding, myEndpoint).CreateChannel(); } }
void ConfigureSecurityMode(Binding binding) { SecurityModeEx securityMode = SecurityModeEx.None; bool enabled = false; if (binding is NetTcpBinding) { NetTcpBinding tcpBinding = binding as NetTcpBinding; switch (tcpBinding.Security.Mode) { case SecurityMode.Message: { securityMode = SecurityModeEx.Message; break; } case SecurityMode.None: { securityMode = SecurityModeEx.None; break; } case SecurityMode.Transport: { securityMode = SecurityModeEx.Transport; break; } case SecurityMode.TransportWithMessageCredential: { securityMode = SecurityModeEx.Mixed; break; } } enabled = true; } if (binding is NetNamedPipeBinding) { NetNamedPipeBinding pipeBinding = binding as NetNamedPipeBinding; switch (pipeBinding.Security.Mode) { case NetNamedPipeSecurityMode.None: { securityMode = SecurityModeEx.None; break; } case NetNamedPipeSecurityMode.Transport: { securityMode = SecurityModeEx.Transport; break; } } enabled = true; } if (binding is NetMsmqBinding) { NetMsmqBinding msmqBinding = binding as NetMsmqBinding; switch (msmqBinding.Security.Mode) { case NetMsmqSecurityMode.Both: { securityMode = SecurityModeEx.Both; break; } case NetMsmqSecurityMode.Message: { securityMode = SecurityModeEx.Message; break; } case NetMsmqSecurityMode.None: { securityMode = SecurityModeEx.None; break; } case NetMsmqSecurityMode.Transport: { securityMode = SecurityModeEx.Transport; break; } } enabled = true; } if (binding is BasicHttpBinding) { BasicHttpBinding basicBinding = binding as BasicHttpBinding; switch (basicBinding.Security.Mode) { case BasicHttpSecurityMode.Message: { securityMode = SecurityModeEx.Message; break; } case BasicHttpSecurityMode.None: { securityMode = SecurityModeEx.None; break; } case BasicHttpSecurityMode.Transport: { securityMode = SecurityModeEx.Transport; break; } case BasicHttpSecurityMode.TransportCredentialOnly: { securityMode = SecurityModeEx.Transport; break; } case BasicHttpSecurityMode.TransportWithMessageCredential: { securityMode = SecurityModeEx.Mixed; break; } } enabled = true; } if (binding is WSHttpBinding) { WSHttpBinding wsBinding = binding as WSHttpBinding; switch (wsBinding.Security.Mode) { case SecurityMode.Message: { securityMode = SecurityModeEx.Message; break; } case SecurityMode.None: { securityMode = SecurityModeEx.None; break; } case SecurityMode.Transport: { securityMode = SecurityModeEx.Transport; break; } case SecurityMode.TransportWithMessageCredential: { securityMode = SecurityModeEx.Mixed; break; } } enabled = true; } if (binding is WSDualHttpBinding) { WSDualHttpBinding wsDualBinding = binding as WSDualHttpBinding; switch (wsDualBinding.Security.Mode) { case WSDualHttpSecurityMode.Message: { securityMode = SecurityModeEx.Message; break; } case WSDualHttpSecurityMode.None: { securityMode = SecurityModeEx.None; break; } } enabled = true; } if (binding is NetPeerTcpBinding) { NetPeerTcpBinding peerBinding = binding as NetPeerTcpBinding; switch (peerBinding.Security.Mode) { case SecurityMode.Message: { securityMode = SecurityModeEx.Message; break; } case SecurityMode.None: { securityMode = SecurityModeEx.None; break; } case SecurityMode.Transport: { securityMode = SecurityModeEx.Transport; break; } case SecurityMode.TransportWithMessageCredential: { securityMode = SecurityModeEx.Transport; break; } } enabled = true; } if (binding is WSFederationHttpBinding) { WSFederationHttpBinding federatedBinding = binding as WSFederationHttpBinding; switch (federatedBinding.Security.Mode) { case WSFederationHttpSecurityMode.Message: { securityMode = SecurityModeEx.Message; break; } case WSFederationHttpSecurityMode.None: { securityMode = SecurityModeEx.None; break; } case WSFederationHttpSecurityMode.TransportWithMessageCredential: { securityMode = SecurityModeEx.Mixed; break; } } enabled = true; } if (binding is NetTcpRelayBinding) { NetTcpRelayBinding tcpRelayBinding = binding as NetTcpRelayBinding; switch (tcpRelayBinding.Security.Mode) { case EndToEndSecurityMode.Message: { securityMode = SecurityModeEx.Message; break; } case EndToEndSecurityMode.None: { securityMode = SecurityModeEx.None; break; } case EndToEndSecurityMode.Transport: { securityMode = SecurityModeEx.Transport; break; } case EndToEndSecurityMode.TransportWithMessageCredential: { securityMode = SecurityModeEx.Mixed; break; } } enabled = true; } if (binding is BasicHttpRelayBinding) { BasicHttpRelayBinding basicRelayBinding = binding as BasicHttpRelayBinding; switch (basicRelayBinding.Security.Mode) { case EndToEndBasicHttpSecurityMode.Message: { securityMode = SecurityModeEx.Message; break; } case EndToEndBasicHttpSecurityMode.None: { securityMode = SecurityModeEx.None; break; } case EndToEndBasicHttpSecurityMode.Transport: { securityMode = SecurityModeEx.Transport; break; } case EndToEndBasicHttpSecurityMode.TransportWithMessageCredential: { securityMode = SecurityModeEx.Mixed; break; } } enabled = true; } if (binding is NetOnewayRelayBinding) { NetOnewayRelayBinding onewayRelayBinding = binding as NetOnewayRelayBinding; switch (onewayRelayBinding.Security.Mode) { case EndToEndSecurityMode.Message: { securityMode = SecurityModeEx.Message; break; } case EndToEndSecurityMode.None: { securityMode = SecurityModeEx.None; break; } case EndToEndSecurityMode.Transport: { securityMode = SecurityModeEx.Transport; break; } case EndToEndSecurityMode.TransportWithMessageCredential: { securityMode = SecurityModeEx.Mixed; break; } } enabled = true; } if (binding is CustomBinding) { enabled = false; } m_NoneRadioButton.Checked = securityMode == SecurityModeEx.None; m_TransportRadioButton.Checked = securityMode == SecurityModeEx.Transport; m_MessageRadioButton.Checked = securityMode == SecurityModeEx.Message; m_MixedRadioButton.Checked = securityMode == SecurityModeEx.Mixed; m_BothRadioButton.Checked = securityMode == SecurityModeEx.Both; m_NoneRadioButton.Enabled = enabled; m_TransportRadioButton.Enabled = enabled; m_MessageRadioButton.Enabled = enabled; m_MixedRadioButton.Enabled = enabled; m_BothRadioButton.Enabled = enabled; }
public static void XmlSFAttributeDocLitDualNsTest() { BasicHttpBinding binding = null; EndpointAddress endpointAddress = null; ChannelFactory <ICalculatorDocLit> factory1 = null; ChannelFactory <IHelloWorldDocLit> factory2 = null; ICalculatorDocLit serviceProxy1 = null; IHelloWorldDocLit serviceProxy2 = null; // *** SETUP *** \\ binding = new BasicHttpBinding(); endpointAddress = new EndpointAddress(Endpoints.BasicHttpDocLitDualNs_Address); factory1 = new ChannelFactory <ICalculatorDocLit>(binding, endpointAddress); serviceProxy1 = factory1.CreateChannel(); factory2 = new ChannelFactory <IHelloWorldDocLit>(binding, endpointAddress); serviceProxy2 = factory2.CreateChannel(); // *** EXECUTE Variation *** \\ try { var dateTime = DateTime.Now; string testStr = "test string"; var intParams = new IntParams() { P1 = 5, P2 = 10 }; var floatParams = new FloatParams() { P1 = 5.0f, P2 = 10.0f }; var byteParams = new ByteParams() { P1 = 5, P2 = 10 }; Assert.Equal(3, serviceProxy1.Sum2(1, 2)); Assert.Equal(intParams.P1 + intParams.P2, serviceProxy1.Sum(intParams)); Assert.Equal(string.Format("{0}{1}", intParams.P1, intParams.P2), serviceProxy1.Concatenate(intParams)); Assert.Equal((float)(floatParams.P1 / floatParams.P2), serviceProxy1.Divide(floatParams)); Assert.Equal((new byte[] { byteParams.P1, byteParams.P2 }), serviceProxy1.CreateSet(byteParams)); Assert.Equal(dateTime, serviceProxy1.ReturnInputDateTime(dateTime)); Guid guid = Guid.NewGuid(); serviceProxy1.AddIntParams(guid, intParams); IntParams outputIntParams = serviceProxy1.GetAndRemoveIntParams(guid); Assert.NotNull(outputIntParams); Assert.Equal(intParams.P1, outputIntParams.P1); Assert.Equal(intParams.P2, outputIntParams.P2); Guid guid2 = Guid.NewGuid(); serviceProxy2.AddString(guid2, testStr); Assert.Equal(testStr, serviceProxy2.GetAndRemoveString(guid2)); } catch (Exception ex) { Assert.True(false, ex.Message); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy1); ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy2); } }
public static GetEventsResult GetEventsAroundPOI(LocationPoint PointOfInterest) { BasicHttpBinding basicHttpBinding = new BasicHttpBinding(); EndpointAddress endpointAddress = new EndpointAddress("http://localhost:56071/CaloomMainService.svc"); ICaloomMainService service = new ChannelFactory< ICaloomMainService >(basicHttpBinding, endpointAddress).CreateChannel(); var serviceResponse = service.GetEventsAroundPOI(PointOfInterest); return serviceResponse; }
public static void ServiceRestart_Throws_CommunicationException() { StringBuilder errorBuilder = new StringBuilder(); string restartServiceAddress = ""; BasicHttpBinding binding = new BasicHttpBinding(); try { using (ChannelFactory <IWcfService> factory = new ChannelFactory <IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic))) { IWcfService serviceProxy = factory.CreateChannel(); restartServiceAddress = serviceProxy.GetRestartServiceEndpoint(); } } catch (Exception e) { string error = String.Format("Unexpected exception thrown while calling the 'GetRestartServiceEndpoint' operation. {0}", e.ToString()); if (e.InnerException != null) { error += String.Format("\r\nInnerException:\r\n{0}", e.InnerException.ToString()); } errorBuilder.AppendLine(error); } if (errorBuilder.Length == 0) { // Get the Service host name and replace localhost with it UriBuilder builder = new UriBuilder(Endpoints.HttpBaseAddress_Basic); string hostName = builder.Uri.Host; restartServiceAddress = restartServiceAddress.Replace("[HOST]", hostName); //On .NET Native retail, exception message is stripped to include only parameter string expectExceptionMsg = restartServiceAddress; try { using (ChannelFactory <IWcfRestartService> factory = new ChannelFactory <IWcfRestartService>(binding, new EndpointAddress(restartServiceAddress))) { // Get the last portion of the restart service url which is a Guid and convert it back to a Guid // This is needed by the RestartService operation as a Dictionary key to get the ServiceHost string uniqueIdentifier = restartServiceAddress.Substring(restartServiceAddress.LastIndexOf("/") + 1); Guid guid = new Guid(uniqueIdentifier); IWcfRestartService serviceProxy = factory.CreateChannel(); serviceProxy.RestartService(guid); } errorBuilder.AppendLine("Expected CommunicationException exception, but no exception thrown."); } catch (Exception e) { if (e.GetType() == typeof(CommunicationException)) { if (e.Message.Contains(expectExceptionMsg)) { } else { errorBuilder.AppendLine(string.Format("Expected exception message contains: {0}, actual: {1}", expectExceptionMsg, e.Message)); } } else { errorBuilder.AppendLine(string.Format("Expected exception: {0}, actual: {1}/n Exception was: {2}", "CommunicationException", e.GetType(), e.ToString())); } } } Assert.True(errorBuilder.Length == 0, string.Format("Test Scenario: ServiceRestart_Throws_CommunicationException FAILED with the following errors: {0}", errorBuilder)); }
private void InitializeServiceClient() { BasicHttpBinding binding = CreateBasicHttp(); _client = new Service1Client(binding, EndPoint); }
/// <summary> /// Logs into the specified project/domain combination /// </summary> /// <param name="sender">The sending object</param> /// <param name="e">The event arguments</param> private void btnLogin_Click(object sender, System.EventArgs e) { //Make sure that a login was entered if (this.txtLogin.Text.Trim() == "") { MessageBox.Show("You need to enter a SpiraTest login", "Authentication Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } //Make sure that a server was entered if (this.txtServer.Text.Trim() == "") { MessageBox.Show("You need to enter a SpiraTest web-server URL", "Authentication Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } //Store the info in settings for later Properties.Settings.Default.SpiraUrl = this.txtServer.Text.Trim(); Properties.Settings.Default.SpiraUserName = this.txtLogin.Text.Trim(); if (chkPassword.Checked) { Properties.Settings.Default.SpiraPassword = this.txtPassword.Text; //Don't trim in case it contains a space } else { Properties.Settings.Default.SpiraPassword = ""; } Properties.Settings.Default.Save(); //If we're not remembering the password, set the property again, now after the save for temporary access by the //import thread if (!chkPassword.Checked) { Properties.Settings.Default.SpiraPassword = this.txtPassword.Text; } //Default the Start Import and login button to disabled this.btnImport.Enabled = false; this.btnLogin.Enabled = false; this.progressBar1.Style = ProgressBarStyle.Marquee; try { //Instantiate the web-service proxy class and set the URL from the text box SpiraImportProxy = new SpiraImportExport.ImportExportClient(); //Set the end-point and allow cookies SpiraImportProxy.Endpoint.Address = new EndpointAddress(Properties.Settings.Default.SpiraUrl + IMPORT_WEB_SERVICES_URL); BasicHttpBinding httpBinding = (BasicHttpBinding)SpiraImportProxy.Endpoint.Binding; ConfigureBinding(httpBinding, SpiraImportProxy.Endpoint.Address.Uri); //Authenticate asynchronously SpiraImportProxy.Connection_Authenticate2Completed += new EventHandler <SpiraImportExport.Connection_Authenticate2CompletedEventArgs>(spiraImportExport_Connection_Authenticate2Completed); SpiraImportProxy.Connection_Authenticate2Async(Properties.Settings.Default.SpiraUserName, this.txtPassword.Text, API_PLUGIN_NAME); } catch (TimeoutException exception) { // Handle the timeout exception. this.progressBar1.Style = ProgressBarStyle.Blocks; this.btnLogin.Enabled = true; SpiraImportProxy.Abort(); MessageBox.Show("A timeout error occurred! (" + exception.Message + ")", "Timeout Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (CommunicationException exception) { // Handle the communication exception. this.progressBar1.Style = ProgressBarStyle.Blocks; this.btnLogin.Enabled = true; SpiraImportProxy.Abort(); MessageBox.Show("A communication error occurred! (" + exception.Message + ")", "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public static void LoadAboutAgentData() { Service00000Client LService00000Client = null; BasicHttpBinding LBasicHttpBinding = null; EndpointAddress LEndpointAddress = null; List <string> LListStrWcfArgs = new List <string>(); string LStrVerificationCode104 = string.Empty; try { LStrVerificationCode104 = App.CreateVerificationCode(EncryptionAndDecryption.UMPKeyAndIVType.M104); IDataTable11005 = new DataTable(); IDataTable11006 = new DataTable(); IDataTable11101 = new DataTable(); IDataTable11009 = new DataTable(); IDataTable11201SA = new DataTable(); IDataTable11201UA = new DataTable(); IDataTable11201UO = new DataTable(); IDataTable11201UU = new DataTable(); LListStrWcfArgs.Add(GClassSessionInfo.DatabaseInfo.TypeID.ToString()); LListStrWcfArgs.Add(GClassSessionInfo.DatabaseInfo.GetConnectionString()); LListStrWcfArgs.Add(GClassSessionInfo.RentInfo.Token); LListStrWcfArgs.Add(GClassSessionInfo.UserInfo.UserID.ToString()); LBasicHttpBinding = WebHelper.CreateBasicHttpBinding(); LEndpointAddress = WebHelper.CreateEndpointAddress(App.GClassSessionInfo.AppServerInfo, "Service00000"); OperationDataArgs LWCFOperationReturn = new OperationDataArgs(); LService00000Client = new Service00000Client(LBasicHttpBinding, LEndpointAddress); LWCFOperationReturn = LService00000Client.OperationMethodA(26, LListStrWcfArgs); if (LWCFOperationReturn.BoolReturn) { IDataTable11005 = LWCFOperationReturn.ListDataSetReturn[0].Tables[0]; IDataTable11006 = LWCFOperationReturn.ListDataSetReturn[1].Tables[0]; IDataTable11101 = LWCFOperationReturn.ListDataSetReturn[2].Tables[0]; IDataTable11009 = LWCFOperationReturn.ListDataSetReturn[3].Tables[0]; IDataTable11201SA = LWCFOperationReturn.ListDataSetReturn[4].Tables[0]; IDataTable11201UA = LWCFOperationReturn.ListDataSetReturn[5].Tables[0]; IDataTable11201UO = LWCFOperationReturn.ListDataSetReturn[6].Tables[0]; IDataTable11201UU = LWCFOperationReturn.ListDataSetReturn[7].Tables[0]; foreach (DataRow LDataRowSingleAgent in IDataTable11101.Rows) { if (LDataRowSingleAgent["C002"].ToString() != "1") { continue; } LDataRowSingleAgent["C017"] = EncryptionAndDecryption.EncryptDecryptString(LDataRowSingleAgent["C017"].ToString(), LStrVerificationCode104, EncryptionAndDecryption.UMPKeyAndIVType.M104); } } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { if (LService00000Client != null) { if (LService00000Client.State == CommunicationState.Opened) { LService00000Client.Close(); } } } }
void ConfigureCredentialsType(Binding binding) { CredentialTypeEx credentialType = CredentialTypeEx.None; bool enabled = false; if (binding is NetTcpBinding) { NetTcpBinding tcpBinding = binding as NetTcpBinding; switch (tcpBinding.Security.Mode) { case SecurityMode.Message: { credentialType = ConvertCredentials(tcpBinding.Security.Message.ClientCredentialType); break; } case SecurityMode.None: { credentialType = CredentialTypeEx.None; break; } case SecurityMode.Transport: { credentialType = ConvertCredentials(tcpBinding.Security.Transport.ClientCredentialType); break; } } enabled = true; } if (binding is NetNamedPipeBinding) { NetNamedPipeBinding pipeBinding = binding as NetNamedPipeBinding; switch (pipeBinding.Security.Mode) { case NetNamedPipeSecurityMode.None: { credentialType = CredentialTypeEx.None; break; } case NetNamedPipeSecurityMode.Transport: { credentialType = CredentialTypeEx.Windows; break; } } enabled = true; } if (binding is NetMsmqBinding) { NetMsmqBinding msmqBinding = binding as NetMsmqBinding; switch (msmqBinding.Security.Mode) { case NetMsmqSecurityMode.Both: case NetMsmqSecurityMode.Message: { credentialType = ConvertCredentials(msmqBinding.Security.Message.ClientCredentialType); break; } case NetMsmqSecurityMode.None: { credentialType = CredentialTypeEx.None; break; } case NetMsmqSecurityMode.Transport: { credentialType = ConvertCredentials(msmqBinding.Security.Transport.MsmqAuthenticationMode); break; } } enabled = true; } if (binding is BasicHttpBinding) { BasicHttpBinding basicBinding = binding as BasicHttpBinding; switch (basicBinding.Security.Mode) { case BasicHttpSecurityMode.Message: case BasicHttpSecurityMode.TransportWithMessageCredential: { credentialType = ConvertCredentials(basicBinding.Security.Message.ClientCredentialType); break; } case BasicHttpSecurityMode.None: { credentialType = CredentialTypeEx.None; break; } case BasicHttpSecurityMode.Transport: case BasicHttpSecurityMode.TransportCredentialOnly: { credentialType = ConvertCredentials(basicBinding.Security.Transport.ClientCredentialType); break; } } enabled = true; } if (binding is WSHttpBinding) { WSHttpBinding wsBinding = binding as WSHttpBinding; switch (wsBinding.Security.Mode) { case SecurityMode.TransportWithMessageCredential: case SecurityMode.Message: { credentialType = ConvertCredentials(wsBinding.Security.Message.ClientCredentialType); break; } case SecurityMode.None: { credentialType = CredentialTypeEx.None; break; } case SecurityMode.Transport: { credentialType = ConvertCredentials(wsBinding.Security.Transport.ClientCredentialType); break; } } enabled = true; } if (binding is WSDualHttpBinding) { WSDualHttpBinding wsDualBinding = binding as WSDualHttpBinding; switch (wsDualBinding.Security.Mode) { case WSDualHttpSecurityMode.Message: { credentialType = ConvertCredentials(wsDualBinding.Security.Message.ClientCredentialType); break; } case WSDualHttpSecurityMode.None: { credentialType = CredentialTypeEx.None; break; } } enabled = true; } if (binding is NetPeerTcpBinding) { NetPeerTcpBinding peerBinding = binding as NetPeerTcpBinding; switch (peerBinding.Security.Mode) { case SecurityMode.None: { credentialType = CredentialTypeEx.None; break; } case SecurityMode.Transport: { credentialType = ConvertCredentials(peerBinding.Security.Transport.CredentialType); break; } } enabled = true; } if (binding is WSFederationHttpBinding) { credentialType = CredentialTypeEx.Token; enabled = true; } if (binding is NetTcpRelayBinding) { credentialType = CredentialTypeEx.Token; enabled = true; } if (binding is BasicHttpRelayBinding) { credentialType = CredentialTypeEx.Token; enabled = true; } m_NoCredentialsRadioButton.Checked = credentialType == CredentialTypeEx.None; m_WindowsCredentialsRadioButton.Checked = credentialType == CredentialTypeEx.Windows; m_UsernameCredentialsRadioButton.Checked = credentialType == CredentialTypeEx.Username; m_CertificateCredentialsRadioButton.Checked = credentialType == CredentialTypeEx.Certificate; m_TokenRadioButton.Checked = credentialType == CredentialTypeEx.Token; m_NoCredentialsRadioButton.Enabled = enabled; m_WindowsCredentialsRadioButton.Enabled = enabled; m_UsernameCredentialsRadioButton.Enabled = enabled; m_CertificateCredentialsRadioButton.Enabled = enabled; m_TokenRadioButton.Enabled = enabled; }
public void UseHttps_returns_binding(BasicHttpBinding binding) { var result = BindingExtensions.UseHttps(binding); Assert.That(result, Is.SameAs(binding)); }
private void Send(NLogEvents events, IEnumerable <AsyncLogEventInfo> asyncContinuations) { #if WCF_SUPPORTED WcfLogReceiverClient client; if (string.IsNullOrEmpty(this.EndpointConfigurationName)) { // endpoint not specified - use BasicHttpBinding Binding binding; #if !SILVERLIGHT2 if (this.UseBinaryEncoding) { binding = new CustomBinding(new BinaryMessageEncodingBindingElement(), new HttpTransportBindingElement()); } else #endif { binding = new BasicHttpBinding(); } client = new WcfLogReceiverClient(binding, new EndpointAddress(this.EndpointAddress)); } else { client = new WcfLogReceiverClient(this.EndpointConfigurationName, new EndpointAddress(this.EndpointAddress)); } client.ProcessLogMessagesCompleted += (sender, e) => { // report error to the callers foreach (var ev in asyncContinuations) { ev.Continuation(e.Error); } // send any buffered events this.SendBufferedEvents(); }; this.inCall = true; #if SILVERLIGHT if (!Deployment.Current.Dispatcher.CheckAccess()) { Deployment.Current.Dispatcher.BeginInvoke(() => client.ProcessLogMessagesAsync(events)); } else { client.ProcessLogMessagesAsync(events); } #else client.ProcessLogMessagesAsync(events); #endif #else var client = new SoapLogReceiverClient(this.EndpointAddress); this.inCall = true; client.BeginProcessLogMessages( events, result => { Exception exception = null; try { client.EndProcessLogMessages(result); } catch (Exception ex) { if (ex.MustBeRethrown()) { throw; } exception = ex; } // report error to the callers foreach (var ev in asyncContinuations) { ev.Continuation(exception); } // send any buffered events this.SendBufferedEvents(); }, null); #endif }
public static IAnimalService GetAnimalService(string connection) { ChannelFactory <IAnimalService> channelFactory = null; try { if (connection.StartsWith("net.tcp")) { // TODO: some security credential can be added // Create a binding of the type exposed by service NetTcpBinding tcpBinding = new NetTcpBinding(); tcpBinding.Security.Mode = SecurityMode.None; // No credential is needed to connect to the host service. tcpBinding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None; // EndPoint tcp address selfhosted EndpointAddress endpointAddressTcp = new EndpointAddress(connection); // Pass Binding and EndPoint address to ChannelFactory using tcpBinding channelFactory = new ChannelFactory <IAnimalService>(tcpBinding, endpointAddressTcp); // Now create the new channel as below IAnimalService channel = channelFactory.CreateChannel(); return(channel); } else if (connection.StartsWith("https")) { // HTTPS // Create a binding of the type exposed by service BasicHttpsBinding httpsBinding = new BasicHttpsBinding(); httpsBinding.Security.Mode = BasicHttpsSecurityMode.Transport; // No credential is needed to connect to the host service. httpsBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None; // EndPoint address EndpointAddress endpointAddress = new EndpointAddress(connection); // Pass Binding and EndPoint address to ChannelFactory using httpBinding channelFactory = new ChannelFactory <IAnimalService>(httpsBinding, endpointAddress); // Now create the new channel as below IAnimalService channel = channelFactory.CreateChannel(); return(channel); } else if (connection.StartsWith("http")) { // HTTP // Create a binding of the type exposed by service BasicHttpBinding httpBinding = new BasicHttpBinding(); httpBinding.Security.Mode = BasicHttpSecurityMode.None; // No credential is needed to connect to the host service. httpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None; // EndPoint address EndpointAddress endpointAddress = new EndpointAddress(connection); // Pass Binding and EndPoint address to ChannelFactory using httpBinding channelFactory = new ChannelFactory <IAnimalService>(httpBinding, endpointAddress); // Now create the new channel as below IAnimalService channel = channelFactory.CreateChannel(); return(channel); } throw new Exception("No valid connection protocol was found"); } catch (TimeoutException) { // Timeout error if (channelFactory != null) { channelFactory.Abort(); } throw; } catch (FaultException) { if (channelFactory != null) { channelFactory.Abort(); } throw; } catch (CommunicationException) { // Communication error if (channelFactory != null) { channelFactory.Abort(); } throw; } catch (Exception) { if (channelFactory != null) { channelFactory.Abort(); } throw; } }
public static Binding CreateBasicHttpBinding() { BasicHttpBinding binding = ContractBindingsHelper.CreateBasicHttpBinding(); return(binding); }
public void WithNoSecurity_returns_binding(BasicHttpBinding binding) { var result = BindingExtensions.WithNoSecurity(binding); Assert.That(result, Is.SameAs(binding)); }
public void WithNoSecurity_sets_security_mode_to_None(BasicHttpBinding binding) { BindingExtensions.WithNoSecurity(binding); Assert.That(binding.Security.Mode, Is.EqualTo(BasicHttpSecurityMode.None)); }
private void IBackgroundWorkerB_DoWork(object sender, DoWorkEventArgs e) { BasicHttpBinding LBasicHttpBinding = null; EndpointAddress LEndpointAddress = null; Service00003Client LService00003Client = null; List <string> LListWcfArgs = new List <string>(); try { List <string> LListStrDBProfile = App.GSystemMainWindow.GetCurrentDatabaseProfile(); List <string> LListStrAppServer = App.GSystemMainWindow.GetCurrentAppServerConnection(); //foreach (string LStrSingleProfile in LListStrDBProfile) { LListWcfArgs.Add(LStrSingleProfile); } LBasicHttpBinding = App.CreateBasicHttpBinding(true, 15); LEndpointAddress = App.CreateEndpointAddress(LListStrAppServer[0], LListStrAppServer[1], true, "Service00003"); LService00003Client = new Service00003Client(LBasicHttpBinding, LEndpointAddress); foreach (ListViewItemSingle LListViewItemSingleLanguage in IListObservableCollectionLanguagePackage) { if (LListViewItemSingleLanguage.DataChangeStatus == ListViewItemDataChangeStatus.IsDefault && LListViewItemSingleLanguage.TipChangeStatus == ListViewItemTipChangeStatus.IsDefault) { continue; } LListWcfArgs.Clear(); foreach (string LStrSingleProfile in LListStrDBProfile) { LListWcfArgs.Add(LStrSingleProfile); } LListWcfArgs.Add(LListViewItemSingleLanguage.LanguageCode.ToString()); LListWcfArgs.Add(LListViewItemSingleLanguage.MessageID); if (LListViewItemSingleLanguage.DataChangeStatus == ListViewItemDataChangeStatus.IsChanged) { LListWcfArgs.Add("C005" + App.GStrSpliterChar + LListViewItemSingleLanguage.MessageContentText01); LListWcfArgs.Add("C006" + App.GStrSpliterChar + LListViewItemSingleLanguage.MessageContentText02); } if (LListViewItemSingleLanguage.TipChangeStatus == ListViewItemTipChangeStatus.IsChanged) { LListWcfArgs.Add("C007" + App.GStrSpliterChar + LListViewItemSingleLanguage.MessageTipDisplay01); LListWcfArgs.Add("C008" + App.GStrSpliterChar + LListViewItemSingleLanguage.MessageTipDisplay02); } I00003OperationReturn = LService00003Client.OperationMethodA(6, LListWcfArgs); if (I00003OperationReturn.BoolReturn) { LListViewItemSingleLanguage.DataChangeStatus = ListViewItemDataChangeStatus.IsDefault; LListViewItemSingleLanguage.TipChangeStatus = ListViewItemTipChangeStatus.IsDefault; LListViewItemSingleLanguage.MessageContentTextOld = LListViewItemSingleLanguage.MessageContentText01 + LListViewItemSingleLanguage.MessageContentText02; LListViewItemSingleLanguage.MessageTipDisplayOld = LListViewItemSingleLanguage.MessageTipDisplay01 + LListViewItemSingleLanguage.MessageTipDisplay02; OperationEventArgs LEventArgs = new OperationEventArgs(); LEventArgs.StrElementTag = "CSLANG"; LEventArgs.ObjSource = LListViewItemSingleLanguage; IOperationEvent(this, LEventArgs); } else { IBoolHasSaveError = true; } } } catch (Exception ex) { I00003OperationReturn.BoolReturn = false; I00003OperationReturn.StringReturn = "UMP001E007" + App.GStrSpliterChar + ex.Message; } finally { if (LService00003Client != null) { if (LService00003Client.State == CommunicationState.Opened) { LService00003Client.Close(); LService00003Client = null; } } } }
public WcfHttpChannelManager(string address, string bindingConfiguration) { var binding = new BasicHttpBinding(bindingConfiguration); _channelFactory = new ChannelFactory <TChannel>(binding, new EndpointAddress(address)); }
public MailScenarioProxy(BasicHttpBinding binding, EndpointAddress remoteAddress) : base(binding, remoteAddress) { }
/// <summary> /// Translates an array of strings from the from langauge code to the to language code. /// From langauge code can stay empty, in that case the source language is auto-detected, across all elements of the array together. /// </summary> /// <param name="texts">Array of strings to translate</param> /// <param name="from">From language code. May be empty</param> /// <param name="to">To language code. Must be a valid language</param> /// <param name="contentType">Whether this is plain text or HTML</param> /// <returns></returns> public static string[] TranslateArray(string[] texts, string from, string to, string contentType) { string fromCode = string.Empty; string toCode = string.Empty; if (from.ToLower() == "Auto-Detect".ToLower() || from == string.Empty) { fromCode = string.Empty; } else { try { fromCode = AvailableLanguages.First(t => t.Value == from).Key; } catch { fromCode = from; } } toCode = LanguageNameToLanguageCode(to); Utils.ClientID = _ClientID; Utils.ClientSecret = _ClientSecret; string headerValue = "Bearer " + Utils.GetAccesToken(); var bind = new BasicHttpBinding { Name = "BasicHttpBinding_LanguageService", OpenTimeout = TimeSpan.FromMinutes(5), CloseTimeout = TimeSpan.FromMinutes(5), ReceiveTimeout = TimeSpan.FromMinutes(5), MaxReceivedMessageSize = int.MaxValue, MaxBufferPoolSize = int.MaxValue, MaxBufferSize = int.MaxValue, Security = new BasicHttpSecurity { Mode = BasicHttpSecurityMode.Transport } }; var epa = new EndpointAddress("https://api.microsofttranslator.com/V2/soap.svc"); LanguageServiceClient client = new LanguageServiceClient(bind, epa); if (String.IsNullOrEmpty(toCode)) { toCode = "en"; } TranslateOptions options = new TranslateOptions(); options.Category = _CategoryID; options.ContentType = contentType; try { var translatedTexts = client.TranslateArray( headerValue, texts, fromCode, toCode, options); string[] res = translatedTexts.Select(t => t.TranslatedText).ToArray(); if (_CreateTMXOnTranslate) { WriteToTmx(texts, res, from, to); } return(res); } catch //try again forcing English as source language { var translatedTexts = client.TranslateArray( headerValue, texts, "en", toCode, options); string[] res = translatedTexts.Select(t => t.TranslatedText).ToArray(); if (_CreateTMXOnTranslate) { WriteToTmx(texts, res, from, to); } return(res); } }
/// <summary> /// Creates a new <see cref="ServiceHost"/> from the URI. /// </summary> /// <param name="serviceType">Specifies the type of WCF service to host.</param> /// <param name="baseAddresses">An array of base addresses for the service.</param> /// <returns>New <see cref="ServiceHost"/>.</returns> protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses) { #if MONO throw new NotSupportedException("Not supported under Mono."); #else // Check security requirement. bool integratedSecurity = (Service.GetAuthenticationSchemes(baseAddresses[0]) & AuthenticationSchemes.Anonymous) != AuthenticationSchemes.Anonymous; // Create service host. ServiceHost host = base.CreateServiceHost(serviceType, baseAddresses); // Enable meta-data publishing. if (m_publishMetadata) { ServiceMetadataBehavior metadataBehavior = host.Description.Behaviors.Find <ServiceMetadataBehavior>(); if (metadataBehavior == null) { metadataBehavior = new ServiceMetadataBehavior(); host.Description.Behaviors.Add(metadataBehavior); } metadataBehavior.HttpGetEnabled = true; } // Enable security on the service. if (!m_disableSecurity) { ServiceAuthorizationBehavior authorizationBehavior = host.Description.Behaviors.Find <ServiceAuthorizationBehavior>(); if (authorizationBehavior == null) { authorizationBehavior = new ServiceAuthorizationBehavior(); host.Description.Behaviors.Add(authorizationBehavior); } authorizationBehavior.PrincipalPermissionMode = PrincipalPermissionMode.Custom; List <IAuthorizationPolicy> policies = new List <IAuthorizationPolicy>(); policies.Add((IAuthorizationPolicy)Activator.CreateInstance(m_authorizationPolicy)); authorizationBehavior.ExternalAuthorizationPolicies = policies.AsReadOnly(); } // Create endpoint and configure security. (Not supported on Mono) host.AddDefaultEndpoints(); if (string.IsNullOrEmpty(m_protocol)) { // Use the default endpoint. foreach (ServiceEndpoint endpoint in host.Description.Endpoints) { BasicHttpBinding basicBinding = endpoint.Binding as BasicHttpBinding; if (basicBinding != null) { // Default endpoint uses BasicHttpBinding. if (integratedSecurity) { // Enable security. basicBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly; basicBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows; } else { // Disable security. basicBinding.Security.Mode = BasicHttpSecurityMode.None; basicBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None; } } } } else { // Create endpoint using the specifics. host.Description.Endpoints.Clear(); Binding serviceBinding; ServiceEndpoint serviceEndpoint; serviceBinding = Service.CreateServiceBinding(ref m_protocol, integratedSecurity); if (serviceBinding != null) { // Binding created for the endpoint. Type contract = Service.GetServiceContract(serviceType); if (!string.IsNullOrEmpty(m_address)) { serviceEndpoint = host.AddServiceEndpoint(contract, serviceBinding, m_address); } else { serviceEndpoint = host.AddServiceEndpoint(contract, serviceBinding, string.Empty); } // Special handling for REST endpoint. if (serviceBinding is WebHttpBinding) { WebHttpBehavior restBehavior = new WebHttpBehavior(); //#if !MONO if (m_publishMetadata) { restBehavior.HelpEnabled = true; } //#endif serviceEndpoint.Behaviors.Add(restBehavior); serviceEndpoint.Behaviors.Add(new FormatSpecificationBehavior()); } } } return(host); #endif }
private static void RunVariation(string serviceAddress, bool isMultiNs = false) { BasicHttpBinding binding = null; EndpointAddress endpointAddress = null; ChannelFactory <ICalculator> factory1 = null; ChannelFactory <IHelloWorld> factory2 = null; ICalculator serviceProxy1 = null; IHelloWorld serviceProxy2 = null; // *** SETUP *** \\ binding = new BasicHttpBinding(); endpointAddress = new EndpointAddress(serviceAddress); factory1 = new ChannelFactory <ICalculator>(binding, endpointAddress); serviceProxy1 = factory1.CreateChannel(); if (isMultiNs) { factory2 = new ChannelFactory <IHelloWorld>(binding, endpointAddress); serviceProxy2 = factory2.CreateChannel(); } // *** EXECUTE Variation *** \\ try { var dateTime = DateTime.Now; string testStr = "test string"; var intParams = new IntParams() { P1 = 5, P2 = 10 }; var floatParams = new FloatParams() { P1 = 5.0f, P2 = 10.0f }; var byteParams = new ByteParams() { P1 = 5, P2 = 10 }; Assert.Equal(3, serviceProxy1.Sum2(1, 2)); Assert.Equal(intParams.P1 + intParams.P2, serviceProxy1.Sum(intParams)); Assert.Equal(string.Format("{0}{1}", intParams.P1, intParams.P2), serviceProxy1.Concatenate(intParams)); Assert.Equal((float)(floatParams.P1 / floatParams.P2), serviceProxy1.Divide(floatParams)); Assert.Equal((new byte[] { byteParams.P1, byteParams.P2 }), serviceProxy1.CreateSet(byteParams)); Assert.Equal(dateTime, serviceProxy1.ReturnInputDateTime(dateTime)); serviceProxy1.SetIntParamsProperty(null); Assert.Null(serviceProxy1.GetIntParamsProperty()); serviceProxy1.SetIntParamsProperty(intParams); IntParams intParamsProp = serviceProxy1.GetIntParamsProperty(); Assert.NotNull(intParamsProp); Assert.Equal(intParams.P1, intParamsProp.P1); Assert.Equal(intParams.P2, intParamsProp.P2); if (isMultiNs) { serviceProxy2.SetStringField(null); Assert.Null(serviceProxy2.GetStringField()); serviceProxy2.SetStringField(testStr); Assert.Equal(testStr, serviceProxy2.GetStringField()); } } catch (Exception ex) { Assert.True(false, ex.Message); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy1); if (isMultiNs) { ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy2); } } }
public ActionResult Create(Voter voter) { try { if (!string.IsNullOrEmpty(voter.IdentityNo) && !string.IsNullOrEmpty(voter.Name) && !string.IsNullOrEmpty(voter.Surname) && !string.IsNullOrEmpty(voter.BirthPlace) && voter.BirthDate != null && !string.IsNullOrEmpty(voter.City) && !string.IsNullOrEmpty(voter.District) ) { if (voter.Handicapped == null) { voter.Handicapped = false; } voter.CreatedAt = DateTime.Now; voter.CreatedBy = User.Identity.Name; voter.CreatedFrom = 1; voter.VoterStatus = true; // //TODO //voter.CreatedBy //voter.CreatedFrom m_internetDc.Voters.InsertOnSubmit(voter); m_internetDc.SubmitChanges(); ViewData["Message"] = " Seçmen başarı ile kaydedildi!"; return(View()); } else { if (m_internetDc.Voters.Any(x => x.IdentityNo == voter.IdentityNo)) { TempData["Message"] = " Bu Aday Zaten Sistemde Kayıtlıdır, Güncellemek için Aşağıdaki Ekranı Kullanın!"; return(RedirectToAction("Edit", "Voter", new { voter.IdentityNo })); } else { var myBinding = new BasicHttpBinding(); var myEndpoint = new EndpointAddress("http://192.168.1.222:9999/TCNufusMudurlugu/GetData"); var myChannelFactory = new ChannelFactory <IService1>(myBinding, myEndpoint); NufusMudurluguService.IService1 client = null; try { client = myChannelFactory.CreateChannel(); EOS.Officier.NufusMudurluguService.Citizen citizen = client.GetData(voter.IdentityNo); ((ICommunicationObject)client).Close(); ViewData["Regions"] = m_merkezDC.Regions.ToList(); var model = new Models.Voter(); var district = m_merkezDC.Districts.First(x => x.DistrictName.Contains(citizen.District)); if (district != null) { if (m_merkezDC.RegionDetails.Any(x => x.DistrictId == district.DistrictId)) { var region = m_merkezDC.RegionDetails.First(x => x.DistrictId == district.DistrictId); model.RegionId = region.RegionId; } } model.IdentityNo = citizen.IdentityNo; model.Name = citizen.Name; model.Surname = citizen.Surname; model.MotherName = citizen.MotherName; model.FatherName = citizen.FatherName; model.Telephone = citizen.Telephone; model.BirthDate = citizen.BirthDate; model.BirthPlace = citizen.BirthPlace; model.Address = citizen.Address; model.City = citizen.City; model.District = citizen.District; model.Handicapped = false; voter.VoterStatus = true; return(View(model)); } catch { if (client != null) { ((ICommunicationObject)client).Abort(); } ViewData["Message"] = "Geçersiz kimlik numarası girildi!"; return(View()); } } } } catch (Exception ex) { ViewData["Message"] = " Bir Hata Oluştu Lütfen Tekrar Deneyiniz!"; return(View()); } }
private static void Main(string[] args) { Console.WriteLine("Project Dropshot [Version 1.0.015]"); Console.WriteLine("(c) 2017 FESTIVAL Development. All rights reserved.\n"); if (!Directory.Exists(Path.Combine(Environment.CurrentDirectory, @"Data"))) { Directory.CreateDirectory(Path.Combine(Environment.CurrentDirectory, @"Data")); } var binding = new BasicHttpBinding(); binding.Security.Mode = BasicHttpSecurityMode.Transport; ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, errors) => true; #region ApplicationWebService applicationWebService = new ApplicationWebService(); var applicationWebServiceEndpoint = new EndpointAddress(string.Format("{0}/ApplicationWebService", ServiceBaseUrl)); var applicationWebServiceHost = new ServiceHost(applicationWebService); applicationWebServiceHost.AddServiceEndpoint(typeof(IApplicationWebServiceContract), binding, applicationWebServiceEndpoint.Uri); applicationWebServiceHost.Open(); Console.WriteLine("OK"); #endregion #region AuthenticationWebService authenticationWebService = new AuthenticationWebService(); var authenticationWebServiceEndpoint = new EndpointAddress(string.Format("{0}/AuthenticationWebService", ServiceBaseUrl)); var authenticationWebServiceHost = new ServiceHost(authenticationWebService); authenticationWebServiceHost.AddServiceEndpoint(typeof(IAuthenticationWebServiceContract), binding, authenticationWebServiceEndpoint.Uri); authenticationWebServiceHost.Open(); Console.WriteLine("OK"); #endregion #region RelationshipWebService relationshipWebService = new RelationshipWebService(); var relationshipWebServiceEndpoint = new EndpointAddress(string.Format("{0}/RelationshipWebService", ServiceBaseUrl)); var relationshipWebServiceHost = new ServiceHost(relationshipWebService); relationshipWebServiceHost.AddServiceEndpoint(typeof(IRelationshipWebServiceContract), binding, relationshipWebServiceEndpoint.Uri); relationshipWebServiceHost.Open(); Console.WriteLine("OK"); #endregion #region ShopWebService shopWebService = new ShopWebService(); var shopWebServiceEndpoint = new EndpointAddress(string.Format("{0}/ShopWebService", ServiceBaseUrl)); var shopWebServiceHost = new ServiceHost(shopWebService); shopWebServiceHost.AddServiceEndpoint(typeof(IShopWebServiceContract), binding, shopWebServiceEndpoint.Uri); shopWebServiceHost.Open(); Console.WriteLine("OK"); #endregion #region UserWebService userWebService = new UserWebService(); var userWebServiceEndpoint = new EndpointAddress(string.Format("{0}/UserWebService", ServiceBaseUrl)); var userWebServiceHost = new ServiceHost(userWebService); userWebServiceHost.AddServiceEndpoint(typeof(IUserWebServiceContract), binding, userWebServiceEndpoint.Uri); userWebServiceHost.Open(); Console.WriteLine("OK"); #endregion #region ClanWebService clanWebService = new ClanWebService(); var clanWebServiceEndpoint = new EndpointAddress(string.Format("{0}/ClanWebService", ServiceBaseUrl)); var clanWebServiceHost = new ServiceHost(clanWebService); clanWebServiceHost.AddServiceEndpoint(typeof(IClanWebServiceContract), binding, clanWebServiceEndpoint.Uri); clanWebServiceHost.Open(); Console.WriteLine("OK"); #endregion #region PrivateMessageWebService privateMessageWebService = new PrivateMessageWebService(); var privateMessageWebServiceEndpoint = new EndpointAddress(string.Format("{0}/PrivateMessageWebService", ServiceBaseUrl)); var privateMessageWebServiceHost = new ServiceHost(privateMessageWebService); privateMessageWebServiceHost.AddServiceEndpoint(typeof(IPrivateMessageWebServiceContract), binding, privateMessageWebServiceEndpoint.Uri); privateMessageWebServiceHost.Open(); Console.WriteLine("OK"); #endregion Console.WriteLine("All services running. Press Return to close."); Console.ReadLine(); }
public async Task <Air_FlightInfoResponse> Air_FlightInfo(SessionHandler.TransactionStatusCode transactionStatusCode, TransactionFlowLinkHandler.TransactionFlowLinkAction linkAction) { BeforeRequest(transactionStatusCode, linkAction); var session = hSession.Session; var link = hLink.Link; var basicHttpBinding = new BasicHttpBinding { MaxReceivedMessageSize = int.MaxValue, Name = "AmadeusWebServicesPortBinding", ReaderQuotas = System.Xml.XmlDictionaryReaderQuotas.Max, Security = { Mode = BasicHttpSecurityMode.Transport } }; var nonceText = Guid.NewGuid().ToString(); var created = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fff") + "Z"; var nonceBytes = Encoding.ASCII.GetBytes(nonceText); var nonceTextEncoded = Convert.ToBase64String(nonceBytes); var shaPwd1 = new System.Security.Cryptography.SHA1Managed(); var pwd = shaPwd1.ComputeHash(Encoding.ASCII.GetBytes("password")); var createdBytes = System.Text.Encoding.ASCII.GetBytes(created); var operand = new byte[nonceBytes.Length + createdBytes.Length + pwd.Length]; Array.Copy(nonceBytes, operand, nonceBytes.Length); Array.Copy(createdBytes, 0, operand, nonceBytes.Length, createdBytes.Length); Array.Copy(pwd, 0, operand, nonceBytes.Length + createdBytes.Length, pwd.Length); var sha1 = new System.Security.Cryptography.SHA1Managed(); var trueDigest = Convert.ToBase64String(sha1.ComputeHash(operand)); var soapSecurityHeader = new SoapSecurityHeader("userName", trueDigest, nonceTextEncoded, created); var factory = ChannelFactory(basicHttpBinding); var serviceProxy = AmadeusWebServicesPtChannel(factory, soapSecurityHeader); #region air flight info method call var result2 = await serviceProxy.Air_FlightInfoAsync(new Air_FlightInfoRequest { Air_FlightInfo = new Air_FlightInfo { generalFlightInfo = new Air_FlightInfoGeneralFlightInfo { boardPointDetails = new Air_FlightInfoGeneralFlightInfoBoardPointDetails { trueLocationId = "TPE" }, offPointDetails = new Air_FlightInfoGeneralFlightInfoOffPointDetails { trueLocationId = "LGW" }, companyDetails = new Air_FlightInfoGeneralFlightInfoCompanyDetails { marketingCompany = "CI" }, flightDate = new Air_FlightInfoGeneralFlightInfoFlightDate { departureDate = "021020" }, flightIdentification = new Air_FlightInfoGeneralFlightInfoFlightIdentification { flightNumber = "69" } } }, AMA_SecurityHostedUser = hSecurity.getHostedUser() }); #endregion factory.Close(); ((ICommunicationObject)serviceProxy).Close(); return(null); }
/// ------------------------------------------------------------------------------------ /// <summary> /// Starts the provider. /// </summary> /// <param name="providerLocation">The provider location.</param> /// <param name="provider">The provider.</param> /// <param name="providerType">Type of the provider.</param> /// ------------------------------------------------------------------------------------ internal static void StartProvider(Uri providerLocation, object provider, Type providerType) { if (s_runningProviders.ContainsKey(providerType)) { return; } string sNamedPipe = providerLocation.ToString(); // REVIEW: we don't dispose ServiceHost. It might be better to add it to the // SingletonsContainer ServiceHost providerHost = null; try { providerHost = new ServiceHost(provider); // Named pipes are better for Windows...don't tie up a dedicated port and perform better. // However, Mono does not yet support them, so on Mono we use a different binding. // Note that any attempt to unify these will require parallel changes in Paratext // and some sort of coordinated release of the new versions. System.ServiceModel.Channels.Binding binding; if (Platform.IsWindows) { var pipeBinding = new NetNamedPipeBinding(); pipeBinding.Security.Mode = NetNamedPipeSecurityMode.None; pipeBinding.MaxBufferSize *= 4; pipeBinding.MaxReceivedMessageSize *= 4; pipeBinding.MaxBufferPoolSize *= 2; pipeBinding.ReaderQuotas.MaxBytesPerRead *= 4; pipeBinding.ReaderQuotas.MaxArrayLength *= 4; pipeBinding.ReaderQuotas.MaxDepth *= 4; pipeBinding.ReaderQuotas.MaxNameTableCharCount *= 4; pipeBinding.ReaderQuotas.MaxStringContentLength *= 4; binding = pipeBinding; } else { var httpBinding = new BasicHttpBinding(); httpBinding.MaxBufferSize *= 4; httpBinding.MaxReceivedMessageSize *= 4; httpBinding.MaxBufferPoolSize *= 2; httpBinding.ReaderQuotas.MaxBytesPerRead *= 4; httpBinding.ReaderQuotas.MaxArrayLength *= 4; httpBinding.ReaderQuotas.MaxDepth *= 4; httpBinding.ReaderQuotas.MaxNameTableCharCount *= 4; httpBinding.ReaderQuotas.MaxStringContentLength *= 4; binding = httpBinding; } providerHost.AddServiceEndpoint(providerType, binding, sNamedPipe); providerHost.Open(); } catch (Exception e) { Logger.WriteError(e); providerHost = null; if (ScriptureProvider.IsInstalled) { MessageBox.Show(PtCommunicationProb, PtCommunicationProbTitle, MessageBoxButtons.OK, MessageBoxIcon.Information); } return; } Logger.WriteEvent("Started provider " + providerLocation + " for type " + providerType + "."); s_runningProviders.Add(providerType, providerHost); }
public static Caloom5WStructure Get5W(Guid EventID) { BasicHttpBinding basicHttpBinding = new BasicHttpBinding(); EndpointAddress endpointAddress = new EndpointAddress("http://localhost:56071/CaloomMainService.svc"); ICaloomMainService service = new ChannelFactory< ICaloomMainService >(basicHttpBinding, endpointAddress).CreateChannel(); var serviceResponse = service.Get5W(EventID); return serviceResponse; }
private List <gsReporte_IndicadoresDeudaVencidaResult> ListarEstadoCuentaResumenCliente(string codAgenda, string codVendedor, DateTime fechaEmisionInicial, DateTime fechaEmisionFinal, DateTime fechaVencimientoInicial, DateTime fechaVencimientoFinal, int divisor, int verTodo, int verCartera) { IndicadoresWCFClient objIndicadoresWCF = new IndicadoresWCFClient(); try { BasicHttpBinding binding = (BasicHttpBinding)objIndicadoresWCF.Endpoint.Binding; binding.MaxReceivedMessageSize = Int32.MaxValue; objIndicadoresWCF.InnerChannel.OperationTimeout = new TimeSpan(0, 10, 0); List <gsReporte_IndicadoresDeudaVencidaResult> lstDocumentos = objIndicadoresWCF.Indicadores_DeudaVencida(((Usuario_LoginResult)Session["Usuario"]).idEmpresa, ((Usuario_LoginResult)Session["Usuario"]).codigoUsuario, codAgenda, codVendedor, fechaEmisionInicial, fechaEmisionFinal, fechaVencimientoInicial, fechaVencimientoFinal, 0, divisor, verTodo, verCartera).ToList(); //var newLstDocumentos01 = mapObjIndicadoreVencido(lstDocumentos); //var nroClientesDeuda = // newLstDocumentos01.GroupBy(x => x.ZonaCobranza) // .Select(g => new gsReporte_IndicadoresDeudaVencidaResult // { // ZonaCobranza = g.Key // , // Vencido30a180 = (g.Sum(x => x.numeroVenc30180)) // , // sumaDeuda = g.Sum(x => x.numeroDeudaTotal) // , // DeudaVencida = g.Sum(x => x.numeroDeudaVenc) // }).ToList(); List <gsReporte_IndicadoresDeudaVencidaResult> lstDoc; if (chkClientes.Checked) { lstDoc = lstDocumentos; } else { lstDoc = lstDocumentos.Where(x => x.numeroVenc30180 > 0).ToList(); } //foreach (var item in nroClientesDeuda) //{ // foreach (var itemDoc in lstDoc) // { // //var numeroVenc30180 = nroClientesDeuda.Where(x =>x.ZonaCobranza = itemDoc.ZonaCobranza && x.ClienteNombre = ) // if (itemDoc.ZonaCobranza != item.ZonaCobranza) continue; // itemDoc.numeroDeudaTotal = Convert.ToInt32(item.sumaDeuda); // itemDoc.numeroDeudaVenc = Convert.ToInt32(item.DeudaVencida); // itemDoc.indDeudaVencida = Convert.ToDecimal(GetIndicador(itemDoc)); // //itemDoc.numeroVenc30180 = Convert.ToInt32(item.Vencido30a180); // } //} ViewState["lstIndicadores"] = JsonHelper.JsonSerializer(lstDoc); //.Where(x => x.Vencido30a180 > 0).ToList() grdIndicadores.DataSource = lstDoc; //.Where(x => x.Vencido30a180 > 0) grdIndicadores.DataBind(); lblMensajeResumenCliente.Text = "Se han encontrado " + lstDoc.Count.ToString() + " registro."; lblMensajeResumenCliente.CssClass = "mensajeExito"; lblDate2.Text = "2"; return(lstDocumentos); } catch (Exception ex) { throw ex; } }
public static void Abort_During_Implicit_Open_Closes_Async_Waiters() { // This test is a regression test of an issue with CallOnceManager. // When a single proxy is used to make several service calls without // explicitly opening it, the CallOnceManager queues up all the requests // that happen while it is opening the channel (or handling previously // queued service calls. If the channel was closed or faulted during // the handling of any queued requests, it caused a pathological worst // case where every queued request waited for its complete SendTimeout // before failing. // // This test operates by making multiple concurrent asynchronous service // calls, but stalls the Opening event to allow them to be queued before // any of them are allowed to proceed. It then closes the channel when // the first service operation is allowed to proceed. This causes the // CallOnce manager to deal with all its queued operations and cause // them to complete other than by timing out. BasicHttpBinding binding = null; ChannelFactory <IWcfService> factory = null; IWcfService serviceProxy = null; int timeoutMs = 20000; long operationsQueued = 0; int operationCount = 5; Task <string>[] tasks = new Task <string> [operationCount]; Exception[] exceptions = new Exception[operationCount]; string[] results = new string[operationCount]; bool isClosed = false; DateTime endOfOpeningStall = DateTime.Now; int serverDelayMs = 100; TimeSpan serverDelayTimeSpan = TimeSpan.FromMilliseconds(serverDelayMs); string testMessage = "testMessage"; try { // *** SETUP *** \\ binding = new BasicHttpBinding(BasicHttpSecurityMode.None); binding.TransferMode = TransferMode.Streamed; // SendTimeout is the timeout used for implicit opens binding.SendTimeout = TimeSpan.FromMilliseconds(timeoutMs); factory = new ChannelFactory <IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic)); serviceProxy = factory.CreateChannel(); // Force the implicit open to stall until we have multiple concurrent calls pending. // This forces the CallOnceManager to have a queue of waiters it will need to notify. ((ICommunicationObject)serviceProxy).Opening += (s, e) => { // Wait until we see sync calls have been queued DateTime startOfOpeningStall = DateTime.Now; while (true) { endOfOpeningStall = DateTime.Now; // Don't wait forever -- if we stall longer than the SendTimeout, it means something // is wrong other than what we are testing, so just fail early. if ((endOfOpeningStall - startOfOpeningStall).TotalMilliseconds > timeoutMs) { Assert.True(false, "The Opening event timed out waiting for operations to queue, which was not expected for this test."); } // As soon as we have all our Tasks at least running, wait a little // longer to allow them finish queuing up their waiters, then stop stalling the Opening if (Interlocked.Read(ref operationsQueued) >= operationCount) { Task.Delay(500).Wait(); endOfOpeningStall = DateTime.Now; return; } Task.Delay(100).Wait(); } }; // Each task will make a synchronous service call, which will cause all but the // first to be queued for the implicit open. The first call to complete then closes // the channel so that it is forced to deal with queued waiters. Func <string> callFunc = () => { // We increment the # ops queued before making the actual sync call, which is // technically a short race condition in the test. But reversing the order would // timeout the implicit open and fault the channel. Interlocked.Increment(ref operationsQueued); // The call of the operation is what creates the entry in the CallOnceManager queue. // So as each Task below starts, it increments the count and adds a waiter to the // queue. We ask for a small delay on the server side just to introduce a small // stall after the sync request has been made before it can complete. Otherwise // fast machines can finish all the requests before the first one finishes the Close(). Task <string> t = serviceProxy.EchoWithTimeoutAsync(testMessage, serverDelayTimeSpan); lock (tasks) { if (!isClosed) { try { isClosed = true; ((ICommunicationObject)serviceProxy).Abort(); } catch { } } } return(t.GetAwaiter().GetResult()); }; // *** EXECUTE *** \\ DateTime startTime = DateTime.Now; for (int i = 0; i < operationCount; ++i) { tasks[i] = Task.Run(callFunc); } for (int i = 0; i < operationCount; ++i) { try { results[i] = tasks[i].GetAwaiter().GetResult(); } catch (Exception ex) { exceptions[i] = ex; } } // *** VALIDATE *** \\ double elapsedMs = (DateTime.Now - endOfOpeningStall).TotalMilliseconds; // Before validating that the issue was fixed, first validate that we received the exceptions or the // results we expected. This is to verify the fix did not introduce a behavioral change other than the // elimination of the long unnecessary timeouts after the channel was closed. int nFailures = 0; for (int i = 0; i < operationCount; ++i) { if (exceptions[i] == null) { Assert.True((String.Equals("test", results[i])), String.Format("Expected operation #{0} to return '{1}' but actual was '{2}'", i, testMessage, results[i])); } else { ++nFailures; TimeoutException toe = exceptions[i] as TimeoutException; Assert.True(toe == null, String.Format("Task [{0}] should not have failed with TimeoutException", i)); } } Assert.True(nFailures > 0, String.Format("Expected at least one operation to throw an exception, but none did. Elapsed time = {0} ms.", elapsedMs)); // --- Here is the test of the actual bug fix --- // The original issue was that sync waiters in the CallOnceManager were not notified when // the channel became unusable and therefore continued to time out for the full amount. // Additionally, because they were executed sequentially, it was also possible for each one // to time out for the full amount. Given that we closed the channel, we expect all the queued // waiters to have been immediately waked up and detected failure. int expectedElapsedMs = (operationCount * serverDelayMs) + timeoutMs / 2; Assert.True(elapsedMs < expectedElapsedMs, String.Format("The {0} operations took {1} ms to complete which exceeds the expected {2} ms", operationCount, elapsedMs, expectedElapsedMs)); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }
void RunClient() { var binding = new BasicHttpBinding(); var remoteAddress = new EndpointAddress("http://localhost:" + NetworkHelpers.FindFreePort() + "/Service1"); var normalClient = new Service1Client(binding, remoteAddress); var collectionClient = new Service1Client(binding, remoteAddress); var nestedClient = new Service1Client(binding, remoteAddress); var dbClient = new Service1Client(binding, remoteAddress); { ManualResetEvent wait = new ManualResetEvent(false); Exception error = null; object result = null; normalClient.GetDataCompleted += delegate(object o, GetDataCompletedEventArgs e) { try { error = e.Error; result = e.Error == null ? e.Result : null; } finally { wait.Set(); } }; normalClient.GetDataAsync(); Assert.IsTrue(wait.WaitOne(TimeSpan.FromSeconds(20)), "#1 timeout"); Assert.IsNull(error, "#1.1, inner exception: {0}", error); Assert.AreEqual("A", ((DataType1)result).Id, "#1.2"); } { ManualResetEvent wait = new ManualResetEvent(false); Exception error = null; ObservableCollection <object> result = null; collectionClient.GetCollectionDataCompleted += delegate(object sender, GetCollectionDataCompletedEventArgs e) { try { error = e.Error; result = e.Error == null ? e.Result : null; } finally { wait.Set(); } }; collectionClient.GetCollectionDataAsync(); Assert.IsTrue(wait.WaitOne(TimeSpan.FromSeconds(20)), "#2 timeout"); Assert.IsNull(error, "#2.1, inner exception: {0}", error); Assert.AreEqual("B,C", ItemsToString(result.Cast <DataType1> ()), "#2.2"); } { ManualResetEvent wait = new ManualResetEvent(false); Exception error = null; WebServiceMoonlightTest.ServiceReference2.DataType2 result = null; nestedClient.GetNestedDataCompleted += delegate(object sender, GetNestedDataCompletedEventArgs e) { try { error = e.Error; result = e.Error == null ? e.Result : null; } finally { wait.Set(); } }; nestedClient.GetNestedDataAsync(); Assert.IsTrue(wait.WaitOne(TimeSpan.FromSeconds(20)), "#3 timeout"); Assert.IsNull(error, "#3.1, inner exception: {0}", error); Assert.AreEqual("D,E", ItemsToString(result.Items.Cast <DataType1> ()), "#3.2"); } { ManualResetEvent wait = new ManualResetEvent(false); Exception error = null; string result = null; dbClient.JSMGetDatabasesCompleted += delegate(object sender, JSMGetDatabasesCompletedEventArgs e) { try { error = e.Error; result = e.Error == null ? e.Result : null; } finally { wait.Set(); } }; dbClient.JSMGetDatabasesAsync(); Assert.IsTrue(wait.WaitOne(TimeSpan.FromSeconds(20)), "#4 timeout"); Assert.IsNull(error, "#4.1, inner exception: {0}", error); Assert.AreEqual("databases", result, "#4.2"); } }
public async Task Main(string[] args) { if (args.Length != 3) { var done = await Task.Run(() => { WriteLine($"{Environment.NewLine} Commands: [Reloc] Is64 Region TimeDateStamp"); WriteLine($"\te.g. running the default Reloc command [dnx run True ntdll 51DA4B7D]"); WriteLine($"\twill result in the 64bit 7zip compressed reloc data to be downloaded to NTDLL.DLL-78E50000-51DA4B7D.reloc.7z"); WriteLine($"\tBy using relocation data during a memory dump extraction, an exact match may be calculated from disk-code<->memory-code.{ Environment.NewLine}"); WriteLine($"\tuser provided {args.Length + 1} arguments (only specify 3), interpreted as;"); WriteLine($"\tIs64[{(args.Length >= 1 ? args[0] : String.Empty)}] Region[{(args.Length >= 2 ? args[1] : String.Empty)}] TimeDateStamp[{(args.Length >= 3 ? args[2] : String.Empty)}] ..."); return false; }); return; } var Is64 = false; var time = uint.MinValue; var Region = string.Empty; var dt = DateTime.MinValue; var KnownAsName = string.Empty; var OrigLoadAddress = ulong.MinValue; if (!bool.TryParse(args[0], out Is64)) { WriteLine($"Error parsing a booliean value (True or False) from [{args[0]}], unable to continue."); return; } Region = args[1]; if (string.IsNullOrWhiteSpace(Region) || Region.Contains(Path.GetInvalidFileNameChars().ToString())) { WriteLine($"Must provide a value for the DLL/EXE name to search for (region), provided value [{args[1]}], unable to continue."); return; } if (!uint.TryParse(args[2], NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out time) && !uint.TryParse(args[2], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out time) && !DateTime.TryParse(args[2], out dt) ) { WriteLine($"Error parsing a TimeDateStamp value (numeric (hex allowed) or in text form e.g. (8/18/2010 1:30:30 PM - 1/1/2010 8:00:15 AM = 229.05:30:15) from [{args[2]}], unable to continue."); return; } // if the argument was not a number or string value for date // maybe it's a filename to use as a reference? ;)?? if (dt == DateTime.MinValue && time == uint.MinValue) time = PETimeDateStamp(args[2]); // The FinalFileName is only known after the server responds with additional metadata var DestName = $"{Region}-?####?-{time:X}.reloc.7z"; WriteLine($"Contacting, dest file [{DestName}]: 64bit:{Is64}, Region(dll):{Region}, TimeDateStamp:{time:X}."); InterWeb = new Net("http://blockwatch.ioactive.com:8888/"); InterWeb.UserName = "******"; InterWeb.PassWord = "******"; // // Sending the "Online" packet dosent really matter since the cred's are sent always. // It's more of an application ping/test that you're good to go. // // Aside from the downloaded .reloc file. You will also get the preferred load address // which can sometimes be missing or altered by due to loader artifacts ? :( // var FinalFileName = await Task.Factory.StartNew(() => InterWeb.Online()) .ContinueWith((isOn) => { Task<byte[]> data = null; if (isOn.Result) data = Task.Factory.StartNew(() => InterWeb.NetRelocCheck(Region, time, Is64, ref OrigLoadAddress, ref KnownAsName)); return data; }).Unwrap().ContinueWith((bytez) => { var FinalName = $"{KnownAsName}-{OrigLoadAddress:X}-{time:X}.reloc.7z"; File.WriteAllBytes(FinalName, bytez.Result); return FinalName; }); if (OrigLoadAddress == ulong.MaxValue) Write("An error reported from server: "); if (File.Exists(FinalFileName)) WriteLine($"Downloaded to {FinalFileName}, size {new FileInfo(FinalFileName).Length}."); else WriteLine("No .reloc available, request an import of the reloc data you need, we will expand the table based on feedback."); return; #if FALSE var LC = new LoginCredsText() { username = InterWeb.UserName, password = InterWeb.PassWord }; WriteLine("test1..."); IChannelFactory<IRequestChannel> factory = new BasicHttpBinding().BuildChannelFactory<IRequestChannel>(new BindingParameterCollection()); factory.Open(); IRequestChannel channel = factory.CreateChannel(new EndpointAddress("http://blockwatch.ioactive.com:8888/Buffer/Text/wsHttp")); channel.Open(); Message requestmessage = Message.CreateMessage(MessageVersion.Soap11, "http://tempuri.org/IElmerBuffer/Online", LC, new DataContractSerializer(LC.GetType())); //send message Message replymessage = channel.Request(requestmessage); WriteLine("Reply message received"); WriteLine("Reply action: {0}", replymessage.Headers.Action); string data = replymessage.GetBody<string>(); WriteLine("Reply content: {0}", data); //Step5: don't forget to close the message requestmessage.Close(); replymessage.Close(); //don't forget to close the channel channel.Close(); //don't forget to close the factory factory.Close(); #endif }
private static bool IsBindingSupported(Binding binding) { s_bindingValidationErrors.Clear(); if (!(binding is BasicHttpBinding || binding is NetHttpBinding || binding is WSHttpBinding || binding is NetTcpBinding || binding is CustomBinding)) { s_bindingValidationErrors.Add(string.Format(SR.BindingTypeNotSupportedFormat, binding.GetType().FullName, typeof(BasicHttpBinding).FullName, typeof(NetHttpBinding).FullName, typeof(WSHttpBinding).FullName, typeof(NetTcpBinding).FullName, typeof(CustomBinding).FullName)); } else { WSHttpBinding wsHttpBinding = binding as WSHttpBinding; if (wsHttpBinding != null) { if (wsHttpBinding.TransactionFlow) { s_bindingValidationErrors.Add(SR.BindingTransactionFlowNotSupported); } if (wsHttpBinding.Security.Mode == SecurityMode.Message) { s_bindingValidationErrors.Add(string.Format(SRServiceModel.UnsupportedSecuritySetting, "Mode", wsHttpBinding.Security.Mode)); } } else { NetTcpBinding netTcpBinding = binding as NetTcpBinding; if (netTcpBinding != null) { if (netTcpBinding.TransactionFlow) { s_bindingValidationErrors.Add(SR.BindingTransactionFlowNotSupported); } if (netTcpBinding.Security.Mode == SecurityMode.Message) { s_bindingValidationErrors.Add(string.Format(SRServiceModel.UnsupportedSecuritySetting, "Mode", netTcpBinding.Security.Mode)); } } else { NetHttpBinding netHttpBinding = binding as NetHttpBinding; if (netHttpBinding != null) { if (netHttpBinding.Security.Mode == BasicHttpSecurityMode.Message) { s_bindingValidationErrors.Add(string.Format(SRServiceModel.UnsupportedSecuritySetting, "Mode", netHttpBinding.Security.Mode)); } } else { BasicHttpBinding basicHttpBinding = binding as BasicHttpBinding; if (basicHttpBinding != null && basicHttpBinding.Security.Mode == BasicHttpSecurityMode.Message) { s_bindingValidationErrors.Add(string.Format(SRServiceModel.UnsupportedSecuritySetting, "Mode", basicHttpBinding.Security.Mode)); } } } } ValidateBindingElements(binding); } return(s_bindingValidationErrors.Count == 0); }
/// <summary> /// This gets called by the Action actually starting the transaction. /// </summary> /// <param name="paymentId">The id corresponding to a <type>PaymentRecord</type> for the transaction we want to start.</param> /// <returns>The url of a page to which we redirect the client's browser to complete the payment.</returns> private string StartGestPayTransactionURL(int paymentId) { var settings = _orchardServices .WorkContext .CurrentSite .As <PaymentGestPaySettingsPart>(); var pRecord = GetPaymentInfo(paymentId); if (pRecord.PaymentTransactionComplete) { //this avoids repeat payments when the user is dumb and goes back in the browser to try and pay again return(GetPaymentInfoUrl(paymentId)); } var user = _orchardServices.WorkContext.CurrentUser; if (pRecord.UserId > 0 && pRecord.UserId != user.Id) { //not the same user who started the payment throw new Exception(); } var gpt = new GestPayTransaction(pRecord); //parameter validation if (gpt == null) { //Log the error Logger.Error(T("Transaction object cannot be null.").Text); //update the PaymentRecord for this transaction EndPayment(paymentId, false, null, T("Failed to create a transaction object based on the PaymentRecord").Text); //return the url of a suitable error page (call this.GetPaymentInfoUrl after inserting the error in the PaymentRecord) return(GetPaymentInfoUrl(paymentId)); } try { Validator.ValidateObject(gpt, new ValidationContext(gpt), true); } catch (Exception ex) { //Log the error Logger.Error(T("Transaction information not valid: {0}", ex.Message).Text); //update the PaymentRecord for this transaction EndPayment(paymentId, false, null, T("Transaction information not valid: {0}", ex.Message).Text); //return the URL of a suitable error page (call this.GetPaymentInfoUrl after inserting the error in the PaymentRecord) return(GetPaymentInfoUrl(paymentId)); } //get the encrypted parameter string EncryptDecryptTransactionResult res = null; string urlFormat = ""; XmlNode encryptXML = null; try { if (settings.UseTestEnvironment) { string endpoint = string.Format(Endpoints.TestWSEntry, Endpoints.CryptDecryptEndPoint); endpoint = endpoint.Substring(0, endpoint.Length - 4); //WSHttpBinding binding = new WSHttpBinding(); //binding.Security.Mode = SecurityMode.Transport; //binding.MessageEncoding = WSMessageEncoding.Text; BasicHttpBinding binding = new BasicHttpBinding(); endpoint = Regex.Replace(endpoint, "(https)", "http"); //https gives errors EndpointAddress address = new EndpointAddress(endpoint); using (var client = new CryptDecryptTest.WSCryptDecryptSoapClient(binding, address)) { encryptXML = client.Encrypt( shopLogin: settings.GestPayShopLogin, uicCode: gpt.uicCode, amount: gpt.amount, shopTransactionId: gpt.shopTransactionID, cardNumber: gpt.cardNumber, expiryMonth: gpt.expiryMonth, expiryYear: gpt.expiryYear, buyerName: gpt.buyerName, buyerEmail: gpt.buyerEmail, languageId: gpt.languageId, cvv: gpt.cvv, customInfo: gpt.customInfo, requestToken: gpt.requestToken, ppSellerProtection: gpt.ppSellerProtection, shippingDetails: gpt.shippingDetails.TestVersion(), paymentTypes: gpt.paymentTypes.ToArray(), paymentTypeDetail: gpt.paymentTypeDetail.TestVersion(), redFraudPrevention: gpt.redFraudPrevention, Red_CustomerInfo: gpt.Red_CustomerInfo.TestVersion(), Red_ShippingInfo: gpt.Red_ShippingInfo.TestVersion(), Red_BillingInfo: gpt.Red_BillingInfo.TestVersion(), Red_CustomerData: gpt.Red_CustomerData.TestVersion(), Red_CustomInfo: gpt.Red_CustomInfo.ToArray(), Red_Items: gpt.Red_Items.TestVersion(), Consel_MerchantPro: gpt.Consel_MerchantPro, Consel_CustomerInfo: gpt.Consel_CustomerInfo.TestVersion(), payPalBillingAgreementDescription: gpt.payPalBillingAgreementDescription, OrderDetails: gpt.OrderDetails.TestVersion() ); urlFormat = string.Format(Endpoints.TestPayEntry, Endpoints.PaymentPage); } } else { string endpoint = string.Format(Endpoints.ProdWSEntry, Endpoints.CryptDecryptEndPoint); endpoint = endpoint.Substring(0, endpoint.Length - 4); BasicHttpBinding binding = new BasicHttpBinding(); endpoint = Regex.Replace(endpoint, "(https)", "http"); //https gives errors EndpointAddress address = new EndpointAddress(endpoint); using (var client = new CryptDecryptProd.WSCryptDecryptSoapClient(binding, address)) { encryptXML = client.Encrypt( shopLogin: settings.GestPayShopLogin, uicCode: gpt.uicCode, amount: gpt.amount, shopTransactionId: gpt.shopTransactionID, cardNumber: gpt.cardNumber, expiryMonth: gpt.expiryMonth, expiryYear: gpt.expiryYear, buyerName: gpt.buyerName, buyerEmail: gpt.buyerEmail, languageId: gpt.languageId, cvv: gpt.cvv, customInfo: gpt.customInfo, requestToken: gpt.requestToken, ppSellerProtection: gpt.ppSellerProtection, shippingDetails: gpt.shippingDetails.ProdVersion(), paymentTypes: gpt.paymentTypes.ToArray(), paymentTypeDetail: gpt.paymentTypeDetail.ProdVersion(), redFraudPrevention: gpt.redFraudPrevention, Red_CustomerInfo: gpt.Red_CustomerInfo.ProdVersion(), Red_ShippingInfo: gpt.Red_ShippingInfo.ProdVersion(), Red_BillingInfo: gpt.Red_BillingInfo.ProdVersion(), Red_CustomerData: gpt.Red_CustomerData.ProdVersion(), Red_CustomInfo: gpt.Red_CustomInfo.ToArray(), Red_Items: gpt.Red_Items.ProdVersion(), Consel_MerchantPro: gpt.Consel_MerchantPro, Consel_CustomerInfo: gpt.Consel_CustomerInfo.ProdVersion(), payPalBillingAgreementDescription: gpt.payPalBillingAgreementDescription, OrderDetails: gpt.OrderDetails.ProdVersion() ); urlFormat = string.Format(Endpoints.ProdPayEntry, Endpoints.PaymentPage); } } } catch (Exception ex) { //Log the error LocalizedString error = T("Request to GestPay service failed: {0}", ex.Message); Logger.Error(error.Text); //update the PaymentRecord for this transaction EndPayment(paymentId, false, null, error.Text); //return the URL of a suitable error page (call this.GetPaymentInfoUrl after inserting the error in the PaymentRecord) return(GetPaymentInfoUrl(paymentId)); } try { res = new EncryptDecryptTransactionResult(encryptXML); Validator.ValidateObject(res, new ValidationContext(res), true); } catch (Exception ex) { //Log the error Logger.Error(T("Validation problems on the response received: {0}", ex.Message).Text); //update the PaymentRecord for this transaction EndPayment(paymentId, false, null, T("Validation problems on the response received: {0}", ex.Message).Text); //return the URL of a suitable error page (call this.GetPaymentInfoUrl after inserting the error in the PaymentRecord) return(GetPaymentInfoUrl(paymentId)); } if (res.TransactionResult.ToUpperInvariant() == "OK") { return(string.Format(urlFormat, settings.GestPayShopLogin, res.CryptDecryptString)); } else { //Log the error LocalizedString error = T("Remote service replied with an error. Error {0}: {1}", res.ErrorCode, res.ErrorDescription); Logger.Error(error.Text); //update the PaymentRecord for this transaction EndPayment(paymentId, false, null, error.Text); //return the URL of a suitable error page (call this.GetPaymentInfoUrl after inserting the error in the PaymentRecord) return(GetPaymentInfoUrl(paymentId)); } }
public void UseHttps_uses_delegate_to_configure_transport_node(BasicHttpBinding binding, Action <HttpTransportSecurity> testDelegate) { BindingExtensions.UseHttps(binding, testDelegate); Mock.Get(testDelegate).Verify(p => p(binding.Security.Transport)); }