Exemplo n.º 1
0
        private static AdresseClient CreateAdresseClient(string url)
        {
            var endpointAddress = new EndpointAddress(
                new Uri(url),
                AddressHeader.CreateAddressHeader("contract", "", "geonorge.Adresse.Adresse")
                );

            return(new AdresseClient(CreateBasicHttpBinding(), endpointAddress));
        }
Exemplo n.º 2
0
        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");
        }
Exemplo n.º 3
0
        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();
        }
Exemplo n.º 4
0
        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);
        }
Exemplo n.º 5
0
        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();
        }
Exemplo n.º 6
0
        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");
        }
Exemplo n.º 7
0
        // 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");
        }
Exemplo n.º 8
0
        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>
        }
Exemplo n.º 9
0
        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);
        }
Exemplo n.º 10
0
        public void Validate_SaveScheduleEntryRangeParam_StartDayGreaterEndDay()
        {
            IBodyArchitectAccessService service = CreateServiceProxy(AddressHeader.CreateAddressHeader("APIKey", "", "EB17BC2A-94FD-4E65-8751-15730F69E7F5"));

            var sessionData = service.Login(ClientInformation, "test_user", "pwd".ToSHA1Hash());
            var param       = new SaveScheduleEntryRangeParam();

            param.StartDay = DateTime.UtcNow;
            param.EndDay   = DateTime.UtcNow.AddDays(-2);

            service.SaveScheduleEntriesRange(sessionData.Token, param);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Handles the operation of buying a selected book
        /// </summary>
        private void btnBuy_Click(object sender, EventArgs e)
        {
            // check if any book is selected for purchase
            if (lstBooks.SelectedItem == null)
            {
                MessageBox.Show("No book selected for purchase", "BookStore Client");
            }
            else
            {
                // get the selected book ID
                string selectedBookItem = lstBooks.SelectedItem.ToString();
                int    startPos         = selectedBookItem.IndexOf('.') + 1;
                int    endPos           = selectedBookItem.IndexOf(',');
                string bookName         = selectedBookItem.Substring(startPos, endPos - startPos);
                bookName = bookName.Trim();

                BuyBookClient myBuyBookClient = new BuyBookClient();

                try
                {
                    // Add the book name as a "resource" header to the endpoint address for the service
                    EndpointAddressBuilder myEndpointAddressBuilder = new EndpointAddressBuilder(myBuyBookClient.Endpoint.Address);
                    myEndpointAddressBuilder.Headers.Add(AddressHeader.CreateAddressHeader(Constants.BookNameHeaderName, Constants.BookNameHeaderNamespace, bookName));
                    myBuyBookClient.Endpoint.Address = myEndpointAddressBuilder.ToEndpointAddress();

                    // Send the request to the service. This will result in the following steps;
                    // 1. Request a security token from HomeRealmSTS authenticating using Windows credentials
                    // 2. Request a security token from BookStoreSTS authenticating using token from 1.
                    // 3. Send the BuyBook request to the BookStoreService authenticating using token from 2.
                    string response = myBuyBookClient.BuyBook("*****@*****.**", "One Microsoft Way, Redmond, WA 98052");
                    MessageBox.Show(response, "BookStore Client");

                    myBuyBookClient.Close();
                }
                catch (Exception ex)
                {
                    myBuyBookClient.Abort();

                    // see if a fault has been sent back
                    FaultException inner = GetInnerException(ex) as FaultException;
                    if (inner != null)
                    {
                        MessageFault fault = inner.CreateMessageFault();
                        MessageBox.Show(String.Format("The server sent back a fault: {0}", fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture).Text));
                    }
                    else
                    {
                        MessageBox.Show(String.Format("Exception while trying to purchase the selected book: {0}", ex), "BookStore Client");
                    }
                }
            }
        }
        /// <inheritdoc/>
        public override bool SendMessage(Message message)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            if (string.IsNullOrEmpty(Client.Address))
            {
                Logger.LogError("Error sending message to client via WEB.", $"The client '{Client.Name ?? Client.ID}' not specified address to send messages.", message);
                return(false);
            }

            ChannelFactory <ICallbackSubscriber> channelFactory;
            ICallbackSubscriber channel;

            try
            {
                var endpointAddress = new EndpointAddress(new Uri(Client.Address), AddressHeader.CreateAddressHeader("headerName", Regex.Replace(Client.Address, ".asmx$", string.Empty), "headerValue"));
                channelFactory = new ChannelFactory <ICallbackSubscriber>(new BasicHttpBinding(), endpointAddress);
                channel        = channelFactory.CreateChannel();
                ((IClientChannel)channel).Open();
            }
            catch (Exception exception)
            {
                Logger.LogUnhandledException(exception, message);
                throw exception;
            }

            var sbMessage = new MessageFromESB()
            {
                MessageFormingTime = message.ReceivingTime,
                MessageTypeID      = message.MessageType.ID,
                Body       = message.Body,
                Attachment = message.BinaryAttachment,
                SenderName = message.Sender,
                GroupID    = message.Group,
                Tags       = ServiceHelper.GetTagDictionary(message),
            };

            return(ServiceHelper.TryWithExceptionLogging(
                       () => channel.AcceptMessage(sbMessage),
                       () =>
            {
                ((IClientChannel)channel).Close();
                channelFactory.Close();
            },
                       $"Error sending message to the client '{Client.Name ?? Client.ID}' via WEB at address '{Client.Address}'.",
                       Client,
                       message,
                       Logger));
        }
