Example #1
0
        /// <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());
        }
Example #2
0
        // Given an EPR, replaces its URI with the specified IP address
        public static EndpointAddress GetIPEndpointAddress(EndpointAddress epr, IPAddress address)
        {
            EndpointAddressBuilder eprBuilder = new EndpointAddressBuilder(epr);

            eprBuilder.Uri = GetIPUri(epr.Uri, address);
            return(eprBuilder.ToEndpointAddress());
        }
Example #3
0
        public IappServiceClient IniciaNuevoCliente(string _Key)
        {
            decimal _porcentajeExcesoCorto;
            string  UriServicio;

            UriServicio     = ConfigurationManager.AppSettings["UriServicio"];
            OcultaErrorReal = ConfigurationManager.AppSettings["OcultaErrorReal"].Equals("1") ? true : false;

            decimal.TryParse(ConfigurationManager.AppSettings["PorcentajeExcesoCorto"], out _porcentajeExcesoCorto);
            PorcentajeExcesoCorto   = _porcentajeExcesoCorto / 100;
            CalidadesTipoArtExcluir = ConfigurationManager.AppSettings["CalidadesTipoExcluir"] as string;
            DefaultOrigenPartido    = ConfigurationManager.AppSettings["DefaultOrigenPartido"] as string;
            IappServiceClient cliente = new IappServiceClient();

            cliente.Endpoint.Address = new System.ServiceModel.EndpointAddress(new Uri(UriServicio), cliente.Endpoint.Address.Identity, cliente.Endpoint.Address.Headers);
            EndpointAddressBuilder builder = new EndpointAddressBuilder(cliente.Endpoint.Address);
            AddressHeader          header  = AddressHeader.CreateAddressHeader("Token", "", _Key);

            builder.Headers.Add(header);
            cliente.Endpoint.Address = builder.ToEndpointAddress();
            var mensajeBehavior = new InspectorBehavior(Usuario, "", _Key);

            cliente.Endpoint.Behaviors.Add(mensajeBehavior);

            return(cliente);
        }
Example #4
0
        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);
        }
Example #5
0
        public void GetListenAddressAndContext(out EndpointAddress listenAddress, out IDictionary <string, string> context)
        {
            // we expect the callback address to be already set when this is called
            if (this.CallbackAddress == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("callbackaddress");
            }
            EndpointAddressBuilder builder       = new EndpointAddressBuilder(this.CallbackAddress);
            AddressHeader          contextHeader = null;
            int contextHeaderIndex = -1;

            for (int i = 0; i < builder.Headers.Count; ++i)
            {
                if (builder.Headers[i].Name == ContextMessageHeader.ContextHeaderName && builder.Headers[i].Namespace == ContextMessageHeader.ContextHeaderNamespace)
                {
                    if (contextHeader != null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(SR.GetString(SR.MultipleContextHeadersFoundInCallbackAddress)));
                    }
                    contextHeader      = builder.Headers[i];
                    contextHeaderIndex = i;
                }
            }
            if (contextHeader != null)
            {
                builder.Headers.RemoveAt(contextHeaderIndex);
            }
            context       = (contextHeader != null) ? ContextMessageHeader.ParseContextHeader(contextHeader.GetAddressHeaderReader()).Context : null;
            listenAddress = builder.ToEndpointAddress();
        }
Example #6
0
        EndpointDispatcher(EndpointDispatcher baseEndpoint, IEnumerable <AddressHeader> headers)
        {
            EndpointAddressBuilder builder = new EndpointAddressBuilder(baseEndpoint.EndpointAddress);

            foreach (AddressHeader h in headers)
            {
                builder.Headers.Add(h);
            }
            EndpointAddress address = builder.ToEndpointAddress();

            addressFilter = new EndpointAddressMessageFilter(address);
            // channelDispatcher is Attached
            contractFilter    = baseEndpoint.ContractFilter;
            contractName      = baseEndpoint.ContractName;
            contractNamespace = baseEndpoint.ContractNamespace;
            dispatchRuntime   = baseEndpoint.DispatchRuntime;
            // endpointFilter is lazy
            filterPriority  = baseEndpoint.FilterPriority + 1;
            originalAddress = address;
            //if (PerformanceCounters.PerformanceCountersEnabled)
            //{
            //    this.perfCounterId = baseEndpoint.perfCounterId;
            //    this.perfCounterBaseId = baseEndpoint.perfCounterBaseId;
            //}
            id = baseEndpoint.id;
        }
