private void Form1_Load(object sender, EventArgs e) { //Banking_Library.IService1 proxy = new Banking_Library.Service1(); EndpointAddress adddress = new EndpointAddress("http://localhost:8080/QuanLyDanhBa/QuanLyDanhBa"); WSHttpBinding binding = new WSHttpBinding(); ServiceLibrary.IQuanLyDanhBa proxy; proxy = ChannelFactory<ServiceLibrary.IQuanLyDanhBa>.CreateChannel(binding, adddress); // = new ServiceLibrary.ServiceQuanLyDanhBa(); //IServiceBank proxy = new ServiceBankClient(); textBox1.Text = proxy.GetAuthor(); //*/ //Dung ChannelFactory cho phep tao nhieu doi tuong proxy voi cac endpoint khac nhau //EndpointAddress address = new EndpointAddress("http://localhost:8000/BankService"); //BasicHttpBinding binding = new BasicHttpBinding(); //Banking_Library.IService1 proxy = ChannelFactory<Banking_Library.IService1>.CreateChannel(binding, address); //txtResult.Text = proxy.GetBalance("aaa").ToString(); //IBankService proxy = ChannelFactory<IBankService>.CreateChannel(binding, address); //decimal balance = proxy.GetBalance("ABC123"); //Dung ChannelFactory cho phep tao nhieu doi tuong proxy voi cac endpoint khac nhau //EndpointAddress address1 = new EndpointAddress("http://localhost:8000/BankService1"); //WSHttpBinding binding1 = new WSHttpBinding(); //IBankService proxy1 = ChannelFactory<IBankService>.CreateChannel(binding1, address1); //decimal balance1 = proxy1.GetBalance("ABC123"); //label1.Text = Convert.ToString(balance) + " and " + Convert.ToString(balance1); }
private void Form1_Load(object sender, EventArgs e) { var endPoint = new EndpointAddress( "http://localhost:4444/MathService"); channel = ChannelFactory<IMathService>.CreateChannel(new BasicHttpBinding(), endPoint); }
static void Main(string[] args) { var aosUriString = ClientConfiguration.Default.UriString; var oauthHeader = OAuthHelper.GetAuthenticationHeader(); var serviceUriString = SoapUtility.SoapHelper.GetSoapServiceUriString(UserSessionServiceName, aosUriString); var endpointAddress = new System.ServiceModel.EndpointAddress(serviceUriString); var binding = SoapUtility.SoapHelper.GetBinding(); var client = new UserSessionServiceClient(binding, endpointAddress); var channel = client.InnerChannel; UserSessionInfo sessionInfo = null; using (OperationContextScope operationContextScope = new OperationContextScope(channel)) { HttpRequestMessageProperty requestMessage = new HttpRequestMessageProperty(); requestMessage.Headers[OAuthHelper.OAuthHeader] = oauthHeader; OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessage; sessionInfo = ((UserSessionService)channel).GetUserSessionInfo(new GetUserSessionInfo()).result; } Console.WriteLine(); Console.WriteLine("User ID: {0}", sessionInfo.UserId); Console.WriteLine("Is Admin: {0}", sessionInfo.IsSysAdmin); Console.ReadLine(); }
public void Connect(string endPointAddress) { if (this._lucidServer != null) { Disconnect(); } EndpointAddress serverEndpointAddress; try { serverEndpointAddress = new EndpointAddress(endPointAddress); } catch { // bad url throw new Exception("Bad server URL: " + endPointAddress); } Binding binding = new NetTcpBinding(SecurityMode.None, true); binding.ReceiveTimeout = TimeSpan.FromSeconds(10); binding.SendTimeout = TimeSpan.FromSeconds(10); binding.OpenTimeout = TimeSpan.FromSeconds(10); var factory = new ChannelFactory<ILucidService>(binding, serverEndpointAddress); this._lucidServer = factory.CreateChannel(); // let server know we are available this._lucidServer.RegisterClient(); Inv.Log.Log.WriteMessage("Connected to server " + endPointAddress); }
public ViewResult Book(BookingModel model) { var request = new BookRequest { RoomNumber = model.RoomNumber, PersonName = model.PersonName, BeginAt = model.BeginAt, EndAt = model.EndAt }; var binding = new NetTcpBinding(); var endpointAddress = new EndpointAddress("net.tcp://*****:*****@ViewBag.Title = "Booking completed"; return View("Success", model); } @ViewBag.Title = "Booking failed"; @ViewBag.Message = result.Message; return View("Failed"); }
IFS2Contract DoCreate(string serverAddress) { if (serverAddress.StartsWith("net.pipe:")) { if (!FS2LoadHelper.Load()) BalloonHelper.ShowFromFiresec("Не удается соединиться с агентом 2"); } var binding = BindingHelper.CreateBindingFromAddress(serverAddress); var endpointAddress = new EndpointAddress(new Uri(serverAddress)); ChannelFactory = new ChannelFactory<IFS2Contract>(binding, endpointAddress); foreach (OperationDescription operationDescription in ChannelFactory.Endpoint.Contract.Operations) { DataContractSerializerOperationBehavior dataContractSerializerOperationBehavior = operationDescription.Behaviors.Find<DataContractSerializerOperationBehavior>() as DataContractSerializerOperationBehavior; if (dataContractSerializerOperationBehavior != null) dataContractSerializerOperationBehavior.MaxItemsInObjectGraph = Int32.MaxValue; } ChannelFactory.Open(); IFS2Contract firesecService = ChannelFactory.CreateChannel(); (firesecService as IContextChannel).OperationTimeout = TimeSpan.FromMinutes(10); return firesecService; }
// channel factory public UdpDuplexChannel (UdpChannelFactory factory, BindingContext ctx, EndpointAddress address, Uri via) : base (factory) { binding_element = factory.Source; RemoteAddress = address; Via = via; }
public CoreServiceProvider() { var binding = new BasicHttpBinding { MaxReceivedMessageSize = 10485760, ReaderQuotas = new XmlDictionaryReaderQuotas { MaxStringContentLength = 10485760, MaxArrayLength = 10485760 }, Security = new BasicHttpSecurity { Mode = BasicHttpSecurityMode.TransportCredentialOnly, Transport = new HttpTransportSecurity { ClientCredentialType = HttpClientCredentialType.Windows } } }; string coreServiceUrl = ConfigurationManager.AppSettings[Constants.TRIDION_CME_URL] + "/webservices/CoreService2013.svc/basicHttp"; Console.WriteLine("Connect to CoreService " + coreServiceUrl); EndpointAddress endpoint = new EndpointAddress(coreServiceUrl); factory = new ChannelFactory<ICoreService>(binding, endpoint); string userName = ConfigurationManager.AppSettings[Constants.USER_NAME]; string password = ConfigurationManager.AppSettings[Constants.PASSWORD]; factory.Credentials.Windows.ClientCredential = new NetworkCredential(userName, password); Client = factory.CreateChannel(); UserData user = Client.GetCurrentUser(); Console.WriteLine("Connected as {0} ({1})", user.Description, user.Title); }
static void Main(string[] args) { Console.Title = "CLIENT"; // Указание, где ожидать входящие сообщения. Uri address = new Uri("http://localhost:4000/IContract"); // Указание, как обмениваться сообщениями. BasicHttpBinding binding = new BasicHttpBinding(); // Создание Конечной Точки. EndpointAddress endpoint = new EndpointAddress(address); // Создание фабрики каналов. ChannelFactory<IContract> factory = new ChannelFactory<IContract>(binding, endpoint); // Использование factory для создания канала (прокси). IContract channel = factory.CreateChannel(); // Использование канала для отправки сообщения получателю и приема ответа. string response = channel.Say("Hello WCF!"); Console.WriteLine(response); // Задержка. Console.ReadKey(); }
static void Main(string[] args) { var config = SetUp(); var baseUri = config.GetSection("TalentManagerRemotingService:BaseUri").Value; var subscriptionkey = config.GetSection("TalentManagerRemotingService:SubscriptionKey").Value; var authenticationToken = config.GetSection("TalentRecruiterRemotingService:AuthenticationToken").Value; string APISubscriptionKeyQuery = $"subscription-key={subscriptionkey}"; var binding = new BasicHttpsBinding(); var endpoint = new System.ServiceModel.EndpointAddress(baseUri + "?" + APISubscriptionKeyQuery); var talentMangerRemotingServiceClient = new TalentMangerRemotingServiceClient(binding, endpoint); //Example of how to fill out the request //Delete and replace these details with your company data var query = new GetBatchSyncEmployeesStatusRqt() { AuthenticationToken = authenticationToken, CustomerId = 1886, ReferenceToken = "20191017-4", InitialReferenceToken = "20191017-4" }; //End of Example var v = talentMangerRemotingServiceClient.GetBatchSyncEmployeesStatusAsync(query); v.Wait(); Console.WriteLine(v.Result.TransactionStatus.StatusDescription); Console.Read(); }
public static string GetAppointment(string matricula) { var aosUriString = ClientConfiguration.Default.UriString; var oauthHeader = OAuthHelper.GetAuthenticationHeader(); var serviceUriString = SoapUtility.SoapHelper.GetSoapServiceUriString("AXZTMSAppointmentServiceGroup", aosUriString); var endpointAddress = new System.ServiceModel.EndpointAddress(serviceUriString); var binding = SoapUtility.SoapHelper.GetBinding(); var client = new AXZTMSAppointmentServiceClient(binding, endpointAddress); var channel = client.InnerChannel; CallContext callContext = new CallContext(); callContext.Company = "USMF"; callContext.Language = "es"; MatriculaDC matriculaDC = new MatriculaDC(); matriculaDC.Matricula = matricula; string appointmentId = ""; using (OperationContextScope operationContextScope = new OperationContextScope(channel)) { HttpRequestMessageProperty requestMessage = new HttpRequestMessageProperty(); requestMessage.Headers[OAuthHelper.OAuthHeader] = oauthHeader; OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessage; appointmentId = ((AXZTMSAppointmentService)channel).getAppointmentIdAsync(matriculaDC).Result; } return(appointmentId); }
private static BlogServiceClient CreateBlogServiceClient(string username, string password) { BlogServiceClient blogServiceClient = null; System.ServiceModel.BasicHttpBinding basicHttpbinding = new System.ServiceModel.BasicHttpBinding(System.ServiceModel.BasicHttpSecurityMode.None); basicHttpbinding.Name = "BasicHttpBinding_IBlogService"; basicHttpbinding.MaxReceivedMessageSize = 2147483646; basicHttpbinding.MaxBufferSize = 2147483646; basicHttpbinding.MaxBufferPoolSize = 2147483646; basicHttpbinding.ReaderQuotas.MaxArrayLength = 2147483646; basicHttpbinding.ReaderQuotas.MaxStringContentLength = 5242880; basicHttpbinding.SendTimeout = new TimeSpan(0, 5, 0); basicHttpbinding.CloseTimeout = new TimeSpan(0, 5, 0); basicHttpbinding.Security.Mode = BasicHttpSecurityMode.None; basicHttpbinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None; System.ServiceModel.EndpointAddress endpointAddress = new System.ServiceModel.EndpointAddress(hostURI); blogServiceClient = new BlogServiceClient(basicHttpbinding, endpointAddress); blogServiceClient.ChannelFactory.Endpoint.Behaviors.Add(new AuthenticationInspectorBehavior()); ClientAuthenticationHeaderContext.HeaderInformation.Username = username; ClientAuthenticationHeaderContext.HeaderInformation.Password = password; return(blogServiceClient); }
public ProtoBufMetaDataReplyChannel(EndpointAddress address, ChannelManagerBase parent, IReplyChannel innerChannel) : base(parent, innerChannel) { this._localAddress = address; _innerChannel = innerChannel; }
public async Task <IPlayer> LoginUserAsync(string username, string password) { var address = new System.ServiceModel.EndpointAddress("http://sanet.by/KniffelService.asmx"); BasicHttpBinding bind = new BasicHttpBinding(); var client = new KniffelServiceSoapClient(bind, address); int rolls = 0; int manuals = 0; int resets = 0; password = password.Encrypt(33); try { var result = await client.GetPlayersMagicsTaskAsync(username, password, rolls, manuals, resets); if (result.Body.GetPlayersMagicsResult) { return(new Player() { Name = username, Password = password }); } } catch { return(null); } finally { client.CloseAsync(); } return(null); }
public static void SameBinding_Binary_EchoComplexString() { CustomBinding binding = null; ChannelFactory<IWcfService> factory = null; EndpointAddress endpointAddress = null; IWcfService serviceProxy = null; ComplexCompositeType compositeObject = null; ComplexCompositeType result = null; try { // *** SETUP *** \\ binding = new CustomBinding(new BinaryMessageEncodingBindingElement(), new HttpTransportBindingElement()); endpointAddress = new EndpointAddress(Endpoints.HttpBinary_Address); factory = new ChannelFactory<IWcfService>(binding, endpointAddress); serviceProxy = factory.CreateChannel(); compositeObject = ScenarioTestHelpers.GetInitializedComplexCompositeType(); // *** EXECUTE *** \\ result = serviceProxy.EchoComplex(compositeObject); // *** VALIDATE *** \\ Assert.True(compositeObject.Equals(result), String.Format(" Error: expected response from service: '{0}' Actual was: '{1}'", compositeObject, result)); // *** CLEANUP *** \\ factory.Close(); ((ICommunicationObject)serviceProxy).Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }
public static Object GetWcfReference(Type type, object[] info) { if (info.Length == 2) info = new object[] { info[0], null, info[1] }; if (info.Length != 3) return null; Type genType; Type factType; if (info[0] == null) { genType = typeof(ChannelFactory<>); factType = genType.MakeGenericType(new Type[] { type }); if (info[1] == null) info[1] = new WSHttpBinding(); info = new object[] { info[1], new EndpointAddress((string)info[2]) }; } else { genType = typeof(DuplexChannelFactory<>); factType = genType.MakeGenericType(new Type[] { type }); info[0] = new InstanceContext(info[0]); info[2] = new EndpointAddress((string)info[2]); if (info[1] == null) info[1] = new WSDualHttpBinding(); } object factObject = Activator.CreateInstance(factType, info); MethodInfo methodInfo = factType.GetMethod("CreateChannel", new Type[] { }); return methodInfo.Invoke(factObject, null); }
public RabbitMQTransportOutputChannel(BindingContext context, EndpointAddress address, Uri via) : base(context, address, via) { _bindingElement = context.Binding.Elements.Find<RabbitMQTransportBindingElement>(); MessageEncodingBindingElement encoderElement; if (_bindingElement.MessageFormat == MessageFormat.MTOM) { encoderElement = context.Binding.Elements.Find<MtomMessageEncodingBindingElement>(); } else if (_bindingElement.MessageFormat == MessageFormat.NetBinary) { encoderElement = context.Binding.Elements.Find<BinaryMessageEncodingBindingElement>(); } else { encoderElement = context.Binding.Elements.Find<TextMessageEncodingBindingElement>(); } if (encoderElement != null) { _encoder = encoderElement.CreateMessageEncoderFactory().Encoder; } _messageProcessor = context.BindingParameters.Find<IFaultMessageProcessor>(); }
public RightNowService(IGlobalContext _gContext) { // Set up SOAP API request to retrieve Endpoint Configuration - // Get the SOAP API url of current site as SOAP Web Service endpoint EndpointAddress endPointAddr = new EndpointAddress(_gContext.GetInterfaceServiceUrl(ConnectServiceType.Soap)); // Minimum required BasicHttpBinding binding2 = new BasicHttpBinding(BasicHttpSecurityMode.TransportWithMessageCredential); binding2.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName; // Optional depending upon use cases binding2.MaxReceivedMessageSize = 5 * 1024 * 1024; binding2.MaxBufferSize = 5 * 1024 * 1024; binding2.MessageEncoding = WSMessageEncoding.Mtom; // Create client proxy class _rnowClient = new RightNowSyncPortClient(binding2, endPointAddr); BindingElementCollection elements = _rnowClient.Endpoint.Binding.CreateBindingElements(); elements.Find<SecurityBindingElement>().IncludeTimestamp = false; _rnowClient.Endpoint.Binding = new CustomBinding(elements); // Add SOAP msg inspector behavior //_rnowClient.Endpoint.Behaviors.Add(new LogMsgBehavior()); // Ask the Add-In framework the handle the session logic _gContext.PrepareConnectSession(_rnowClient.ChannelFactory); // Set up query and set request _rnowClientInfoHeader = new ClientInfoHeader(); _rnowClientInfoHeader.AppID = "Case Management Accelerator Services"; }
private static bool FindUserServiceServer() { string[] serviceRootUrls = ConfigurationManager.AppSettings["LicenseHost"].Split(';'); foreach (string serviceRootUrl in serviceRootUrls) { string serviceUrl = serviceRootUrl + "/Services/UserService.svc"; System.ServiceModel.BasicHttpBinding binding = new System.ServiceModel.BasicHttpBinding(System.ServiceModel.BasicHttpSecurityMode.None); binding.MaxReceivedMessageSize = 10485760; //1Gig System.ServiceModel.EndpointAddress endPointAddress = new System.ServiceModel.EndpointAddress(serviceUrl); BitSite.UserServiceReference.UserServiceClient client = new BitSite.UserServiceReference.UserServiceClient(binding, endPointAddress); try { client.HandShake(); userServiceClient = client; return(true); } catch { } } return(false); }
protected override IOutputSessionChannel OnCreateChannel(System.ServiceModel.EndpointAddress remoteAddress, Uri via) { SsbOutputSessionChannel channel; channel = new SsbOutputSessionChannel(this, this.connstr, via, remoteAddress, this.bufferManager, this.messageEncoderFactory.Encoder, endConversationOnClose, contract, useEncryption, useActionForSsbMessageType); return(channel); }
public FileTransferServiceProxy() { this.m_BasicHttpBinding = new BasicHttpBinding(); this.m_EndpointAddress = new EndpointAddress(EndpointAddressUrl); this.m_BasicHttpBinding.Security.Mode = BasicHttpSecurityMode.TransportWithMessageCredential; this.m_BasicHttpBinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName; this.m_BasicHttpBinding.MaxReceivedMessageSize = 2147483647; XmlDictionaryReaderQuotas readerQuotas = new XmlDictionaryReaderQuotas(); readerQuotas.MaxArrayLength = 25 * 208000; readerQuotas.MaxStringContentLength = 25 * 208000; this.m_BasicHttpBinding.ReaderQuotas = readerQuotas; this.m_ChannelFactory = new ChannelFactory<Contract.IFileTransferService>(this.m_BasicHttpBinding, this.m_EndpointAddress); this.m_ChannelFactory.Credentials.UserName.UserName = YellowstonePathology.YpiConnect.Contract.Identity.GuestWebServiceAccount.UserName; this.m_ChannelFactory.Credentials.UserName.Password = YellowstonePathology.YpiConnect.Contract.Identity.GuestWebServiceAccount.Password; foreach (System.ServiceModel.Description.OperationDescription op in this.m_ChannelFactory.Endpoint.Contract.Operations) { var dataContractBehavior = op.Behaviors.Find<System.ServiceModel.Description.DataContractSerializerOperationBehavior>(); if (dataContractBehavior != null) { dataContractBehavior.MaxItemsInObjectGraph = int.MaxValue; } } this.m_FileTransferServiceChannel = this.m_ChannelFactory.CreateChannel(); }
/// <summary> /// EndPoint를 정의합니다. /// </summary> /// <param name="bind">The bind.</param> /// <returns></returns> private static EndpointAddress GetEndpointAddress(MessageEncoding bind) { try { System.ServiceModel.EndpointAddress endpointAdress = null; string temp = mService.ServiceURI.ToUpper().IndexOf("NET.TCP") >= 0 ? "/NETTCP" : "/DATA"; endpointAdress = new System.ServiceModel.EndpointAddress(mService.ServiceURI + temp); //switch (bind) //{ // case MessageEncoding.MTOM: // endpointAdress = new System.ServiceModel.EndpointAddress(mService.ServiceURI + "/MTOM"); // break; // case MessageEncoding.Default: // string temp = mService.ServiceURI.ToUpper().IndexOf("NET.TCP") >=0 ? "/NETTCP" : "/DATA"; // endpointAdress = new System.ServiceModel.EndpointAddress(mService.ServiceURI + temp); // break; //} return(endpointAdress); } catch (Exception ex) { throw ex; } }
public OutputChannelBase (ChannelFactoryBase factory, EndpointAddress remoteAddress, Uri via) : base (factory) { this.channel_factory = factory; RemoteAddress = remoteAddress; Via = via; }
public OrationiSlave() { Binding binding = new NetTcpBinding(SecurityMode.None); EndpointAddress defaultEndpointAddress = new EndpointAddress("net.tcp://localhost:57344/Orationi/Master/v1/"); EndpointAddress discoveredEndpointAddress = DiscoverMaster(); ContractDescription contractDescription = ContractDescription.GetContract(typeof(IOrationiMasterService)); ServiceEndpoint serviceEndpoint = new ServiceEndpoint(contractDescription, binding, discoveredEndpointAddress ?? defaultEndpointAddress); var channelFactory = new DuplexChannelFactory<IOrationiMasterService>(this, serviceEndpoint); try { channelFactory.Open(); } catch (Exception ex) { channelFactory?.Abort(); } try { _masterService = channelFactory.CreateChannel(); _communicationObject = (ICommunicationObject)_masterService; _communicationObject.Open(); } catch (Exception ex) { if (_communicationObject != null && _communicationObject.State == CommunicationState.Faulted) _communicationObject.Abort(); } }
public SslStreamSecurityUpgradeInitiator(SslStreamSecurityUpgradeProvider parent, EndpointAddress remoteAddress, Uri via) : base("application/ssl-tls", remoteAddress, via) { SecurityTokenResolver resolver; this.parent = parent; InitiatorServiceModelSecurityTokenRequirement tokenRequirement = new InitiatorServiceModelSecurityTokenRequirement { TokenType = SecurityTokenTypes.X509Certificate, RequireCryptographicToken = true, KeyUsage = SecurityKeyUsage.Exchange, TargetAddress = remoteAddress, Via = via, TransportScheme = this.parent.Scheme }; this.serverCertificateAuthenticator = parent.ClientSecurityTokenManager.CreateSecurityTokenAuthenticator(tokenRequirement, out resolver); if (parent.RequireClientCertificate) { InitiatorServiceModelSecurityTokenRequirement requirement2 = new InitiatorServiceModelSecurityTokenRequirement { TokenType = SecurityTokenTypes.X509Certificate, RequireCryptographicToken = true, KeyUsage = SecurityKeyUsage.Signature, TargetAddress = remoteAddress, Via = via, TransportScheme = this.parent.Scheme }; this.clientCertificateProvider = parent.ClientSecurityTokenManager.CreateSecurityTokenProvider(requirement2); if (this.clientCertificateProvider == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("ClientCredentialsUnableToCreateLocalTokenProvider", new object[] { requirement2 }))); } } }
public static MixObjectsSoapClient CreateServiceClient() { var endpointAddr = new EndpointAddress(new Uri(Application.Current.Host.Source, Page.ServiceUrl)); var binding = new BasicHttpBinding(); var ctor = typeof(MixObjectsSoapClient).GetConstructor(new Type[] { typeof(Binding), typeof(EndpointAddress) }); return (MixObjectsSoapClient)ctor.Invoke(new object[] { binding, endpointAddr }); }
public byte[] GetFile(ClassLibrary.Entites.File file, long partNumber) { PNRPManager manager = PeerServiceHost.PNRPManager; List<ClassLibrary.Entites.Peer> foundPeers = manager.ResolveByPeerName(file.PeerName); if (foundPeers.Count != 0) { ClassLibrary.Entites.Peer peer = foundPeers.FirstOrDefault(); EndpointAddress endpointAddress = new EndpointAddress(string.Format("net.tcp://{0}:{1}/PeerToPeerClient.Services/PeerService", peer.PeerHostName, ClassLibrary.Config.LocalPort)); NetTcpBinding tcpBinding = new NetTcpBinding(SecurityMode.None); PeerServiceClient client = new PeerServiceClient(tcpBinding, endpointAddress); byte[] data = null; try { data = client.TransferFile(file, partNumber); } catch { throw new Exception("Unreachable host '" + file.PeerName); } return data; } else { throw new Exception("Unable to resolve peer " + file.PeerName); } }
private void StartDownload() { new Thread(delegate() { bool retry = false; int count = 0; do { retry = false; try { NetNamedPipeBinding binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None); EndpointAddress address = new EndpointAddress("net.pipe://localhost/download"); using (ChannelFactory<IDownloadManager> factory = new ChannelFactory<IDownloadManager>(binding, address)) { IDownloadManager dm = factory.CreateChannel(); if (dm != null) { string msg = dm.CopyFile("test file"); MessageBox.Show(msg); } factory.Close(); } } catch (CommunicationException) { retry = (count++ < 30); Thread.Sleep(1000); } } while(retry); }).Start(); }
public Client(String URL) { BasicHttpBinding myBinding = new BasicHttpBinding(); EndpointAddress myEndpoint = new EndpointAddress(URL); myChannelFactory = new ChannelFactory<Server.IServerService>(myBinding, myEndpoint); comInterface = myChannelFactory.CreateChannel(); }
static void Main(string[] args) { Console.Title = "CLIENT"; // Указание, где ожидать входящие сообщения. Uri address = new Uri("http://localhost:4000/IContract"); // ADDRESS. (A) // Указание, как обмениваться сообщениями. BasicHttpBinding binding = new BasicHttpBinding(); // BINDING. (B) // Создание Конечной Точки. EndpointAddress endpoint = new EndpointAddress(address); // Создание фабрики каналов. ChannelFactory<IContract> factory = new ChannelFactory<IContract>(binding, endpoint); // CONTRACT. (C) // Использование factory для создания канала (прокси). IContract channel = factory.CreateChannel(); // Использование канала для отправки сообщения получателю. channel.Say("Hello WCF!");// сложный механизм // Задержка. Console.ReadKey(); }
void MainPageLoaded(object sender, RoutedEventArgs e) { // Simple Version var basicHttpBinding = new BasicHttpBinding(); var endpointAddress = new EndpointAddress("http://localhost:50738/UserGroupEvent.svc"); var userGroupEventService = new ChannelFactory<IAsyncUserGroupEventService>(basicHttpBinding, endpointAddress).CreateChannel(); AsyncCallback asyncCallBack = delegate(IAsyncResult result) { var response = ((IAsyncUserGroupEventService)result.AsyncState).EndGetUserGroupEvent(result); Dispatcher.BeginInvoke(() => SetUserGroupEventData(response)); }; userGroupEventService.BeginGetUserGroupEvent("123", asyncCallBack, userGroupEventService); // Deluxe Variante mit eigenem Proxy var channel = new UserGroupEventServiceProxy("BasicHttpBinding_IAsyncUserGroupEventService").Channel; channel.BeginGetUserGroupEvent("123", ProcessResult, channel); // Variante mit Faulthandler using (var scope = new OperationContextScope((IContextChannel)channel)) { var messageHeadersElement = OperationContext.Current.OutgoingMessageHeaders; messageHeadersElement.Add(MessageHeader.CreateHeader("DoesNotHandleFault", "", true)); channel.BeginGetUserGroupEventWithFault("123", ProcessResultWithFault, channel); } }
static void Main(string[] args) { CalculatorClient client1 = new CalculatorClient("calculatorservice"); client1.Open(); CalculatorClient client2 = new CalculatorClient("calculatorservice"); client2.Open(); client1.Close(); client2.Close(); Console.WriteLine("ChannelFactory的状态: {0}", client1.ChannelFactory.State); Console.WriteLine("ChannelFactory的状态: {0}\n", client2.ChannelFactory.State); EndpointAddress address = new EndpointAddress("http://127.0.0.1:3721/calculatorservice"); Binding binding = new WS2007HttpBinding(); CalculatorClient client3 = new CalculatorClient(binding, address); client3.Open(); CalculatorClient client4 = new CalculatorClient(binding, address); client4.Open(); client3.Close(); client4.Close(); Console.WriteLine("ChannelFactory的状态: {0}", client3.ChannelFactory.State); Console.WriteLine("ChannelFactory的状态: {0}", client4.ChannelFactory.State); Console.Read(); }
public ImitatorServiceFactory() { var binding = BindingHelper.CreateBindingFromAddress("net.pipe://127.0.0.1/GKImitator/"); var endpointAddress = new EndpointAddress(new Uri("net.pipe://127.0.0.1/GKImitator/")); _channelFactory = new ChannelFactory<IImitatorService>(binding, endpointAddress); _channelFactory.Open(); }
/// <summary> /// SerialChannel Base /// </summary> /// <param name="bufferManager"> /// Buffer manager created by factory and listener</param> /// <param name="encoderFactory"> /// Referece to encoder factory as returned by encoder element</param> /// <param name="address">Remote address</param> /// <param name="portNumber">COM port number</param> /// <param name="parent">reference to factory/listener</param> /// <param name="maxReceivedMessageSize"> /// Some settings for transport channel</param> public SerialChannelBase(BufferManager bufferManager, MessageEncoderFactory encoderFactory, EndpointAddress address, string portNumber, ChannelManagerBase parent, long maxReceivedMessageSize) : base(parent) { this.address = address; this.bufferManager = bufferManager; this.encoder = encoderFactory.CreateSessionEncoder(); this.maxReceivedMessageSize = maxReceivedMessageSize; this.portNumber = portNumber; // Create port serialPort = new SerialPort(); // Set the appropriate properties. serialPort.PortName = this.portNumber; //TODO: Read these settings from configuration file serialPort.BaudRate = 9600; serialPort.Parity = Parity.None; serialPort.DataBits = 8; serialPort.StopBits = StopBits.One; serialPort.Handshake = Handshake.None; // Set the read/write timeouts serialPort.ReadTimeout = 500; serialPort.WriteTimeout = 500; }
private ChannelFactory<ISharedTextEditorC2S> GetChannelFactory(string host) { var binding = new BasicHttpBinding(); var endpoint = new EndpointAddress(host); return new ChannelFactory<ISharedTextEditorC2S>(binding, endpoint); }
public override bool TryGetToken(EndpointAddress target, EndpointAddress issuer, out GenericXmlSecurityToken cachedToken) { if (target == null) { throw new ArgumentNullException("target"); } cachedToken = null; lock (thisLock) { GenericXmlSecurityToken tmp; Key key = new Key(target.Uri, issuer == null ? null : issuer.Uri); if (this.cache.TryGetValue(key, out tmp)) { // if the cached token is going to expire soon, remove it from the cache and return a cache miss if (tmp.ValidTo < DateTime.UtcNow + TimeSpan.FromMinutes(1)) { this.cache.Remove(key); OnTokenRemoved(key); } else { cachedToken = tmp; } } } return (cachedToken != null); }
static void Main( string[] args ) { EndpointAddress address = new EndpointAddress("http://localhost:8001/TradeService"); WSHttpBinding binding = new WSHttpBinding(); System.ServiceModel.ChannelFactory<ITradeService> cf = new ChannelFactory<ITradeService>(binding, address); ITradeService proxy = cf.CreateChannel(); Console.WriteLine("\nTrade IBM"); try { double result = proxy.TradeSecurity("IBM", 1000); Console.WriteLine("Cost was " + result); Console.WriteLine("\nTrade MSFT"); result = proxy.TradeSecurity("MSFT", 2000); Console.WriteLine("Cost was " + result); } catch (Exception ex) { Console.Write("Can not perform task. Error Message - " + ex.Message); } Console.WriteLine("\n\nPress <enter> to exit..."); Console.ReadLine(); }
public EndpointAddressBuilder (EndpointAddress address) { identity = address.Identity; uri = address.Uri; foreach (AddressHeader h in address.Headers) headers.Add (h); }
/// <summary> /// Конструктор PerfCountersStableNetClient /// </summary> /// <param name="endpointConfigurationName">Имя конфигурации</param> /// <param name="remoteAddress">Удалённый адрес</param> /// <param name="connectionTestTimeMs">Время переподключения</param> public PerfCountersStableNetClient(string endpointConfigurationName, string remoteAddress, int connectionTestTimeMs) { _crEnpointConfigName = endpointConfigurationName; _crRemoteAddr = new System.ServiceModel.EndpointAddress(remoteAddress); _connectionTestTimeMsMin = Math.Max(500, connectionTestTimeMs / 32); _connectionTestTimeMsMax = connectionTestTimeMs; }
public static EndpointAddress GetEndPointAddress() { var serviceUriString = SoapHelper.GetSoapServiceUriString(AppSettings.GetByKey("OperationsServiceGroupName"), AppSettings.GetByKey("OperationsUriString")); var endpointAddress = new System.ServiceModel.EndpointAddress(serviceUriString); return(endpointAddress); }
/// <summary> /// StableLoggerNetClient constructor /// </summary> /// <param name="binding">The binding with which to make calls to the service</param> /// <param name="remoteAddress">The address of the service endpoint</param> /// <param name="connectionTestTimeMs">Max reconnection period in milliseconds</param> public StableLoggerNetClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress, int connectionTestTimeMs) { _crBinding = binding; _crRemoteAddr = remoteAddress; _connectionTestTimeMsMin = Math.Max(500, connectionTestTimeMs / 32); _connectionTestTimeMsMax = connectionTestTimeMs; }
/// <summary> /// StableLoggerNetClient constructor /// </summary> /// <param name="endpointConfigurationName">The name of the endpoint in the application configuration file</param> /// <param name="remoteAddress">The address of the service endpoint</param> /// <param name="connectionTestTimeMs">Max reconnection period in milliseconds</param> public StableLoggerNetClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress, int connectionTestTimeMs) { _crEnpointConfigName = endpointConfigurationName; _crRemoteAddr = remoteAddress; _connectionTestTimeMsMin = Math.Max(500, connectionTestTimeMs / 32); _connectionTestTimeMsMax = connectionTestTimeMs; }
public DinerwareProvider() { ConfigurationHelper conFigHelper = new ConfigurationHelper(); var endPointAddress = new System.ServiceModel.EndpointAddress(conFigHelper.URL_VIRTUALCLIENT); var binding = new System.ServiceModel.BasicHttpBinding(); binding.Security.Mode = BasicHttpSecurityMode.None; virtualDinerwareClient = new VirtualClientClient(binding, endPointAddress); }
private static UkPostalCodeService.LookupSoapClient CreateUkServiceClient() { var binding = new System.ServiceModel.BasicHttpBinding(); var address = new System.ServiceModel.EndpointAddress("http://ws1.postcodesoftware.co.uk/lookup.asmx"); var client = new UkPostalCodeService.LookupSoapClient(binding, address); return(client); }
public GameServiceClient(System.ServiceModel.EndpointAddress remoteAddress) : this(new GameServiceClientCallback(), new CustomBinding( new PollingDuplexBindingElement(), new BinaryMessageEncodingBindingElement(), new HttpTransportBindingElement()), remoteAddress) { }
public Form1() { InitializeComponent(); Pbar.Visible = false; CPUlevel.SelectedIndex = 0; dgvTopResults.DataSource = resultList; System.ServiceModel.BasicHttpBinding binding = new System.ServiceModel.BasicHttpBinding(); System.ServiceModel.EndpointAddress address = new System.ServiceModel.EndpointAddress("http://fascinatinginformation.com/ADFGXService/Service.svc"); client = new ServiceClient(binding, address); }
protected override void ProcessRecord() { base.ProcessRecord(); var remoteAddress = new System.ServiceModel.EndpointAddress(SapiUrl); HttpBindingBase binding; if (remoteAddress.Uri.Scheme == "https") { binding = new System.ServiceModel.BasicHttpsBinding(); } else { binding = new System.ServiceModel.BasicHttpBinding(); } SapiClients.client = new SapiClient(binding, remoteAddress); var behaviour = new CustomAuthenticationBehaviour(); SapiClients.client.Endpoint.EndpointBehaviors.Add(behaviour); pscConnectOptions pscOptions = new pscConnectOptions { base64 = Base64, authServer = Server, user = User, password = Password }; if (PortSet) { pscOptions.portSpecified = true; pscOptions.port = PortValue; } var loginResult = SapiClients.client.login(pscOptions); behaviour.ApplyAuthenticationToken(loginResult.token); var actionTask = SapiClients.client.connectAsync(); var result = Progress("Connect", actionTask); var finalResult = new SapiConnectResult(result); // For Interval in Seconds // This Scheduler will start after 0 hour and 15 minutes call after every 15 minutes // IntervalInSeconds(start_hour, start_minute, seconds) MyScheduler.IntervalInMinutes(0, 15, 15, () => { SapiClients.client.keepalive(); }); WriteObject(finalResult); // This is what actually "returns" output. }
public static PrisModelURSClient GetPrisModelURSClient(Miljoe miljoe, string partyID, string password, string endpointAddress) { PrisModelURSClient client = new PrisModelURSClient(); client.Endpoint.Behaviors.Add(new CustomBehavior(partyID)); client.Endpoint.Behaviors.Add(new ClientViaBehavior(new Uri(URS_Utils.GetEndpointAddress(miljoe)))); SetClientCredentials(client.ClientCredentials, partyID, password); System.ServiceModel.EndpointAddress addr = new System.ServiceModel.EndpointAddress(endpointAddress); client.Endpoint.Address = addr; return(client); }
private BisWsWebserviceCallClient GetClient() { var aosUriString = clientConfig.UriString; var serviceUriString = SoapHelper.GetSoapServiceUriString(BisActionServiceName, aosUriString); var endpointAddress = new System.ServiceModel.EndpointAddress(serviceUriString); var binding = SoapHelper.GetBinding(); var client = new BisWsWebserviceCallClient(binding, endpointAddress); return(client); }
private BisMessageHttpActionServiceReference.BisMessageStartFromHttpClient GetClient() { var aosUriString = ClientConfiguration.getClientConfiguration().UriString; var serviceUriString = SoapHelper.GetSoapServiceUriString(BisMessageHttpActionServiceName, aosUriString); var endpointAddress = new System.ServiceModel.EndpointAddress(serviceUriString); var binding = SoapHelper.GetBinding(); var client = new BisMessageHttpActionServiceReference.BisMessageStartFromHttpClient(binding, endpointAddress); return(client); }
protected void Init() { CEHeader = new CEHeader { BillingCenter = Ambiente.billingcenter, CodiceFiscale = Ambiente.codicefiscale, ContractId = Ambiente.contractid, ContractType = Ambiente.contracttype, CostCenter = Ambiente.costcenter, Customer = Ambiente.customer, IdCRM = string.Empty, SenderSystem = Ambiente.sendersystem, UserId = Ambiente.smuser, PartitaIva = Ambiente.partitaiva, IDSender = string.Empty, UserType = Ambiente.usertype }; CE = new CE(); CE.Header = CEHeader; CE.Header.GUIDMessage = IdRichiesta; _httpHeaders = GetHttpHeaders(Ambiente); string uri = null; switch (Servizio.TipoServizioId) { case (int)TipoServizioId.POSTA1: case (int)TipoServizioId.POSTA4: uri = Ambiente.LolUri; break; case (int)TipoServizioId.ROL: uri = Ambiente.RolUri; break; default: break; } var enpointAddress = new System.ServiceModel.EndpointAddress(uri); BasicHttpBinding myBinding = new BasicHttpBinding(); myBinding.SendTimeout = TimeSpan.FromMinutes(3); myBinding.MaxReceivedMessageSize = 2147483647; WsCEClient = new WsCEClient(myBinding, enpointAddress); }
private void ThisAddIn_Startup(object sender, System.EventArgs e) { // Upon running Excel - Open a blank new Workbook this.Application.Workbooks.Add(); // Initialize the client var binding = new BasicHttpBinding(); binding.MaxReceivedMessageSize = Int32.MaxValue; binding.MaxBufferSize = Int32.MaxValue; var endpointAddress = new System.ServiceModel.EndpointAddress(MNB_ENDPOINT_ADDRESS); client = new MNBArfolyamServiceSoapClient(binding, endpointAddress); }
static void Main(string[] args) { try { Options options = new Options(args); AmqpBinaryBinding binding = new AmqpBinaryBinding(); binding.BrokerHost = options.Broker; binding.BrokerPort = options.Port; binding.TransferMode = TransferMode.Streamed; IChannelFactory <IOutputChannel> factory = binding.BuildChannelFactory <IOutputChannel>(); factory.Open(); try { System.ServiceModel.EndpointAddress addr = options.Address; IOutputChannel sender = factory.CreateChannel(addr); sender.Open(); MyRawBodyWriter.Initialize(options.Content); DateTime end = DateTime.Now.Add(options.Timeout); System.ServiceModel.Channels.Message message; for (int count = 0; ((count < options.Count) || (options.Count == 0)) && ((options.Timeout == TimeSpan.Zero) || (end.CompareTo(DateTime.Now) > 0)); count++) { message = Message.CreateMessage(MessageVersion.None, "", new MyRawBodyWriter()); AmqpProperties props = new AmqpProperties(); props.ContentType = "text/plain"; string id = Guid.NewGuid().ToString() + ":" + count; props.PropertyMap.Add("spout-id", new AmqpString(id)); message.Properties["AmqpProperties"] = props; sender.Send(message); } } finally { factory.Close(); } } catch (Exception e) { Console.WriteLine("Spout: " + e); } }
static void Main(string[] args) { //using namedpipe endpoint for the communication wcf.EndpointAddress _address = new wcf.EndpointAddress("net.pipe://localhost/onmachinecchannel"); wcf.NetNamedPipeBinding _pipeBinding = new wcf.NetNamedPipeBinding(); //Building Proxy Object Using ChannelFactory class CalculatorServiceContractLib.ICalculate _proxy = wcf.ChannelFactory <CalculatorServiceContractLib.ICalculate> .CreateChannel (_pipeBinding, _address); int result = _proxy.Add(10, 20); Console.WriteLine(result); Console.ReadKey(); }
public EndpointDispatcher(System.ServiceModel.EndpointAddress address, string contractName, string contractNamespace, bool isSystemEndpoint) { this.originalAddress = address; this.contractName = contractName; this.contractNamespace = contractNamespace; if (address != null) { this.addressFilter = new EndpointAddressMessageFilter(address); } else { this.addressFilter = new MatchAllMessageFilter(); } this.contractFilter = new MatchAllMessageFilter(); this.dispatchRuntime = new System.ServiceModel.Dispatcher.DispatchRuntime(this); this.filterPriority = 0; this.isSystemEndpoint = isSystemEndpoint; }
static void Main(string[] args) { try { Options options = new Options(args); AmqpBinaryBinding binding = new AmqpBinaryBinding(); binding.BrokerHost = options.Broker; binding.BrokerPort = options.Port; binding.TransferMode = TransferMode.Streamed; IChannelFactory <IInputChannel> factory = binding.BuildChannelFactory <IInputChannel>(); factory.Open(); try { System.ServiceModel.EndpointAddress addr = options.Address; IInputChannel receiver = factory.CreateChannel(addr); receiver.Open(); TimeSpan timeout = options.Timeout; System.ServiceModel.Channels.Message message; while (receiver.TryReceive(timeout, out message)) { AmqpProperties props = (AmqpProperties)message.Properties["AmqpProperties"]; Console.WriteLine("Message(properties=" + MessagePropertiesAsString(props) + ", content='" + MessageContentAsString(message, props) + "')"); } } finally { factory.Close(); } } catch (Exception e) { Console.WriteLine("Drain: " + e); } }
public RFServiceClient() { try { var binding = new System.ServiceModel.NetNamedPipeBinding("riffBinding"); var uri = RFSettings.GetAppSetting("RFServiceUri"); var endpoint = new System.ServiceModel.EndpointAddress(uri); var channelFactory = new ChannelFactory <IRFService>(binding, endpoint); RFService = channelFactory.CreateChannel(); } catch { if (RFService != null) { ((ICommunicationObject)RFService).Abort(); } throw; } }
public static AutorisationClient GetClient() { string serviceRootUrl = ConfigurationManager.AppSettings["LicenseHost"]; string serviceUrl = serviceRootUrl + "/Autorisation.svc"; System.ServiceModel.BasicHttpBinding binding = new System.ServiceModel.BasicHttpBinding(System.ServiceModel.BasicHttpSecurityMode.None); //binding.MaxBufferPoolSize = 2073741824; //2Gig //Int32.MaxValue; //binding.MaxBufferSize = 2073741824; //2Gig //Int32.MaxValue; //binding.ReaderQuotas = System.Xml.XmlDictionaryReaderQuotas.Max; binding.MaxReceivedMessageSize = 10485760; //1Gig //TEST EMIEL //binding.UseDefaultWebProxy = false; //binding.TransferMode = TransferMode.Buffered; System.ServiceModel.EndpointAddress endPointAddress = new System.ServiceModel.EndpointAddress(serviceUrl); BitSite.BitAutorisationService.AutorisationClient client = new BitSite.BitAutorisationService.AutorisationClient(binding, endPointAddress); return(client); }
public static T GetInstance() { T local = default(T); Type type = typeof(T); string serviceAddress = GetServiceAddress(type.Name.Replace("Client", "")); if (string.IsNullOrEmpty(serviceAddress)) { return(default(T)); } object[] parameters = new object[2]; System.ServiceModel.BasicHttpBinding binding = new System.ServiceModel.BasicHttpBinding(System.ServiceModel.BasicHttpSecurityMode.None) { MaxBufferSize = 0x7fffffff, MaxReceivedMessageSize = 0x7fffffffL, SendTimeout = new TimeSpan(0, 5, 0), ReceiveTimeout = new TimeSpan(0, 5, 0), OpenTimeout = new TimeSpan(0, 1, 0), CloseTimeout = new TimeSpan(0, 1, 0) }; System.ServiceModel.EndpointAddress address = new System.ServiceModel.EndpointAddress(new Uri(serviceAddress, UriKind.Absolute), new System.ServiceModel.Channels.AddressHeader[0]); parameters[0] = binding; parameters[1] = address; ConstructorInfo constructor = null; try { Type[] types = new Type[] { typeof(System.ServiceModel.Channels.Binding), typeof(System.ServiceModel.EndpointAddress) }; constructor = typeof(T).GetConstructor(types); } catch (Exception) { return(default(T)); } if (constructor != null) { local = (T)constructor.Invoke(parameters); } return(local); }
private EndpointDispatcher(EndpointDispatcher baseEndpoint, IEnumerable <AddressHeader> headers) { EndpointAddressBuilder builder = new EndpointAddressBuilder(baseEndpoint.EndpointAddress); foreach (AddressHeader header in headers) { builder.Headers.Add(header); } System.ServiceModel.EndpointAddress address = builder.ToEndpointAddress(); this.addressFilter = new EndpointAddressMessageFilter(address); this.contractFilter = baseEndpoint.ContractFilter; this.contractName = baseEndpoint.ContractName; this.contractNamespace = baseEndpoint.ContractNamespace; this.dispatchRuntime = baseEndpoint.DispatchRuntime; this.filterPriority = baseEndpoint.FilterPriority + 1; this.originalAddress = address; if (PerformanceCounters.PerformanceCountersEnabled) { this.perfCounterId = baseEndpoint.perfCounterId; this.perfCounterBaseId = baseEndpoint.perfCounterBaseId; } this.id = baseEndpoint.id; }