Exemplo n.º 13
0
        public void Validate_SaveCustomer_NullEmail()
        {
            IBodyArchitectAccessService service = CreateServiceProxy(AddressHeader.CreateAddressHeader("APIKey", "", "EB17BC2A-94FD-4E65-8751-15730F69E7F5"));

            var sessionData = service.Login(ClientInformation, "test_user", "pwd".ToSHA1Hash());
            var customerDto = new CustomerDTO();

            customerDto.Gender    = Gender.Male;
            customerDto.FirstName = "name";
            customerDto.Birthday  = DateTime.UtcNow.AddYears(-20);

            service.SaveCustomer(sessionData.Token, customerDto);
        }
Exemplo n.º 14
0
        public Service(string baseUrl, string apiKey)
        {
            // Gets "FileManager" out of "IFileManagerService"
            var name    = typeof(T).Name.Substring(1).Replace("Service", "");
            var url     = baseUrl + "/" + name.ToLowerInvariant() + "/" + name + "Service";
            var binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
            // memoQ server requires "ApiKey" HTTP header for caller authentication
            var header  = AddressHeader.CreateAddressHeader("ApiKey", "", apiKey);
            var address = new EndpointAddress(new Uri(url), header);

            factory = new ChannelFactory <T>(binding, address);
            proxy   = factory.CreateChannel();
        }
Exemplo n.º 15
0
        public void CycleDefinition_WithoutWeeks()
        {
            var definition = new SupplementCycleDefinitionDTO();

            definition.Name     = "test";
            definition.Language = "en";

            IBodyArchitectAccessService service = CreateServiceProxy(AddressHeader.CreateAddressHeader("APIKey", "", "EB17BC2A-94FD-4E65-8751-15730F69E7F5"));

            var sessionData = service.Login(ClientInformation, "test_user", "pwd".ToSHA1Hash());

            service.SaveSupplementsCycleDefinition(sessionData.Token, definition);
        }