Example #7
0
        public void GetListenAddressAndContext(out EndpointAddress listenAddress, out IDictionary <string, string> context)
        {
            if (this.CallbackAddress == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("callbackaddress");
            }
            EndpointAddressBuilder builder = new EndpointAddressBuilder(this.CallbackAddress);
            AddressHeader          header  = null;
            int index = -1;

            for (int i = 0; i < builder.Headers.Count; i++)
            {
                if ((builder.Headers[i].Name == "Context") && (builder.Headers[i].Namespace == "http://schemas.microsoft.com/ws/2006/05/context"))
                {
                    if (header != null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(System.ServiceModel.SR.GetString("MultipleContextHeadersFoundInCallbackAddress")));
                    }
                    header = builder.Headers[i];
                    index  = i;
                }
            }
            if (header != null)
            {
                builder.Headers.RemoveAt(index);
            }
            context       = (header != null) ? ContextMessageHeader.ParseContextHeader(header.GetAddressHeaderReader()).Context : null;
            listenAddress = builder.ToEndpointAddress();
        }
 public SubscriptionManager(EndpointAddressBuilder existingAddressBuilder, string identifier, Uri toUri, string deliveryResourceUri)
 {
     existingAddressBuilder.Uri = toUri;
     existingAddressBuilder.Headers.Add(new IdentifierHeader(identifier));
     existingAddressBuilder.Headers.Add(new ResourceUriHeader(deliveryResourceUri));
     _address = existingAddressBuilder.ToEndpointAddress();
 }
Example #9
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();
        }
Example #10
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();
        }
Example #11
0
        private static void SetEndpointAddress(ServiceEndpoint endpoint, string remoteAddress)
        {
            // change the endpoint address and preserve the identity certificate defined in the config file
            EndpointAddressBuilder endpointAddressBuilder = new EndpointAddressBuilder(endpoint.Address);
            UriBuilder             uriBuilder             = new UriBuilder(endpointAddressBuilder.Uri);

            uriBuilder.Host            = remoteAddress;
            endpointAddressBuilder.Uri = uriBuilder.Uri;
            endpoint.Address           = endpointAddressBuilder.ToEndpointAddress();
        }
Example #12
0
        public ClientContext(Uri endpointUri, AddressingVersion addressingVersion, IChannelFactory <T> proxyFactory, AddressHeaderCreatorDelegate addressHeaderCreatorDelegate)
        {
            var builder = new EndpointAddressBuilder();

            addressHeaderCreatorDelegate(builder.Headers);
            builder.Uri = endpointUri;

            _channel = proxyFactory.CreateChannel(builder.ToEndpointAddress());
            _scope   = new OperationContextScope((IContextChannel)_channel);
            AddressingVersionExtension.Activate(addressingVersion);
        }
Example #13
0
        public static EndpointAddress ToEndointAddress(ManagementBaseObject obj, bool isLocal)
        {
            EndpointAddressBuilder builder = new EndpointAddressBuilder();

            builder.Identity = new X509CertificateEndpointIdentity(new X509Certificate2("powershell.pfx", "mono"));
            foreach (var header in GetAddressHeaders(obj, isLocal))
            {
                builder.Headers.Add(header);
            }
            builder.Uri = new Uri(CimNamespaces.CimNamespace + "/" + obj.ClassPath.ClassName);
            return(builder.ToEndpointAddress());
        }
Example #14
0
        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());
        }
        /// <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");
                    }
                }
            }
        }
Example #16
0
        private static EndpointAddress CreateCallbackAddress(EndpointAddress listenAddress, IDictionary <string, string> context)
        {
            if (listenAddress == null)
            {
                return(null);
            }
            EndpointAddressBuilder builder = new EndpointAddressBuilder(listenAddress);

            if (context != null)
            {
                builder.Headers.Add(new ContextAddressHeader(context));
            }
            return(builder.ToEndpointAddress());
        }
Example #17
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());
        }
Example #18
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();
        }
Example #19
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>
        }
Example #20
0
        public ClientContext(Uri endpointUri, AddressingVersion addressingVersion, IChannelFactory <T> proxyFactory, AddressHeaderCreatorDelegate addressHeaderCreatorDelegate)
        {
            EndpointAddressBuilder builder = new EndpointAddressBuilder();

            addressHeaderCreatorDelegate(builder.Headers);
            builder.Identity = new X509CertificateEndpointIdentity(new X509Certificate2("powershell.pfx", "mono"));
            builder.Uri      = endpointUri;
            var endpoint  = builder.ToEndpointAddress();
            var realProxy = proxyFactory as ChannelFactory <T>;

            if (!realProxy.Endpoint.Behaviors.Contains(typeof(OperationContextBehavior)))
            {
                realProxy.Endpoint.Behaviors.Add(new OperationContextBehavior());
            }
            _channel = proxyFactory.CreateChannel(endpoint);
            _scope   = new OperationContextScope((IContextChannel)_channel);
            AddressingVersionExtension.Activate(addressingVersion);
            endpoint.Headers.WriteAddressHeaders();
        }
