/// <summary> /// 创建WCF服务对象 /// </summary> /// <param name="serviceAddress">服务地址</param> /// <returns>服务对象</returns> public static IService CreateWCFServiceClient <IService>(string strUrl) where IService : class { //string serviceAddress = ConfigurationManagerHelper.GetInstance().GetAddressByKey(typeof(IService)); //if (string.IsNullOrEmpty(serviceAddress)) // return null; try { string account = GetClientAddress(); AddressHeader accountHeader = AddressHeader.CreateAddressHeader("ClientAddress", "Address", account); var endpointAddr = new EndpointAddress(new Uri(strUrl), accountHeader); BasicHttpBinding binding = new BasicHttpBinding(); binding.MaxBufferSize = 2147483647; binding.MaxReceivedMessageSize = 2147483647; binding.Security.Mode = BasicHttpSecurityMode.None; binding.ReceiveTimeout = new TimeSpan(0, 25, 0); binding.OpenTimeout = new TimeSpan(0, 25, 0); binding.SendTimeout = new TimeSpan(0, 25, 0); binding.CloseTimeout = new TimeSpan(0, 25, 0); ChannelFactory <IService> factory = new ChannelFactory <IService>(binding); IService service = factory.CreateChannel(endpointAddr); return(service); } catch (Exception) { return(null); } }
private static bool GetRemoteEnlistmentId(EndpointAddress address, out Guid remoteEnlistmentId) { AddressHeaderCollection headers = address.Headers; if (headers.Count == 1) { AddressHeader header = headers.FindHeader("Enlistment", "http://schemas.microsoft.com/ws/2006/02/transactions"); if (header != null) { XmlDictionaryReader addressHeaderReader = header.GetAddressHeaderReader(); XmlDictionaryReader reader2 = addressHeaderReader; try { ControlProtocol protocol; EnlistmentHeader.ReadFrom(addressHeaderReader, out remoteEnlistmentId, out protocol); return(protocol == ControlProtocol.Durable2PC); } catch (InvalidEnlistmentHeaderException exception) { Microsoft.Transactions.Bridge.DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, TraceEventType.Information); } finally { if (reader2 != null) { reader2.Dispose(); } } } } remoteEnlistmentId = Guid.Empty; return(false); }
public static void SnippetWriteToAddressingVersionXmlWriterXmlDictionaryStringXmlDictionaryString() { AddressHeader addressHeader1 = AddressHeader.CreateAddressHeader("specialservice1", "http://localhost:8000/service", 1); AddressHeader addressHeader2 = AddressHeader.CreateAddressHeader("specialservice2", "http://localhost:8000/service", 2); AddressHeader[] addressHeaders = new AddressHeader[2] { addressHeader1, addressHeader2 }; AddressHeaderCollection headers = new AddressHeaderCollection(addressHeaders); EndpointAddress endpointAddress = new EndpointAddress( new Uri("http://localhost:8003/servicemodelsamples/service/incode/identity"), addressHeaders); // <Snippet33> XmlWriter writer = XmlWriter.Create("addressdata.xml"); XmlDictionaryWriter dictWriter = XmlDictionaryWriter.CreateDictionaryWriter(writer); XmlDictionary d = new XmlDictionary(); XmlDictionaryString xdLocalName = new XmlDictionaryString(XmlDictionary.Empty, "EndpointReference", 0); XmlDictionaryString xdNamespace = new XmlDictionaryString(XmlDictionary.Empty, "http://www.w3.org/2005/08/addressing", 0); endpointAddress.WriteTo( AddressingVersion.WSAddressing10, dictWriter, xdLocalName, xdNamespace); writer.Close(); // </Snippet33> }
/// <summary> /// Replaces the <see cref="Identifier"/> value, if any, with the supplied <paramref name="id"/>, if any. /// </summary> /// <param name="id">The new identifier value to use, or clear if null.</param> public void CreateIdentifierHeader(Guid?id) { var builder = new EndpointAddressBuilder(this.EndpointAddress.ToEndpointAddress()); var header = builder.Headers.FirstOrDefault(a => a.Name == "Identifier" && a.Namespace == Constants.WsEventing.Namespace); if (id == null) { if (header == null) { return; } var wasRemoved = builder.Headers.Remove(header); Debug.Assert(wasRemoved); } else { if (header != null) { var wasRemoved = builder.Headers.Remove(header); Debug.Assert(wasRemoved); } var uuid = new UniqueId(id.Value); header = AddressHeader.CreateAddressHeader("Identifier", Constants.WsEventing.Namespace, uuid.ToString()); builder.Headers.Add(header); } this.epa = EndpointAddressAugust2004.FromEndpointAddress(builder.ToEndpointAddress()); }
private static TService HttpCreate <TService>(string uri, int TimeOut) { WSHttpBinding binding = new System.ServiceModel.WSHttpBinding(); binding.SendTimeout = TimeSpan.FromSeconds(TimeOut); binding.ReceiveTimeout = TimeSpan.FromSeconds(TimeOut); binding.MaxReceivedMessageSize = int.MaxValue; binding.ReaderQuotas.MaxStringContentLength = int.MaxValue; binding.ReaderQuotas.MaxArrayLength = int.MaxValue; binding.ReaderQuotas.MaxBytesPerRead = int.MaxValue; #region 设置一些配置信息 binding.Security.Mode = SecurityMode.None; binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None; #endregion #region 务令牌处理 string token = string.Empty; AddressHeader[] addressHeaders = new AddressHeader[] { }; if (string.IsNullOrEmpty(token) && OperationContext.Current != null) { int index = OperationContext.Current.IncomingMessageHeaders.FindHeader("token", ""); if (index >= 0) { token = OperationContext.Current.IncomingMessageHeaders.GetHeader <string>(index); } } if (string.IsNullOrEmpty(token) && WebOperationContext.Current != null) { if (WebOperationContext.Current.IncomingRequest.Headers["token"] != null) { token = WebOperationContext.Current.IncomingRequest.Headers["token"].ToString(); } } if (!string.IsNullOrEmpty(token)) { //若存在令牌,则继续添加令牌,不存在,则不管令牌 AddressHeader addressHeader1 = AddressHeader.CreateAddressHeader("token", "", token); addressHeaders = new AddressHeader[] { addressHeader1 }; } #endregion EndpointAddress endpoint = new EndpointAddress(new Uri(uri), addressHeaders); ChannelFactory <TService> channelfactory = new ChannelFactory <TService>(binding, endpoint); //返回工厂创建MaxItemsInObjectGraph foreach (OperationDescription op in channelfactory.Endpoint.Contract.Operations) { DataContractSerializerOperationBehavior dataContractBehavior = op.Behaviors.Find <DataContractSerializerOperationBehavior>() as DataContractSerializerOperationBehavior; if (dataContractBehavior != null) { dataContractBehavior.MaxItemsInObjectGraph = int.MaxValue; } } TService tservice = channelfactory.CreateChannel(); return(tservice); }
public static void Snippet5() { AddressHeader addressHeader1 = AddressHeader.CreateAddressHeader("specialservice1", "http://localhost:8000/service", 1); AddressHeader addressHeader2 = AddressHeader.CreateAddressHeader("specialservice2", "http://localhost:8000/service", 2); AddressHeader[] addressHeaders = new AddressHeader[2] { addressHeader1, addressHeader2 }; // <Snippet5> EndpointAddress endpointAddress = new EndpointAddress( new Uri("http://localhost:8003/servicemodelsamples/service/incode/identity"), addressHeaders); EndpointAddress endpointAddress2 = new EndpointAddress( new Uri("http://localhost:8003/servicemodelsamples/service/incode/identity"), addressHeaders); if (endpointAddress == endpointAddress2) { Console.WriteLine("The two endpoint addresses are equal"); } else { Console.WriteLine("The two endpoint addresses are not equal"); } // </Snippet5> }
public static void Snippetop_Inequality() { AddressHeader addressHeader1 = AddressHeader.CreateAddressHeader("specialservice1", "http://localhost:8000/service", 1); AddressHeader addressHeader2 = AddressHeader.CreateAddressHeader("specialservice2", "http://localhost:8000/service", 2); AddressHeader[] addressHeaders = new AddressHeader[2] { addressHeader1, addressHeader2 }; AddressHeaderCollection headers = new AddressHeaderCollection(addressHeaders); //<Snippet22> EndpointIdentity endpointIdentity = EndpointIdentity.CreateUpnIdentity(WindowsIdentity.GetCurrent().Name); EndpointAddress endpointAddress1 = new EndpointAddress( new Uri ("http://localhost:8003/servicemodelsamples/service/incode/identity1"), endpointIdentity, addressHeaders); EndpointAddress endpointAddress2 = new EndpointAddress( new Uri ("http://localhost:8003/servicemodelsamples/service/incode/identity2"), endpointIdentity, addressHeaders); bool op_Inequality_val = (endpointAddress1 != endpointAddress2); //</Snippet22> }
public static void SnippetReadFrom2() { AddressHeader addressHeader1 = AddressHeader.CreateAddressHeader("specialservice1", "http://localhost:8000/service", 1); AddressHeader addressHeader2 = AddressHeader.CreateAddressHeader("specialservice2", "http://localhost:8000/service", 2); AddressHeader[] addressHeaders = new AddressHeader[2] { addressHeader1, addressHeader2 }; AddressHeaderCollection headers = new AddressHeaderCollection(addressHeaders); EndpointAddress endpointAddress = new EndpointAddress( new Uri("http://localhost:8003/servicemodelsamples/service/incode/identity"), addressHeaders); XmlWriter writer = XmlWriter.Create("addressdata.xml"); XmlDictionaryWriter dictWriter = XmlDictionaryWriter.CreateDictionaryWriter(writer); endpointAddress.WriteTo(AddressingVersion.WSAddressing10, dictWriter); dictWriter.Close(); // <Snippet25> XmlReader reader = XmlReader.Create("addressdata.xml"); XmlDictionaryReader dictReader = XmlDictionaryReader.CreateDictionaryReader(reader); EndpointAddress createdEA = EndpointAddress.ReadFrom (AddressingVersion.WSAddressing10, dictReader); // </Snippet25> }
public static void Snippet3() { // Get base address from app settings in configuration Uri baseAddress = new Uri(ConfigurationManager.AppSettings["baseAddress"]); // <Snippet3> //Create new address headers for special services and add them to an array AddressHeader addressHeader1 = AddressHeader.CreateAddressHeader("specialservice1", "http://localhost:8000/service", 1); AddressHeader addressHeader2 = AddressHeader.CreateAddressHeader("specialservice2", "http://localhost:8000/service", 2); AddressHeader[] addressHeaders = new AddressHeader[2] { addressHeader1, addressHeader2 }; AddressHeaderCollection addressHeaderColl = new AddressHeaderCollection(addressHeaders); // <Snippet#15> EndpointIdentity endpointIdentity = EndpointIdentity.CreateUpnIdentity(WindowsIdentity.GetCurrent().Name); EndpointAddress endpointAddress = new EndpointAddress( new Uri("http://localhost:8003/servicemodelsamples/service/incode/identity"), endpointIdentity, addressHeaderColl); EndpointIdentity thisEndpointIdentity = endpointAddress.Identity; // </Snippet#15> // </Snippet3> }
public static void Snippet6() { AddressHeader addressHeader1 = AddressHeader.CreateAddressHeader("specialservice1", "http://localhost:8000/service", 1); AddressHeader addressHeader2 = AddressHeader.CreateAddressHeader("specialservice2", "http://localhost:8000/service", 2); AddressHeader[] addressHeaders = new AddressHeader[2] { addressHeader1, addressHeader2 }; AddressHeaderCollection headers = new AddressHeaderCollection(addressHeaders); EndpointAddress endpointAddress = new EndpointAddress( new Uri("http://localhost:8003/servicemodelsamples/service/incode/identity"), addressHeaders); // <Snippet6> // <Snippet8> XmlDictionaryReader metadataReader = endpointAddress.GetReaderAtMetadata(); // </Snippet8> // <Snippet7> XmlDictionaryReader extensionReader = endpointAddress.GetReaderAtExtensions(); // </Snippet7> EndpointIdentity identity = EndpointIdentity.CreateUpnIdentity(WindowsIdentity.GetCurrent().Name); EndpointAddress endpointAddress2 = new EndpointAddress( new Uri("http://localhost:8003/servicemodelsamples/service/incode/identity"), identity, headers, metadataReader, extensionReader); // </Snippet6> }
public SolicitudRecogidaConfirmacion SolicitudRecogida(Solicitud Sol) { SolicitudRecogidaConfirmacion confirmacion = new SolicitudRecogidaConfirmacion(); ServientregaRecogida.PickUpRequestClient Client = new ServientregaRecogida.PickUpRequestClient(); EndpointAddressBuilder endpoint = new EndpointAddressBuilder(Client.Endpoint.Address); endpoint.Headers.Add(AddressHeader.CreateAddressHeader("User", "http://tempuri.org/", ConfigurationManager.AppSettings["login"])); endpoint.Headers.Add(AddressHeader.CreateAddressHeader("Password", "http://tempuri.org/", ConfigurationManager.AppSettings["pwd"])); endpoint.Headers.Add(AddressHeader.CreateAddressHeader("CodSer", "http://tempuri.org/", ConfigurationManager.AppSettings["Id_CodFacturacion"])); Client.Endpoint.Address = endpoint.ToEndpointAddress(); string[] guias = new string[Sol.listGuias.Count()]; for (int i = 0; i < Sol.listGuias.Count(); i++) { guias[i] = Sol.listGuias[i].GuiaID; } ServientregaRecogida.ResponsePickUpRequest req = Client.CreateRequestSporadic(guias, Sol.FechaRecodiga, Sol.HoraRecogida, Sol.ReferenciaAdicional); if (req.PickUpRequestList[0].PickupRequestNumber == 0) { confirmacion.RequestID = "0"; confirmacion.MensajeRequest = "La guia no ha sido chequeada para solicitud de recodiga"; } else { confirmacion.RequestID = req.PickUpRequestList[0].PickupRequestNumber.ToString(); confirmacion.MensajeRequest = "La solicitud de programación de recogida ha sido exitosa"; } return(confirmacion); }
public static PullPointSubscriptionClient GetPullPointSubClient(string ip, int port, string toHeaderAddr, List <MessageHeader> headers) { //EndpointAddress serviceAddress = new EndpointAddress(string.Format("http://{0}:{1}/onvif/event_service", ip, port)); AddressHeader[] addrHeader; // = AddressHeader.CreateAddressHeader("Action", "http://www.w3.org/2005/08/addressing", "http://docs.oasis-open.org/wsn/bw-2/NotificationProducer/SubscribeRequest"); addrHeader = new AddressHeader[2]; addrHeader[0] = AddressHeader.CreateAddressHeader("Action", "http://www.w3.org/2005/08/addressing", "http://www.onvif.org/ver10/events/wsdl/PullPointSubscription/PullMessagesRequest"); addrHeader[1] = AddressHeader.CreateAddressHeader("To", "http://www.w3.org/2005/08/addressing", toHeaderAddr); //addrHeader[1] = AddressHeader.CreateAddressHeader("MessageID", "http://www.w3.org/2005/08/addressing", "urn:uuid:e47b9746-c5c1-455e-839f-0db5bed7d8c7"); //addrHeader[1] = AddressHeader.CreateAddressHeader("ReplyTo", "http://www.w3.org/2005/08/addressing", "http://www.w3.org/2005/08/addressing/anonymous"); //MessageHeader[] msgHeader; //msgHeader = new MessageHeader[1]; //msgHeader[0] = MessageHeader.CreateHeader("Action", "http://www.w3.org/2005/08/addressing", "http://docs.oasis-open.org/wsn/bw-2/NotificationProducer/SubscribeRequest", true); EndpointAddress serviceAddress = new EndpointAddress( new System.Uri(string.Format("http://{0}:{1}/onvif/event_service", ip, port)), addrHeader); HttpTransportBindingElement httpBinding = new HttpTransportBindingElement(); httpBinding.AuthenticationScheme = AuthenticationSchemes.Digest; var messageElement = new TextMessageEncodingBindingElement(); messageElement.MessageVersion = MessageVersion.CreateVersion(EnvelopeVersion.Soap12, AddressingVersion.None); CustomBinding bind = new CustomBinding(messageElement, httpBinding); PullPointSubscriptionClient ppsc = new PullPointSubscriptionClient(bind, serviceAddress); return(ppsc); }
internal static PaymentServicePlatformPortTypeClient GetService(string siteUrl) { var basicHttpSecurityMode = BasicHttpSecurityMode.None; if (siteUrl.StartsWith("https")) { basicHttpSecurityMode = BasicHttpSecurityMode.Transport; } System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12; Uri serviceUri = new Uri(siteUrl); AddressHeader addressHeader1 = AddressHeader.CreateAddressHeader("SOAPAction", "https://implementacion.nps.com.ar/ws.php/Authorize_3p", 1); AddressHeader[] addressHeaders1 = new AddressHeader[1] { addressHeader1 }; EndpointAddress endpointAddress = new EndpointAddress(serviceUri, addressHeaders1); //Create the binding here Binding binding = new CustomBinding(BindingFactory.CreateInstance(basicHttpSecurityMode)); PaymentServicePlatformPortTypeClient client = new PaymentServicePlatformPortTypeClient(binding, endpointAddress); client.Endpoint.Behaviors.Add(new FaultFormatingBehavior()); return(client); }
public void LoginWithAPIKey() { IBodyArchitectAccessService service = CreateServiceProxy(AddressHeader.CreateAddressHeader("APIKey", "", "EB17BC2A-94FD-4E65-8751-15730F69E7F5")); var sessionData = service.Login(ClientInformation, "test_user", "pwd".ToSHA1Hash()); Assert.IsNotNull(sessionData); }
private static EndpointAddress CreateEndpointAddress(string uri, string clientId, string clientLogDir) { return(new EndpointAddress(new Uri(uri), new AddressHeader[] { AddressHeader.CreateAddressHeader("ClientIdentification", string.Empty, clientId), AddressHeader.CreateAddressHeader("ClientLogDir", string.Empty, clientLogDir) })); }
private EndpointAddress GetEndpointAddress() { return(new EndpointAddress( new Uri(_options.ClientUrl), new DnsEndpointIdentity(_options.DnsEndpointIdentity) , AddressHeader.CreateAddressHeader(_options.HeaderKey, "", _options.HeaderValue) )); }
private static EndpointAddress ReadContents( AddressingVersion addressingVersion, XmlReader reader) { Uri uri = null; EndpointIdentity identity = null; reader.MoveToContent(); if (reader.LocalName == "Address" && reader.NamespaceURI == addressingVersion.Namespace && reader.NodeType == XmlNodeType.Element && !reader.IsEmptyElement) { uri = new Uri(reader.ReadElementContentAsString()); } else { throw new XmlException(String.Format( "Expecting 'Address' from namespace '{0}', but found '{1}' from namespace '{2}'", addressingVersion.Namespace, reader.LocalName, reader.NamespaceURI)); } reader.MoveToContent(); #if !NET_2_1 MetadataSet metadata = null; if (reader.LocalName == "Metadata" && reader.NamespaceURI == addressingVersion.Namespace && !reader.IsEmptyElement) { reader.Read(); metadata = (MetadataSet) new XmlSerializer(typeof(MetadataSet)).Deserialize(reader); reader.MoveToContent(); reader.ReadEndElement(); } reader.MoveToContent(); if (reader.LocalName == "Identity" && reader.NamespaceURI == Constants.WsaIdentityUri) { // FIXME: implement reader.Skip(); } #endif if (addressingVersion == AddressingVersion.WSAddressing10 && uri == w3c_anonymous) { uri = anonymous_role; } #if NET_2_1 return(new EndpointAddress(uri, identity)); #else if (metadata == null) { return(new EndpointAddress(uri, identity)); } return(new EndpointAddress(uri, identity, AddressHeader.CreateAddressHeader(metadata))); #endif }
private static ssrIndexSearchClient CreateSsrIndexSearchClient(string url) { var endpointAddress = new EndpointAddress( new Uri(url), AddressHeader.CreateAddressHeader("contract", "", "geonorge.Stedsnavn.ssrIndexSearch") ); return(new ssrIndexSearchClient(CreateBasicHttpBinding(), endpointAddress)); }
private EiendomByggClient CreateEiendomByggClient(string url) { var endpointAddress = new EndpointAddress( new Uri(url), AddressHeader.CreateAddressHeader("contract", "", "geonorge.EiendomBygg.EiendomBygg") ); return(new EiendomByggClient(CreateBasicHttpBinding(), endpointAddress)); }
private SokKomDataClient CreateSokKomDataClient(string url) { var endpointAddress = new EndpointAddress( new Uri(url), AddressHeader.CreateAddressHeader("contract", "", "geonorge.KommuneData.SokKomData") ); return(new SokKomDataClient(CreateBasicHttpBinding(), endpointAddress)); }
private static SSRClient CreateSsrClient(string url) { var endpointAddress = new EndpointAddress( new Uri(url), AddressHeader.CreateAddressHeader("contract", "", "geonorge.StedsRegister.SSR") ); return(new SSRClient(CreateBasicHttpBinding(), endpointAddress)); }
public void GetAddressHeaderReader() { var h = AddressHeader.CreateAddressHeader("foo", String.Empty, null); var r = h.GetAddressHeaderReader(); r.MoveToContent(); Assert.AreEqual("foo", r.LocalName, "#1"); Assert.AreEqual("true", r.GetAttribute("nil", XmlSchema.InstanceNamespace), "#2"); }
private static AdresseClient CreateAdresseClient(string url) { var endpointAddress = new EndpointAddress( new Uri(url), AddressHeader.CreateAddressHeader("contract", "", "geonorge.Adresse.Adresse") ); return(new AdresseClient(CreateBasicHttpBinding(), endpointAddress)); }
static void Main(string[] args) { // Cria um novo client e define o responsável pelo tratamento do retorno var soapClient = new ClientesCadastroSoapClient(); // Define os dados de autenticação var builder = new EndpointAddressBuilder(soapClient.Endpoint.Address); builder.Headers.Add(AddressHeader.CreateAddressHeader("app_key", "", omie_app_key)); builder.Headers.Add(AddressHeader.CreateAddressHeader("app_secret", "", omie_app_secret)); soapClient.Endpoint.Address = builder.ToEndpointAddress(); CBLog("Exemplo DotNet"); CBLog(""); CBLog(" 1 - Atualizar um cliente"); CBLog(" 2 - Listar clientes"); CBLog(""); CBLog(" Opção: ", false); var a = Console.ReadKey(); CBLog(""); CBLog(""); if (a.KeyChar == '1') { // Upsert no cadastro de cliente CBLog("Atualizando o cadastro do cliente... ", false); var cliente = new clientes_cadastro { razao_social = "Omiexperience S/A", cnpj_cpf = "18.511.742/0001-47", cidade = "SAO PAULO (SP)", estado = "SP", codigo_cliente_integracao = "444" }; // Executa a chamada soapClient.UpsertClienteCompleted += OnSoapClientOnUpsertClienteCompleted; soapClient.UpsertClienteAsync(cliente); } else if (a.KeyChar == '2') { CBLog("Listando clientes cadastrados... "); var clientes_filtro = new clientes_list_request(); clientes_filtro.apenas_importado_api = "N"; clientes_filtro.pagina = "1"; clientes_filtro.registros_por_pagina = "3"; soapClient.ListarClientesCompleted += soapClient_ListarClientesCompleted; soapClient.ListarClientesAsync(clientes_filtro); } Console.ReadKey(); }
private static TService HttpsCreate <TService>(string url, int TimeOut) { Uri uri = new Uri(url); ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult); WSHttpBinding binding = new System.ServiceModel.WSHttpBinding(); binding.SendTimeout = new TimeSpan(0, TimeOut / 60, TimeOut % 60); binding.ReceiveTimeout = new TimeSpan(0, TimeOut / 60, TimeOut % 60); #region 设置一些配置信息 binding.Security.Mode = SecurityMode.Transport; binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None; #endregion System.ServiceModel.Web.WebOperationContext ctx = System.ServiceModel.Web.WebOperationContext.Current; var token = ctx.IncomingRequest.Headers["token"].ToString(); AddressHeaderCollection addressHeaderColl; if (!string.IsNullOrEmpty(token)) { AddressHeader addressHeader1 = AddressHeader.CreateAddressHeader("token", "", token); AddressHeader[] addressHeaders = new AddressHeader[] { addressHeader1 }; addressHeaderColl = new AddressHeaderCollection(addressHeaders); } else { addressHeaderColl = new AddressHeaderCollection(); } // //string[] cers = ZH.Security.Client.CertUtil.GetHostCertificate(uri); //TODO 证书处理 string[] cers = "".Split('.'); var IdentityDns = EndpointIdentity.CreateDnsIdentity(cers[0]); // System.ServiceModel.EndpointAddress endpoint = new EndpointAddress(uri, IdentityDns, addressHeaderColl); ChannelFactory <TService> channelfactory = new ChannelFactory <TService>(binding, endpoint); foreach (OperationDescription op in channelfactory.Endpoint.Contract.Operations) { DataContractSerializerOperationBehavior dataContractBehavior = op.Behaviors.Find <DataContractSerializerOperationBehavior>() as DataContractSerializerOperationBehavior; if (dataContractBehavior != null) { dataContractBehavior.MaxItemsInObjectGraph = int.MaxValue; } } // channelfactory.Credentials.ServiceCertificate.DefaultCertificate = new X509Certificate2(Convert.FromBase64String(cers[1])); // new X509Certificate2(x509certificate); \ // //返回工厂创建 TService tservice = channelfactory.CreateChannel(); // return(tservice); }
public static void AddHeaders <T>(System.ServiceModel.ClientBase <T> client, string username, string password, string uygulamaKullaniciAdi) where T : class { EndpointAddressBuilder addressBuilder = new EndpointAddressBuilder(client.Endpoint.Address); addressBuilder.Headers.Add(AddressHeader.CreateAddressHeader("KullaniciAdi", string.Empty, username)); addressBuilder.Headers.Add(AddressHeader.CreateAddressHeader("Parola", string.Empty, password)); addressBuilder.Headers.Add(AddressHeader.CreateAddressHeader("UygulamaKullaniciAdi", string.Empty, uygulamaKullaniciAdi)); client.Endpoint.Address = addressBuilder.ToEndpointAddress(); }
public void WriteAddressHeader() { var h = AddressHeader.CreateAddressHeader("foo", "urn:foo", null); var sw = new StringWriter(); var xw = XmlDictionaryWriter.CreateDictionaryWriter(XmlWriter.Create(sw)); h.WriteAddressHeader(xw); xw.Close(); Assert.AreEqual("<?xml version=\"1.0\" encoding=\"utf-16\"?><foo i:nil=\"true\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"urn:foo\" />", sw.ToString(), "#1"); }
// It should work, but MS implementation expects body to be // IComparable. public void EqualsTest() { AddressHeader h = AddressHeader.CreateAddressHeader( "foo", "urn:foo", null); AddressHeader h2 = AddressHeader.CreateAddressHeader( "foo", "urn:foo", null); Assert.IsFalse(h.Equals(null), "#1"); // never throw nullref Assert.IsTrue(h.Equals(h2), "#2"); }
public static void Main() { // <Snippet0> // <Snippet1> // Name property AddressHeader addressHeaderWithName = AddressHeader.CreateAddressHeader("MyServiceName", "http://localhost:8000/service", 1); string addressHeaderName = addressHeaderWithName.Name; // </Snippet1> // <Snippet2> //Put snippet here. // Namespace property AddressHeader addressHeaderWithNS = AddressHeader.CreateAddressHeader("MyServiceName", "http://localhost:8000/service", 1); string addressHeaderNS = addressHeaderWithNS.Namespace; // </Snippet2> // <Snippet3> // Obsolete // </Snippet3> // <Snippet4> // Obsolete // </Snippet4> // <Snippet5> // Create address headers for special services and add them to an array AddressHeader addressHeader1 = AddressHeader.CreateAddressHeader("specialservice1", "http://localhost:8000/service", 1); AddressHeader addressHeader2 = AddressHeader.CreateAddressHeader("specialservice2", "http://localhost:8000/service", 2); AddressHeader[] addressHeaders = new AddressHeader[2] { addressHeader1, addressHeader2 }; // Endpoint address constructor with URI and address headers EndpointAddress endpointAddressWithHeaders = new EndpointAddress( new Uri("http://localhost/silverlightsamples/service1"), addressHeaders ); // Confirm adddressHeader1 is in endpointAddressWithHeaders - boolHeaders returns True. AddressHeaderCollection addressHeaderCollection = endpointAddressWithHeaders.Headers; bool boolHeaders = addressHeaderCollection.Contains(addressHeader1); // </Snippet5> // <Snippet10> // <Snippet6> //Create address headers with XmlObjectSerializer specified XmlObjectSerializer serializer = new DataContractSerializer(typeof(int)); AddressHeader addressHeaderWithObjSer = AddressHeader.CreateAddressHeader("MyServiceName", "http://localhost:8000/service", 1, serializer); int value = addressHeaderWithObjSer.GetValue <int>(); // </Snippet6> // </Snippet10> // </Snippet0> }
public EndpointAddress CreateEndpointReference(AddressHeader refParam) { if (this.baseEndpoint == null) { DiagnosticUtility.FailFast("Uninitialized base endpoint reference"); } EndpointAddressBuilder builder = new EndpointAddressBuilder(this.baseEndpoint); builder.Headers.Clear(); builder.Headers.Add(refParam); return builder.ToEndpointAddress(); }
public void Validate_Activity_ColorValidator() { IBodyArchitectAccessService service = CreateServiceProxy(AddressHeader.CreateAddressHeader("APIKey", "", "EB17BC2A-94FD-4E65-8751-15730F69E7F5")); var sessionData = service.Login(ClientInformation, "test_user", "pwd".ToSHA1Hash()); var activity = new ActivityDTO(); activity.Name = "test"; activity.Color = "wrong"; service.SaveActivity(sessionData.Token, activity); }
/// <summary> /// Gets URL upon calling which the required study data can be retrieved. /// </summary> /// <param name="studyUIDs">List of UIDs for the studies to be retrieved</param> /// <param name="endPointUrl">URL of the NBIA Data Service to query. This is NOT the Data Transfer URL!</param> /// <returns>URL that returns zip file with the studies</returns> public string retrieveStudyURL(string[] studyUIDs, string endPointUrl) { TransferServiceContextService.DataTransferDescriptor dtd; using (NCIACoreServicePortTypeClient proxy = new NCIACoreServicePortTypeClient("NCIACoreServicePortTypePort", endPointUrl)) { try { TransferServiceContextReference tras = proxy.retrieveDicomDataByStudyUIDs(studyUIDs); // new TransferServiceContextReference(); EndpointReferenceType endPoint = tras.EndpointReference; // new EndpointReferenceType(); AddressHeader[] ah = new AddressHeader[endPoint.ReferenceProperties.Any.Length]; for (int lcv = 0; lcv < ah.Length; lcv++) { XmlElement refProp = endPoint.ReferenceProperties.Any[lcv]; ah[lcv] = AddressHeader.CreateAddressHeader(refProp.LocalName, refProp.NamespaceURI, refProp.InnerText); } EndpointAddress ea = new EndpointAddress(new Uri(endPoint.Address.Value), ah); // create binding by hand so we don't have to associate a config file with a dll BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None); binding.Name = "TransferServiceContextPortTypePort"; TransferServiceContextPortTypeClient transProxy = new TransferServiceContextPortTypeClient(binding, ea); dtd = transProxy.getDataTransferDescriptor(); } catch (System.Net.WebException ex) { System.Console.WriteLine(ex.Message); //never gets here throw new GridServicerException("Error querying NCIA Grid", ex); } catch (Exception e) { System.Console.WriteLine(e.Message); //never gets here throw new GridServicerException("Error retrieving from NCIA Grid", e); } } if (string.IsNullOrEmpty(dtd.url)) return dtd.url; else return null; }
public string retrieveStudyURL(string[] studyUIDs, string endPointUrl) { TransferServiceContextService.DataTransferDescriptor dtd; try { var proxy = new NCIACoreServicePortTypeClient(); var tras = proxy.retrieveDicomDataByStudyUIDs(studyUIDs); var endPoint = tras.EndpointReference; var ah = new AddressHeader[endPoint.ReferenceProperties.Any.Length]; proxy.Endpoint.Address = new EndpointAddress(endPointUrl); for (var lcv = 0; lcv < ah.Length; lcv++) { var refProp = endPoint.ReferenceProperties.Any[lcv]; ah[lcv] = AddressHeader.CreateAddressHeader(refProp.LocalName, refProp.NamespaceURI, refProp.InnerText); } var ea = new EndpointAddress(new Uri(endPoint.Address.Value), ah); var binding = new BasicHttpBinding(BasicHttpSecurityMode.None); binding.Name = "TransferServiceContextPortTypePort"; var transProxy = new TransferServiceContextPortTypeClient(binding, ea); dtd = transProxy.getDataTransferDescriptor(); } catch (WebException ex) { Console.WriteLine(ex.Message); throw new GridServicerException("Error querying NCIA Grid", ex); } catch (Exception e) { Console.WriteLine(e.Message); throw new GridServicerException("Error retrieving from NCIA Grid", e); } if (dtd.url != null || dtd.url.Equals("")) return dtd.url; else return null; }
internal static Header Create(string name, HeaderId headerId) { if (headerId < HeaderId.Unknown || headerId > (HeaderId) MimeData.nameIndex.Length) throw new System.ArgumentException(Resources.Strings.InvalidHeaderId, nameof(headerId)); if (headerId == HeaderId.Unknown) throw new System.ArgumentException(Resources.Strings.CannotDetermineHeaderNameFromId, nameof(headerId)); Header header; switch (MimeData.headerNames[(int) MimeData.nameIndex[(int) headerId]].headerType) { case HeaderType.AsciiText: header = new AsciiTextHeader(MimeData.headerNames[(int) MimeData.nameIndex[(int) headerId]].name, headerId); break; case HeaderType.Date: header = new DateHeader(MimeData.headerNames[(int) MimeData.nameIndex[(int) headerId]].name, headerId); break; case HeaderType.Received: header = new ReceivedHeader(); break; case HeaderType.ContentType: header = new ContentTypeHeader(); break; case HeaderType.ContentDisposition: header = new ContentDispositionHeader(); break; case HeaderType.Address: header = new AddressHeader(MimeData.headerNames[(int) MimeData.nameIndex[(int) headerId]].name, headerId); break; default: header = new TextHeader(MimeData.headerNames[(int) MimeData.nameIndex[(int) headerId]].name, headerId); break; } if (!string.IsNullOrEmpty(name) && !header.MatchName(name)) throw new System.ArgumentException("name"); return header; }
public EndpointAddress CreateRegistrationService(AddressHeader refParam, ProtocolVersion protocolVersion) { switch (protocolVersion) { case ProtocolVersion.Version10: return new EndpointAddress(this.registrationServiceAddress10, refParam); case ProtocolVersion.Version11: return new EndpointAddress(this.registrationServiceAddress11, refParam); default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentException(SR.GetString(SR.InvalidWsatProtocolVersion))); } }
private void retrieveStudyUID(string[] str) { TransferServiceContextService.DataTransferDescriptor dtd =null; TransferServiceContextPortTypeClient transProxy = null; NCIACoreServicePortTypeClient proxy = null; try { proxy = new NCIACoreServicePortTypeClient(); TransferServiceContextReference tras = proxy.retrieveDicomDataByStudyUIDs(str); // new TransferServiceContextReference(); EndpointReferenceType endPoint = tras.EndpointReference; // new EndpointReferenceType(); AddressHeader[] ah = new AddressHeader[endPoint.ReferenceProperties.Any.Length]; for (int lcv = 0; lcv < ah.Length; lcv++) { XmlElement refProp = endPoint.ReferenceProperties.Any[lcv]; ah[lcv] = AddressHeader.CreateAddressHeader(refProp.LocalName, refProp.NamespaceURI, refProp.InnerText); } EndpointAddress ea = new EndpointAddress(new Uri(endPoint.Address.Value), ah); // create binding by hand so we don't have to associate a config file with a dll BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None); binding.Name = "TransferServiceContextPortTypePort"; transProxy = new TransferServiceContextPortTypeClient(binding, ea); dtd = transProxy.getDataTransferDescriptor(); } catch (System.Net.WebException ex) { System.Console.WriteLine(ex.Message); } catch (Exception e) { System.Console.WriteLine(e.Message); throw new GridServicerException("Error querying NCIA Grid", e); } if (dtd.url != null && dtd.url.Equals("")) { WebRequest wr = WebRequest.Create(dtd.url); WebResponse resp = wr.GetResponse(); byte[] buf = new byte[8192]; int read; if (transProxy != null && proxy != null) { try { Stream stream = resp.GetResponseStream(); FileStream fs = new FileStream(_directory + "/" + str[0] + ".zip", FileMode.Create, FileAccess.Write); while ((read = stream.Read(buf, 0, buf.Length)) > 0) { fs.Write(buf, 0, read); } fs.Close(); stream.Close(); resp.Close(); proxy.Close(); transProxy.Close(); } catch (IOException ioe) { throw new GridServicerException("Error writting zip file from caGrid", ioe); } } } }
public void Validate_Throws_With_Endpoint_Address_Headers() { HttpBehavior behavior = new HttpBehavior(); ServiceEndpoint endpoint = new ServiceEndpoint(ContractDescription.GetContract(typeof(CustomerService))); endpoint.Binding = new HttpBinding(); AddressHeader[] headers = new AddressHeader[] { AddressHeader.CreateAddressHeader("hello") }; endpoint.Address = new EndpointAddress(new Uri("http://somehost"), headers); ExceptionAssert.Throws<InvalidOperationException>( "Address with headers should throw", Http.SR.HttpServiceEndpointCannotHaveMessageHeaders(endpoint.Address), () => behavior.Validate(endpoint)); }
void Init(Uri uri, EndpointIdentity identity, AddressHeader[] headers) { if (headers == null || headers.Length == 0) { Init(uri, identity, (AddressHeaderCollection)null, null, -1, -1, -1); } else { Init(uri, identity, new AddressHeaderCollection(headers), null, -1, -1, -1); } }
public AddressMessageHeader (AddressHeader header) { _header = header; }
private void Init(System.Uri uri, EndpointIdentity identity, AddressHeader[] headers) { if ((headers == null) || (headers.Length == 0)) { this.Init(uri, identity, null, null, -1, -1, -1); } else { this.Init(uri, identity, new AddressHeaderCollection(headers), null, -1, -1, -1); } }