Exemplo n.º 16
0
        static void Main(string[] args)
        {
            Uri             uri     = new Uri("http://localhost:9876/calculatorservice");
            var             header  = AddressHeader.CreateAddressHeader("UserName", "http://localhost:9876", "jqin");
            EndpointAddress address = new EndpointAddress(uri, header);

            using (var client = new ServiceReference1.CalculatorServiceClient(new WSHttpBinding(), address))
            {
                double result = client.Add(1D, 2D);
                Console.WriteLine(result);
                Console.ReadKey();
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// Initializes the notification service client.
        /// </summary>
        private void InitializeClient(string addressText)
        {
            IPAddress ipAddress;

            if (!IPAddress.TryParse(addressText, out ipAddress))
            {
                Messages.Text += "Invalid Machine Address entered.";
                return;
            }
            var callbackClass = new NotificationServiceCallback();

            callbackClass.NotificationReceived += OnNotificationReceived;
            var notificationServiceBinding = new NetTcpBinding(SecurityMode.Message);

            notificationServiceBinding.ReceiveTimeout = TimeSpan.FromSeconds(10);
            notificationServiceBinding.SendTimeout    = TimeSpan.FromSeconds(10);

            AddressHeader          header  = AddressHeader.CreateAddressHeader("machine-connect", "hurco.com", "machine-connect");
            EndpointAddressBuilder builder = new EndpointAddressBuilder(new EndpointAddress("net.tcp://" + ipAddress + "/NotificationService"));

            builder.Headers.Add(header);
            builder.Identity = EndpointIdentity.CreateDnsIdentity("machine-connect.hurco.com");

            notificationServiceClient = new NotificationServiceClient(new InstanceContext(callbackClass), notificationServiceBinding, builder.ToEndpointAddress()); //create local service

            ab = false;
            if (notificationServiceClient.ClientCredentials == null)
            {
                Messages.Text += "Invalid client. Please try again.";
                return;
            }

            ////turn on security
            notificationServiceBinding.Security.Mode = SecurityMode.Message;
            notificationServiceBinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
            ///turn on security


            notificationServiceClient.ClientCredentials.UserName.UserName = "******"; // your VendorID (1234)
            notificationServiceClient.ClientCredentials.UserName.Password = "******";
            HeartbeatTimer = new Timer(PingWinmax, null, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1));
            try
            {
                notificationServiceClient.Open();
            }
            catch (Exception e)
            {
                Messages.Text += "Failed to Connect:\n" + e.Message + "\n" + e.StackTrace;
            }
        }
Exemplo n.º 18
0
        //</snippet17>

        // Create EndpointAddress from Uri and Context
        static public EndpointAddress CreateEndpointAddress(string uri, IDictionary <XmlQualifiedName, string> context)
        {
            EndpointAddress epr = null;

            if (context != null && context.Count > 0)
            {
                AddressHeader contextHeader = AddressHeader.CreateAddressHeader(contextHeaderName, contextHeaderNamespace, new Dictionary <XmlQualifiedName, string>(context));
                epr = new EndpointAddress(new Uri(uri), contextHeader);
            }
            else
            {
                epr = new EndpointAddress(uri);
            }
            return(epr);
        }
Exemplo n.º 19
0
        public virtual EndpointAddress setDadosAutenticacao(EndpointAddress Adress)
        {
            EndpointAddressBuilder builder = new EndpointAddressBuilder(Adress);

            string app_key    = Parametro.GetParametro("app_key");
            string app_secret = Parametro.GetParametro("app_secret");

            builder.Headers.Add(AddressHeader.CreateAddressHeader("app_key", "", app_key));       // Coloque aqui a sua KEY de acesso
            builder.Headers.Add(AddressHeader.CreateAddressHeader("app_secret", "", app_secret)); // Coloque aqui a SECRET de acesso

            //builder.Headers.Add(AddressHeader.CreateAddressHeader("app_key", "", "1142656109")); // Coloque aqui a sua KEY de acesso
            //builder.Headers.Add(AddressHeader.CreateAddressHeader("app_secret", "", "66b2a456a2c92eaf9646bc95587d47f0")); // Coloque aqui a SECRET de acesso

            return(builder.ToEndpointAddress());
        }
Exemplo n.º 20
0
        private void SetHeaders(string headerValue, bool closeExisting)
        {
            if (closeExisting)
            {
                client.Close();
                client = new Proxy.Client();
            }

            var headers = new AddressHeader[]
            {
                AddressHeader.CreateAddressHeader("x-accesstoken", "", headerValue)
            };

            client.Endpoint.Address = new System.ServiceModel.EndpointAddress(client.Endpoint.Address.Uri, headers);
        }
Exemplo n.º 21
0
        public static void SetupClientBase <T>(System.ServiceModel.ClientBase <T> client, HttpContext httpContext) where T : class
        {
            var guid        = LoggingHelper.GetInstanceGUID(httpContext, () => new Guid()).GetValueOrDefault();
            var sessionGUID = LoggingHelper.GetSessionGUID(httpContext, httpContext?.Handler as Page, () => new Guid()).GetValueOrDefault();
            var pageGUID    = LoggingHelper.GetPageGUID(httpContext, httpContext?.Handler as Page, () => new Guid()).GetValueOrDefault();
            var bundleGUID  = LoggingHelper.GetBundleGUID(httpContext, () => new Guid()).GetValueOrDefault();

            var newLogElement = new LogElementDTO(
                guid: guid,
                sessionGUID: sessionGUID,
                pageGUID: pageGUID,
                bundleGUID: bundleGUID,
                progressGUID: null,
                unixTimestamp: TimeHelper.UnixTimestamp(),
                logType: LogType.OnSetup,
                element: $"SetupClientBase_{client.Endpoint.Address.Uri}", //LoggingHelper.StripUrlForLRAP(context.Request.RawUrl),
                element2: null,
                value: "",                                                 //SerializationHelper.Serialize(requestParams, SerializationType.Json),
                times: 1,
                unixTimestampEnd: null,
                instanceTime: DateTime.Now,
                stackTrace: null
                );

            var eab = new EndpointAddressBuilder(client.Endpoint.Address);

            eab.Headers.Add(AddressHeader.CreateAddressHeader(Consts.GUIDTag,
                                                              string.Empty,
                                                              guid.ToString()));

            eab.Headers.Add(AddressHeader.CreateAddressHeader(Consts.SessionGUIDTag,
                                                              string.Empty,
                                                              sessionGUID.ToString()));

            eab.Headers.Add(AddressHeader.CreateAddressHeader(Consts.PageGUIDTag,
                                                              string.Empty,
                                                              pageGUID.ToString()));

            eab.Headers.Add(AddressHeader.CreateAddressHeader(Consts.BundleGUIDTag,
                                                              string.Empty,
                                                              bundleGUID.ToString()));

            eab.Headers.Add(AddressHeader.CreateAddressHeader(Consts.ServerGUIDTag,
                                                              string.Empty,
                                                              LoggingHelper.GetServerGUID(httpContext, () => new Guid()).GetValueOrDefault().ToString()));

            client.Endpoint.Address = eab.ToEndpointAddress();
        }
Exemplo n.º 22
0
        public void Validate_SaveScheduleEntryRangeParam_ActivityIdIsNull()
        {
            IBodyArchitectAccessService service = CreateServiceProxy(AddressHeader.CreateAddressHeader("APIKey", "", "EB17BC2A-94FD-4E65-8751-15730F69E7F5"));

            var sessionData = service.Login(ClientInformation, "test_user", "pwd".ToSHA1Hash());
            var param       = new SaveScheduleEntryRangeParam();

            param.StartDay = DateTime.UtcNow;
            param.EndDay   = DateTime.UtcNow.AddDays(2);
            var dto = new ScheduleEntryDTO();

            dto.StartTime = param.StartDay;
            dto.EndTime   = dto.StartTime + TimeSpan.FromHours(1);
            param.Entries.Add(dto);
            service.SaveScheduleEntriesRange(sessionData.Token, param);
        }
Exemplo n.º 23
0
        static void Main(string[] args)
        {
            // <Snippet0>
            // <Snippet3>
            // <Snippet1>
            EndpointAddressBuilder eab = new EndpointAddressBuilder();

            // </Snippet1>
            eab.Uri = new Uri("http://localhost/Uri");
            eab.Headers.Add(AddressHeader.CreateAddressHeader("n", "ns", "val"));
            // </Snippet3>

            // <Snippet4>
            eab.Identity = EndpointIdentity.CreateUpnIdentity("identity");
            // </Snippet4>

            // <Snippet5>
            XmlDictionaryReader xdrExtensions = eab.GetReaderAtExtensions();
            // </Snippet5>

            // <Snippet6>
            StringReader sr = new StringReader(@"<myExtension xmlns=""myExtNs"" />");

            eab.SetExtensionReader(XmlDictionaryReader.CreateDictionaryReader(XmlReader.Create(sr)));
            // </Snippet6>

            // <Snippet7>
            EndpointAddress ea = eab.ToEndpointAddress();

            // </Snippet7>

            // <Snippet8>
            sr = new StringReader(@"<myMetadata xmlns=""myMetaNs"" />");
            XmlDictionaryReader xdrMetaData = eab.GetReaderAtMetadata();

            // </Snippet8>

            // <Snippet9>
            eab.SetMetadataReader(XmlDictionaryReader.CreateDictionaryReader(XmlReader.Create(sr)));
            // </Snippet9>
            // </Snippet0>

            // <Snippet2>
            EndpointAddress        endpointAddress = new EndpointAddress("http://localhost/uri2");
            EndpointAddressBuilder eab2            = new EndpointAddressBuilder(endpointAddress);
            // </Snippet2>
        }
Exemplo n.º 24
0
 static void Main(string[] args)
 {
     using (ChannelFactory <ICalculator> channelFactory = new ChannelFactory <ICalculator>("calculatorservice"))
     {
         ICalculator calculator = channelFactory.CreateChannel();
         using (OperationContextScope contextScope = new OperationContextScope(calculator as IClientChannel))
         {
             string        sn            = "{DDA095DA-93CA-49EF-BE01-EF5B47179FD0}";
             string        ns            = "http://www.artech.com/";
             AddressHeader addressHeader = AddressHeader.CreateAddressHeader("sn", ns, sn);
             MessageHeader messageHeader = addressHeader.ToMessageHeader();
             OperationContext.Current.OutgoingMessageHeaders.Add(messageHeader);
             Console.WriteLine("x + y = {2} when x = {0} and y = {1}", 1, 2, calculator.Add(1, 2));
         }
     }
     Console.Read();
 }
Exemplo n.º 25
0
        public static void SnippetReadFromVersionToString()
        {
            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);

            // <Snippet27>
            string URIstring = endpointAddress.ToString();
            // </Snippet27>
        }