Example #21
0
        public IappServiceClient IniciaNuevoCliente()
        {
            string UriServicio;

            UriServicio = ConfigurationManager.AppSettings["UriServicioPedNac"];
            //26062018
            decimal _porcentajeExcesoCorto;

            //OcultaErrorReal = ConfigurationManager.AppSettings["OcultaErrorReal"].Equals("1") ? true : false;

            //decimal.TryParse(ConfigurationManager.AppSettings["PorcentajeExcesoCorto"], out _porcentajeExcesoCorto);
            //PorcentajeExcesoCorto = _porcentajeExcesoCorto / 100;
            //CalidadesTipoArtExcluir = ConfigurationManager.AppSettings["CalidadesTipoExcluir"] as string;
            //DefaultOrigenPartido = ConfigurationManager.AppSettings["DefaultOrigenPartido"] as string;

            //IappServiceClient cliente = new IappServiceClient();
            //cliente.Endpoint.Address = new System.ServiceModel.EndpointAddress(new Uri(UriServicio), cliente.Endpoint.Address.Identity, cliente.Endpoint.Address.Headers);
            //return cliente;

            IappServiceClient cliente = new IappServiceClient();

            cliente.Endpoint.Address = new System.ServiceModel.EndpointAddress(new Uri(UriServicio), cliente.Endpoint.Address.Identity, cliente.Endpoint.Address.Headers);

            //if (HttpContext.Current == null || HttpContext.Current.Session["Token"] == null || HttpContext.Current.Session["Token"].ToString().Trim() == string.Empty)
            //{
            //    HttpContext.Current.Session["Token"] = Security ?? "";
            //}
            EndpointAddressBuilder builder = new EndpointAddressBuilder(cliente.Endpoint.Address);
            AddressHeader          header  = AddressHeader.CreateAddressHeader("Token", "", appfe.Token.security);

            builder.Headers.Add(header);
            cliente.Endpoint.Address = builder.ToEndpointAddress();
            var mensajeBehavior = new InspectorBehavior(Usuario, "", appfe.Token.security ?? "");

            cliente.Endpoint.Behaviors.Add(mensajeBehavior);

            return(cliente);
        }
Example #22
0
        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;
        }
Example #23
0
        static void Main()
        {
            // Create a client.
            HelloClient client = new HelloClient();

            // Add a reference-parameter header to the address.
            // Since the EndpointAddress class is immutable, we must use
            // EndpointAddressBuilder to change the value.
            EndpointAddressBuilder builder = new EndpointAddressBuilder(client.Endpoint.Address);
            AddressHeader          header  = AddressHeader.CreateAddressHeader(IDName, IDNamespace, "John");

            builder.Headers.Add(header);
            client.Endpoint.Address = builder.ToEndpointAddress();

            // Call the Hello service operation.
            Console.WriteLine(client.Hello());

            //Closing the client gracefully closes the connection and cleans up resources
            client.Close();

            Console.WriteLine();
            Console.WriteLine("Press <ENTER> to terminate client.");
            Console.ReadLine();
        }