Exemplo n.º 26
0
        private static EndpointAddress ReadFrom(System.ServiceModel.Channels.AddressingVersion addressingVersion, XmlReader xreader)
        {
            string           xml      = xreader.ReadOuterXml();
            StringReader     sreader  = new StringReader(xml);
            XmlReader        reader   = XmlReader.Create(sreader);
            Uri              uri      = null;
            EndpointIdentity identity = null;

            reader.MoveToContent();
            List <AddressHeader> header = new List <AddressHeader> ();

            while (reader.NodeType == XmlNodeType.Element && !reader.IsEmptyElement)
            {
                if (reader.LocalName == "EndpointReference")
                {
                    reader.Read();
                }
                else if (reader.LocalName == "Address" &&
                         reader.NodeType == XmlNodeType.Element &&
                         !reader.IsEmptyElement)
                {
                    uri = new Uri(reader.ReadElementContentAsString());
                }
                else if (reader.LocalName == "Identity" &&
                         reader.NodeType == XmlNodeType.Element &&
                         !reader.IsEmptyElement)
                {
                    //How can key re-empact Identity
                    identity = new X509CertificateEndpointIdentity(new System.Security.Cryptography.X509Certificates.X509Certificate2("powershell.pfx", "mono"));
                    break;
                }
                else
                {
                    var headerName      = reader.LocalName;
                    var headerNamespace = reader.NamespaceURI;
                    reader.MoveToContent();
                    reader.ReadStartElement();
                    var obj = reader.ReadElementContentAs(GetTypeFromLocalName(reader.LocalName), new XmlNamespaceManager(reader.NameTable));
                    header.Add(AddressHeader.CreateAddressHeader(headerName, headerNamespace, obj));
                    reader.MoveToContent();
                    reader.ReadEndElement();
                }
            }
            return(identity == null ? new EndpointAddress(uri, header.ToArray()) : new EndpointAddress(uri, identity, header.ToArray()));
        }
Exemplo n.º 27
0
        public void WriteAddressHeaderTest()
        {
            AddressHeader h = AddressHeader.CreateAddressHeader(1);

            StringWriter      sw = new StringWriter();
            XmlWriterSettings s  = new XmlWriterSettings();

            s.OmitXmlDeclaration = true;
            XmlWriter w = XmlWriter.Create(sw, s);

            h.WriteAddressHeader(w);

            w.Close();

            Assert.AreEqual(
                @"<int xmlns=""http://schemas.microsoft.com/2003/10/Serialization/"">1</int>",
                sw.ToString());
        }
Exemplo n.º 28
0
        static void WithHeader()
        {
            AddressHeader   header  = AddressHeader.CreateAddressHeader("UserType", "http://www.aaa.com", "Licensed User");
            EndpointAddress address = new EndpointAddress(new Uri("http://127.0.0.1:23232/myservices/calculatorservice"), header);
            //EndpointAddress address = new EndpointAddress(new Uri("http://127.0.0.1:23232/myservices/calculatorservice"));
            Binding             httpBinding = new WS2007HttpBinding();
            ContractDescription contract    = ContractDescription.GetContract(typeof(ICalculator));
            ServiceEndpoint     endPoint    = new ServiceEndpoint(contract, httpBinding, address);

            using (ChannelFactory <ICalculator> channelFactory = new ChannelFactory <ICalculator>(endPoint))
            {
                ICalculator proxy = channelFactory.CreateChannel();
                Console.WriteLine("x + y = {2} when x = {0} and y = {1}", 1, 2, proxy.Add(1, 2));
                Console.WriteLine("x - y = {2} when x = {0} and y = {1}", 1, 2, proxy.Substract(1, 2));
                Console.WriteLine("x * y = {2} when x = {0} and y = {1}", 1, 2, proxy.Multiply(1, 2));
                Console.WriteLine("x / y = {2} when x = {0} and y = {1}", 1, 2, proxy.Divide(1, 2));
            }
        }
Exemplo n.º 29
0
        public static void Snippet4()
        {
            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
            };

            EndpointIdentity endpointIdentity = EndpointIdentity.CreateUpnIdentity(WindowsIdentity.GetCurrent().Name);
            EndpointAddress  endpointAddress  = new EndpointAddress(
                new Uri("http://localhost:8003/servicemodelsamples/service/incode/identity"), endpointIdentity, addressHeaders);
            // <Snippet4>
            Message msg = Message.CreateMessage(MessageVersion.Soap11, "urn:action");

            endpointAddress.ApplyTo(msg);
            // </Snippet4>
        }
        /// <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);
            }
        }