Example #24
0
        public XmlDocument CreateInformationCardXML(InformationCard card)
        {
            MemoryStream stream = new MemoryStream();
            XmlWriter    writer = XmlWriter.Create(stream);

            writer.WriteStartElement("InformationCard", "http://schemas.xmlsoap.org/ws/2005/05/identity");


            writer.WriteAttributeString("lang", "http://www.w3.org/XML/1998/namespace", "en-US");
            writer.WriteStartElement("InformationCardReference", "http://schemas.xmlsoap.org/ws/2005/05/identity");
            writer.WriteElementString("CardId", "http://schemas.xmlsoap.org/ws/2005/05/identity", card.CardReference.CardID);
            writer.WriteElementString("CardVersion", "http://schemas.xmlsoap.org/ws/2005/05/identity", card.CardReference.CardVersion.ToString());
            writer.WriteEndElement();

            if (card.CardName != null && card.CardName.Length > 0)
            {
                writer.WriteStartElement("CardName", "http://schemas.xmlsoap.org/ws/2005/05/identity");
                writer.WriteString(card.CardName);
                writer.WriteEndElement();
            }



            if (card.CardImage != null && card.CardImage.ImageName.Length > 0)
            {
                writer.WriteStartElement("CardImage", "http://schemas.xmlsoap.org/ws/2005/05/identity");
                if (card.CardImage != null && card.CardImage.ImageMimeType != null && card.CardImage.ImageMimeType.Length > 0)
                {
                    writer.WriteAttributeString("MimeType", card.CardImage.ImageMimeType);
                }

                FileInfo cardImage = new FileInfo(card.CardImage.ImageName);
                if (cardImage.Exists)
                {
                    byte[] cardImageBytes = new byte[cardImage.Length];
                    using (FileStream imageFS = cardImage.OpenRead())
                    {
                        imageFS.Read(cardImageBytes, 0, cardImageBytes.Length);
                    }


                    string imageBase64 = Convert.ToBase64String(cardImageBytes);
                    writer.WriteString(imageBase64);
                    writer.WriteEndElement();
                }
            }


            writer.WriteStartElement("Issuer", "http://schemas.xmlsoap.org/ws/2005/05/identity");
            writer.WriteString(card.Issuer);
            writer.WriteEndElement();

            //writer.WriteStartElement("IssuerName", "http://schemas.xmlsoap.org/ws/2005/05/identity");
            //writer.WriteString(card.IssuerName);
            //writer.WriteEndElement();

            writer.WriteStartElement("TimeIssued", "http://schemas.xmlsoap.org/ws/2005/05/identity");
            writer.WriteString(XmlConvert.ToString(card.TimeIssued, XmlDateTimeSerializationMode.Utc));
            writer.WriteEndElement();


            writer.WriteStartElement("TimeExpires", "http://schemas.xmlsoap.org/ws/2005/05/identity");
            writer.WriteString(XmlConvert.ToString(card.TimeExpires, XmlDateTimeSerializationMode.Utc));
            writer.WriteEndElement();


            writer.WriteStartElement("TokenServiceList", "http://schemas.xmlsoap.org/ws/2005/05/identity");


            foreach (TokenService ts in card.TokenServiceList)
            {
                EndpointAddressBuilder endpointBuilder = new EndpointAddressBuilder();

                endpointBuilder.Uri = new Uri(ts.EndpointReference.Address);

                endpointBuilder.Identity = new X509CertificateEndpointIdentity(RetrieveCertificate(ts.EndpointReference.Identity));

                if (null != ts.EndpointReference.Mex)
                {
                    MetadataReference mexReference = new MetadataReference();
                    mexReference.Address        = new EndpointAddress(ts.EndpointReference.Mex);
                    mexReference.AddressVersion = AddressingVersion.WSAddressing10;

                    MetadataSection mexSection = new MetadataSection();
                    mexSection.Metadata = mexReference;

                    MetadataSet mexSet = new MetadataSet();
                    mexSet.MetadataSections.Add(mexSection);


                    MemoryStream mexMemoryStream = new MemoryStream();

                    XmlTextWriter mexWriter = new XmlTextWriter(mexMemoryStream, System.Text.Encoding.UTF8);

                    mexSet.WriteTo(mexWriter);

                    mexWriter.Flush();

                    mexMemoryStream.Seek(0, SeekOrigin.Begin);

                    XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(mexMemoryStream, XmlDictionaryReaderQuotas.Max);

                    endpointBuilder.SetMetadataReader(reader);


                    writer.WriteStartElement("TokenService", "http://schemas.xmlsoap.org/ws/2005/05/identity");
                    EndpointAddress endpoint = endpointBuilder.ToEndpointAddress();
                    endpoint.WriteTo(AddressingVersion.WSAddressing10, writer);

                    writer.WriteStartElement("UserCredential", "http://schemas.xmlsoap.org/ws/2005/05/identity");


                    if (ts.UserCredential.DisplayCredentialHint != null && ts.UserCredential.DisplayCredentialHint.Length > 0)
                    {
                        writer.WriteStartElement("DisplayCredentialHint", "http://schemas.xmlsoap.org/ws/2005/05/identity");


                        if (ts.UserCredential.UserCredentialType == CredentialType.SelfIssued)
                        {
                            //Override the user value as this should be false for types of SelfIssued
                            ts.UserCredential.DisplayCredentialHint = "false";
                        }
                        writer.WriteString(ts.UserCredential.DisplayCredentialHint);
                        writer.WriteEndElement();
                    }

                    switch (ts.UserCredential.UserCredentialType)
                    {
                    case CredentialType.SelfIssued:


                        writer.WriteStartElement("SelfIssuedCredential", "http://schemas.xmlsoap.org/ws/2005/05/identity");
                        if (!string.IsNullOrEmpty(ts.UserCredential.Value))
                        {
                            writer.WriteStartElement("PrivatePersonalIdentifier", "http://schemas.xmlsoap.org/ws/2005/05/identity");
                            writer.WriteString(ts.UserCredential.Value);
                            writer.WriteEndElement();
                        }
                        writer.WriteEndElement();
                        break;

                    case CredentialType.UsernameAndPassword:
                        writer.WriteStartElement("UsernamePasswordCredential", "http://schemas.xmlsoap.org/ws/2005/05/identity");
                        if (!string.IsNullOrEmpty(ts.UserCredential.Value))
                        {
                            writer.WriteStartElement("Username", "http://schemas.xmlsoap.org/ws/2005/05/identity");
                            writer.WriteString(ts.UserCredential.Value);
                            writer.WriteEndElement();
                        }
                        writer.WriteEndElement();
                        break;

                    case CredentialType.Kerberos:
                        writer.WriteStartElement("KerberosV5Credential", "http://schemas.xmlsoap.org/ws/2005/05/identity");
                        writer.WriteEndElement();
                        break;


                    case CredentialType.SmartCard:
                        writer.WriteStartElement("X509V3Credential", "http://schemas.xmlsoap.org/ws/2005/05/identity");

                        writer.WriteStartElement("X509Data", "http://www.w3.org/2000/09/xmldsig#");
                        if (!string.IsNullOrEmpty(ts.UserCredential.Value))
                        {
                            writer.WriteStartElement("KeyIdentifier", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
                            writer.WriteAttributeString("ValueType",
                                                        null,
                                                        "http://docs.oasis-open.org/wss/2004/xx/oasis-2004xx-wss-soap-message-security-1.1#ThumbprintSHA1");
                            writer.WriteString(RetrieveCertificate(ts.UserCredential.Value).Thumbprint);
                            writer.WriteEndElement();
                        }
                        else
                        {
                            throw new InvalidDataException("No thumbprint was specified");
                        }
                        writer.WriteEndElement();
                        writer.WriteEndElement();
                        break;

                    default:
                        break;
                    }
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                }
            }
            writer.WriteEndElement(); //end of tokenservice list
            //
            // tokentypes
            //
            writer.WriteStartElement("SupportedTokenTypeList", "http://schemas.xmlsoap.org/ws/2005/05/identity");
            foreach (TokenType tokenType in card.AcceptedTokenTypes)
            {
                writer.WriteElementString("TokenType",
                                          "http://schemas.xmlsoap.org/ws/2005/02/trust",
                                          tokenType.Uri);
            }
            writer.WriteEndElement();

            //
            // claims
            //
            writer.WriteStartElement("SupportedClaimTypeList", "http://schemas.xmlsoap.org/ws/2005/05/identity");
            foreach (CardClaim claim in card.SupportedClaimTypeList)
            {
                writer.WriteStartElement("SupportedClaimType", "http://schemas.xmlsoap.org/ws/2005/05/identity");
                writer.WriteAttributeString("Uri", claim.Uri);


                if (!String.IsNullOrEmpty(claim.DisplayTag))
                {
                    writer.WriteElementString("DisplayTag", "http://schemas.xmlsoap.org/ws/2005/05/identity",
                                              claim.DisplayTag);
                }

                if (!String.IsNullOrEmpty(claim.Description))
                {
                    writer.WriteElementString("Description", "http://schemas.xmlsoap.org/ws/2005/05/identity",
                                              claim.Description);
                }
                writer.WriteEndElement();
            }
            writer.WriteEndElement();


            if (card.RequireRPIdentification)
            {
                writer.WriteElementString("RequireAppliesTo", "http://schemas.xmlsoap.org/ws/2005/05/identity", card.RequireRPIdentification.ToString());
            }


            if (!String.IsNullOrEmpty(card.PrivacyNotice))
            {
                writer.WriteStartElement("PrivacyNotice", "http://schemas.xmlsoap.org/ws/2005/05/identity");
                writer.WriteString(card.PrivacyNotice);
                writer.WriteEndElement();
            }
            writer.WriteEndElement();

            writer.Close();



            stream.Position = 0;

            XmlDocument doc = new XmlDocument();

            doc.PreserveWhitespace = false;
            doc.Load(stream);

            return(doc);
        }
 public void GetListenAddressAndContext(out EndpointAddress listenAddress, out IDictionary<string, string> context)
 {
     // we expect the callback address to be already set when this is called
     if (this.CallbackAddress == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("callbackaddress");
     }
     EndpointAddressBuilder builder = new EndpointAddressBuilder(this.CallbackAddress);
     AddressHeader contextHeader = null;
     int contextHeaderIndex = -1;
     for (int i = 0; i < builder.Headers.Count; ++i)
     {
         if (builder.Headers[i].Name == ContextMessageHeader.ContextHeaderName && builder.Headers[i].Namespace == ContextMessageHeader.ContextHeaderNamespace)
         {
             if (contextHeader != null)
             {
                 throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(SR.GetString(SR.MultipleContextHeadersFoundInCallbackAddress)));
             }
             contextHeader = builder.Headers[i];
             contextHeaderIndex = i;
         }
     }
     if (contextHeader != null)
     {
         builder.Headers.RemoveAt(contextHeaderIndex);
     }
     context = (contextHeader != null) ? ContextMessageHeader.ParseContextHeader(contextHeader.GetAddressHeaderReader()).Context : null;
     listenAddress = builder.ToEndpointAddress();
 }
        static EndpointAddress CreateCallbackAddress(EndpointAddress listenAddress, IDictionary<string, string> context)
        {
            if (listenAddress == null)
            {
                return null;
            }

            EndpointAddressBuilder builder = new EndpointAddressBuilder(listenAddress);
            if (context != null)
            {
                builder.Headers.Add(new ContextAddressHeader(context));
            }
            return builder.ToEndpointAddress();
        }
Example #27
0
        /// <summary>
        /// Runs the test.
        /// </summary>
        public void RunTest()
        {
            try
            {
                //
                // P6 testing variables
                //
                const string projectId  = "EC00515";
                const string activityId = "EC1230";

                //
                // By pass my self signed cert.
                //
                ServicePointManager.DefaultConnectionLimit = 9999;
                ServicePointManager.Expect100Continue      = true;
                ServicePointManager.SecurityProtocol      |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
                ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); };


                //<DatabaseInstanceId xmlns="http://xmlns.oracle.com/Primavera/P6/V7/WS/Authentication">1</DatabaseInstanceId>
                // P6 project service endpoint
                //
                const string projectServiceEndpoint        = "https://oyster.gnet:8209/p6ws/services/ProjectService";
                const string activiyServiceEndpoint        = "https://oyster.gnet:8209/p6ws/services/ActivityService";
                const string authenticationServiceEndpoint = "https://oyster.gnet:8209/p6ws/services/AuthenticationService";

                const string userName = "******";
                const string password = "******";

                var authenticationService = CreateAuthenticationServiceClient(authenticationServiceEndpoint, userName, password);
                var readDatabaseInstances = authenticationService.ReadDatabaseInstances(new object());

                var databaseInstanceId = 0;
                foreach (var readDatabaseInstance in readDatabaseInstances)
                {
                    Console.WriteLine("DatabaseName {0} with DatabaseInstanceId = {1}", readDatabaseInstance.DatabaseName, readDatabaseInstance.DatabaseInstanceId);
                    if (readDatabaseInstance.DatabaseName.StartsWith("P6Demo"))
                    {
                        databaseInstanceId = readDatabaseInstance.DatabaseInstanceId;
                    }
                }

                //var login = new Login {UserName = userName, Password = password, DatabaseInstanceId = databaseInstanceId, DatabaseInstanceIdSpecified = true};
                //var loginResponse = authenticationService.Login(login);


                //var readSessions = authenticationService.ReadSessionProperties(new object());

                //
                // Create a client proxy for ProjectService
                //
                var projectService  = CreateProjectServiceClient(projectServiceEndpoint, userName, password);
                var activityService = CreateActivityServiceClient(activiyServiceEndpoint, userName, password);

                var eab           = new EndpointAddressBuilder(projectService.Endpoint.Address);
                var addressHeader = AddressHeader.CreateAddressHeader("DatabaseInstanceId", "http://xmlns.oracle.com/Primavera/P6/WS/Authentication/V1", databaseInstanceId.ToString(CultureInfo.InvariantCulture));
                eab.Headers.Add(addressHeader);
                projectService.Endpoint.Address = eab.ToEndpointAddress();



                var readProjects = DefaultProjectFields();
                readProjects.Filter = String.Format("Id = '{0}'", projectId);


                //
                // Read our projects
                //
                var readProject = projectService.ReadProjects(readProjects);
                if (readProject.Length > 0)
                {
                    Console.WriteLine("readProject has {0} project with code {1} last one named named {2}", readProject.Length, readProject[readProject.Length - 1].Id, readProject[readProject.Length - 1].Name);
                }


                var readActivities = DefaultActivityFields();
                readActivities.Filter = String.Format("Project Code = {0} and Id ='{1}'", readProject[0].Id, activityId);

                var readActivityTest = activityService.ReadActivities(readActivities);

                foreach (var activity in readActivityTest)
                {
                    Console.WriteLine(activity.Name);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Example #28
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;
            }
        }
Example #29
0
 public EndpointReference(EndpointAddressBuilder addressBuilder)
 {
     _address = addressBuilder.ToEndpointAddress();
 }
Example #30
0
        public void SerializeAndSign(string filename, X509Certificate2 cert)
        {
            MemoryStream stream = new MemoryStream();
            XmlWriter    writer = XmlWriter.Create(stream);

            writer.WriteStartElement(XmlNames.WSIdentity.InfoCardElement, XmlNames.WSIdentity.Namespace);

            //
            // write the InformationCardReference element
            //
            writer.WriteAttributeString(XmlNames.Xml.Language, XmlNames.Xml.Namespace, m_language);
            writer.WriteStartElement(XmlNames.WSIdentity.InfoCardRefElement, XmlNames.WSIdentity.Namespace);
            writer.WriteElementString(XmlNames.WSIdentity.CardIdElement, XmlNames.WSIdentity.Namespace, m_cardId);
            writer.WriteElementString(XmlNames.WSIdentity.CardVersionElement, XmlNames.WSIdentity.Namespace, m_cardVersion);
            writer.WriteEndElement();

            //
            // card name
            //
            if (!String.IsNullOrEmpty(m_cardName))
            {
                writer.WriteStartElement(XmlNames.WSIdentity.CardNameElement, XmlNames.WSIdentity.Namespace);
                writer.WriteString(m_cardName);
                writer.WriteEndElement();
            }


            //
            // card image
            //
            if (null != m_logo && 0 != m_logo.Length)
            {
                writer.WriteStartElement(XmlNames.WSIdentity.CardImageElement, XmlNames.WSIdentity.Namespace);
                if (!String.IsNullOrEmpty(m_mimeType))
                {
                    writer.WriteAttributeString(XmlNames.WSIdentity.MimeTypeAttribute, m_mimeType);
                }
                string val = Convert.ToBase64String(m_logo);
                writer.WriteString(val);
                writer.WriteEndElement();
            }

            //
            // card issuer uri
            //
            writer.WriteStartElement(XmlNames.WSIdentity.IssuerElement, XmlNames.WSIdentity.Namespace);
            writer.WriteString(m_issuerId);
            writer.WriteEndElement();


            //
            // issue time
            //
            writer.WriteStartElement(XmlNames.WSIdentity.TimeIssuedElement, XmlNames.WSIdentity.Namespace);
            writer.WriteString(XmlConvert.ToString(m_issuedOn, XmlDateTimeSerializationMode.Utc));
            writer.WriteEndElement();

            //
            // expiry time
            //
            writer.WriteStartElement(XmlNames.WSIdentity.TimeExpiresElement, XmlNames.WSIdentity.Namespace);
            writer.WriteString(XmlConvert.ToString(m_expiresOn, XmlDateTimeSerializationMode.Utc));
            writer.WriteEndElement();

            //
            // Start the tokenservice list
            //
            writer.WriteStartElement(XmlNames.WSIdentity.TokenServiceListElement, XmlNames.WSIdentity.Namespace);

            EndpointAddressBuilder eprBuilder = new EndpointAddressBuilder();

            eprBuilder.Uri = new Uri(m_issuerId);

            eprBuilder.Identity = new X509CertificateEndpointIdentity(cert);

            if (null != m_mexUri)
            {
                MetadataReference mexRef = new MetadataReference();
                mexRef.Address        = new EndpointAddress(m_mexUri);
                mexRef.AddressVersion = AddressingVersion.WSAddressing10;

                MetadataSection mexSection = new MetadataSection();
                mexSection.Metadata = mexRef;

                MetadataSet mexSet = new MetadataSet();
                mexSet.MetadataSections.Add(mexSection);


                MemoryStream memStream = new MemoryStream();

                XmlTextWriter writer1 = new XmlTextWriter(memStream, System.Text.Encoding.UTF8);

                mexSet.WriteTo(writer1);

                writer1.Flush();

                memStream.Seek(0, SeekOrigin.Begin);

                XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(memStream, XmlDictionaryReaderQuotas.Max);

                eprBuilder.SetMetadataReader(reader);
            }

            m_epr = eprBuilder.ToEndpointAddress();



            writer.WriteStartElement(XmlNames.WSIdentity.TokenServiceElement, XmlNames.WSIdentity.Namespace);

            //
            // Write the EndPointReference
            //
            m_epr.WriteTo(AddressingVersion.WSAddressing10, writer);

            //
            // Write the UserCredential Element
            //
            writer.WriteStartElement(XmlNames.WSIdentity.UserCredentialElement, XmlNames.WSIdentity.Namespace);

            //
            // Write the hint
            //
            if (!String.IsNullOrEmpty(m_hint))
            {
                writer.WriteStartElement(XmlNames.WSIdentity.DisplayCredentialHintElement, XmlNames.WSIdentity.Namespace);
                writer.WriteString(m_hint);
                writer.WriteEndElement();
            }

            switch (m_cardType)
            {
            case DefaultValues.CardType.UserNamePassword:
                writer.WriteStartElement(XmlNames.WSIdentity.UserNamePasswordCredentialElement, XmlNames.WSIdentity.Namespace);
                if (!string.IsNullOrEmpty(m_credentialIdentifier))
                {
                    writer.WriteStartElement(XmlNames.WSIdentity.UserNameElement, XmlNames.WSIdentity.Namespace);
                    writer.WriteString(m_credentialIdentifier);
                    writer.WriteEndElement();
                }
                writer.WriteEndElement();
                break;

            case DefaultValues.CardType.KerberosAuth:
                writer.WriteStartElement(XmlNames.WSIdentity.KerberosV5CredentialElement, XmlNames.WSIdentity.Namespace);
                writer.WriteEndElement();
                break;

            case DefaultValues.CardType.SelfIssuedAuth:
                writer.WriteStartElement(XmlNames.WSIdentity.SelfIssuedCredentialElement, XmlNames.WSIdentity.Namespace);
                if (!string.IsNullOrEmpty(m_credentialIdentifier))
                {
                    writer.WriteStartElement(XmlNames.WSIdentity.PrivatePersonalIdentifierElement, XmlNames.WSIdentity.Namespace);
                    writer.WriteString(m_credentialIdentifier);
                    writer.WriteEndElement();
                }
                else
                {
                    throw new InvalidDataException("No PPID was specified");
                }
                writer.WriteEndElement();
                break;

            case DefaultValues.CardType.SmartCard:
                writer.WriteStartElement(XmlNames.WSIdentity.X509V3CredentialElement, XmlNames.WSIdentity.Namespace);

                writer.WriteStartElement(XmlNames.XmlDSig.X509DataElement, XmlNames.XmlDSig.Namespace);
                if (!string.IsNullOrEmpty(m_credentialIdentifier))
                {
                    writer.WriteStartElement(XmlNames.WSSecurityExt.KeyIdentifierElement, XmlNames.WSSecurityExt.Namespace);
                    writer.WriteAttributeString(XmlNames.WSSecurityExt.ValueTypeAttribute,
                                                null,
                                                XmlNames.WSSecurityExt.Sha1ThumbrpintKeyTypeValue);
                    writer.WriteString(m_credentialIdentifier);
                    writer.WriteEndElement();
                }
                else
                {
                    throw new InvalidDataException("No thumbprint was specified");
                }
                writer.WriteEndElement();
                writer.WriteEndElement();
                break;

            default:
                break;
            }
            writer.WriteEndElement(); //end of user credential
            writer.WriteEndElement(); // end of tokenservice
            writer.WriteEndElement(); //end of tokenservice list
            //
            // tokentypes
            //
            writer.WriteStartElement(XmlNames.WSIdentity.SupportedTokenTypeListElement, XmlNames.WSIdentity.Namespace);
            foreach (string type in m_tokenTypes)
            {
                writer.WriteElementString(XmlNames.WSTrust.TokenType,
                                          XmlNames.WSTrust.Namespace,
                                          type);
            }
            writer.WriteEndElement();

            //
            // claims
            //
            writer.WriteStartElement(XmlNames.WSIdentity.SupportedClaimTypeListElement, XmlNames.WSIdentity.Namespace);
            foreach (ClaimInfo clm in m_supportedClaims)
            {
                writer.WriteStartElement(XmlNames.WSIdentity.SupportedClaimTypeElement, XmlNames.WSIdentity.Namespace);
                writer.WriteAttributeString(XmlNames.WSIdentity.UriAttribute, clm.Id);


                if (!String.IsNullOrEmpty(clm.DisplayTag))
                {
                    writer.WriteElementString(XmlNames.WSIdentity.DisplayTagElement,
                                              XmlNames.WSIdentity.Namespace,
                                              clm.DisplayTag);
                }

                if (!String.IsNullOrEmpty(clm.Description))
                {
                    writer.WriteElementString(XmlNames.WSIdentity.DescriptionElement,
                                              XmlNames.WSIdentity.Namespace,
                                              clm.Description);
                }
                writer.WriteEndElement();
            }
            writer.WriteEndElement();

            //
            // RequireAppliesTo
            //
            if (m_requireAppliesTo)
            {
                writer.WriteElementString(XmlNames.WSIdentity.RequireAppliesToElement, XmlNames.WSIdentity.Namespace, null);
            }

            //
            // Privacy Notice
            //
            if (!String.IsNullOrEmpty(m_privacyNoticeAt))
            {
                writer.WriteStartElement(XmlNames.WSIdentity.PrivacyNoticeAtElement, XmlNames.WSIdentity.Namespace);
                writer.WriteString(m_privacyNoticeAt);
                writer.WriteEndElement();
            }
            writer.WriteEndElement();

            writer.Close();



            //
            // Sign the xml content
            //
            stream.Position = 0;

            XmlDocument doc = new XmlDocument();

            doc.PreserveWhitespace = false;
            doc.Load(stream);

            SignedXml signed = new SignedXml();

            signed.SigningKey = cert.PrivateKey;
            signed.Signature.SignedInfo.CanonicalizationMethod
                = SignedXml.XmlDsigExcC14NTransformUrl;

            Reference reference = new Reference();

            reference.Uri = "#_Object_InfoCard";
            reference.AddTransform(
                new XmlDsigExcC14NTransform());
            signed.AddReference(reference);


            KeyInfo         info = new KeyInfo();
            KeyInfoX509Data data = new KeyInfoX509Data(cert,
                                                       X509IncludeOption.WholeChain);

            info.AddClause(data);

            signed.KeyInfo = info;
            DataObject cardData = new DataObject("_Object_InfoCard", null, null, doc.DocumentElement);

            signed.AddObject(cardData);

            signed.ComputeSignature();

            XmlElement e = signed.GetXml();

            XmlTextWriter fileWriter = new XmlTextWriter(filename, Encoding.UTF8);

            e.WriteTo(fileWriter);
            fileWriter.Flush();
            fileWriter.Close();
        }