Ejemplo n.º 1
0
        public XConnectClient GetClient()
        {
            CertificateWebRequestHandlerModifierOptions options =
                CertificateWebRequestHandlerModifierOptions.Parse("StoreName=My;StoreLocation=LocalMachine;FindType=FindByThumbprint;FindValue=C14AA17037663A3C3A134734AA588B654B431EB2");

            var certificateModifier = new CertificateWebRequestHandlerModifier(options);

            List <IHttpClientModifier> clientModifiers = new List <IHttpClientModifier>();
            var timeoutClientModifier = new TimeoutHttpClientModifier(new TimeSpan(0, 0, 20));

            clientModifiers.Add(timeoutClientModifier);

            var collectionClient    = new CollectionWebApiClient(new Uri("https://sc9.xconnect/odata"), clientModifiers, new[] { certificateModifier });
            var searchClient        = new SearchWebApiClient(new Uri("https://sc9.xconnect/odata"), clientModifiers, new[] { certificateModifier });
            var configurationClient = new ConfigurationWebApiClient(new Uri("https://sc9.xconnect/configuration"), clientModifiers, new[] { certificateModifier });

            var config = new XConnectClientConfiguration(
                new XdbRuntimeModel(CollectionModel.Model), collectionClient, searchClient, configurationClient);

            try
            {
                config.Initialize();
            }
            catch (XdbModelConflictException ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }

            return(new XConnectClient(config));
        }
Ejemplo n.º 2
0
        public static XConnectClient GetClient()
        {
            string xconnectCollectionCertificateConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["xconnect.collection.certificate"].ConnectionString;
            string xconnectCollectionConnectionString            = System.Configuration.ConfigurationManager.ConnectionStrings["xconnect.collection"].ConnectionString;;
            CertificateWebRequestHandlerModifierOptions options  =
                CertificateWebRequestHandlerModifierOptions.Parse("xconnectCollectionCertificateConnectionString");

            var certificateModifier = new CertificateWebRequestHandlerModifier(options);

            List <IHttpClientModifier> clientModifiers = new List <IHttpClientModifier>();
            var timeoutClientModifier = new TimeoutHttpClientModifier(new TimeSpan(0, 0, 20));

            clientModifiers.Add(timeoutClientModifier);

            var collectionClient    = new CollectionWebApiClient(new Uri(xconnectCollectionConnectionString + "/odata"), clientModifiers, new[] { certificateModifier });
            var searchClient        = new SearchWebApiClient(new Uri(xconnectCollectionConnectionString + "/odata"), clientModifiers, new[] { certificateModifier });
            var configurationClient = new ConfigurationWebApiClient(new Uri(xconnectCollectionConnectionString + "/configuration"), clientModifiers, new[] { certificateModifier });

            var config = new XConnectClientConfiguration(
                new XdbRuntimeModel(CollectionModel.Model), collectionClient, searchClient, configurationClient);

            try
            {
                config.Initialize();
            }
            catch (XdbModelConflictException ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }

            return(new XConnectClient(config));
        }
Ejemplo n.º 3
0
        private XConnectClient GetClient()
        {
            XConnectClientConfiguration cfg;

            if (string.IsNullOrEmpty(XconnectThumbprint))
            {
                cfg = new XConnectClientConfiguration(
                    new XdbRuntimeModel(FaceApiModel.Model),
                    new Uri(XconnectUrl),
                    new Uri(XconnectUrl));
            }
            else
            {
                CertificateWebRequestHandlerModifierOptions options =
                    CertificateWebRequestHandlerModifierOptions.Parse("StoreName=My;StoreLocation=LocalMachine;FindType=FindByThumbprint;FindValue=" + XconnectThumbprint);
                var certificateModifier = new CertificateWebRequestHandlerModifier(options);

                // Step 2 - Client Configuration

                var collectionClient    = new CollectionWebApiClient(new Uri(XconnectUrl + "/odata"), null, new[] { certificateModifier });
                var searchClient        = new SearchWebApiClient(new Uri(XconnectUrl + "/odata"), null, new[] { certificateModifier });
                var configurationClient = new ConfigurationWebApiClient(new Uri(XconnectUrl + "/configuration"), null, new[] { certificateModifier });


                cfg = new XConnectClientConfiguration(
                    new XdbRuntimeModel(FaceApiModel.Model), collectionClient, searchClient, configurationClient);
            }

            cfg.Initialize();

            var client = new XConnectClient(cfg);

            return(client);
        }
        /// <summary>
        /// Gets the handler configurations for the Reference Data client
        /// </summary>
        /// <param name="thumbprint"></param>
        /// <returns></returns>
        public virtual IWebRequestHandlerModifier[] GetReferenceDataHandlers(string thumbprint)
        {
            // Valid certificate thumbprints must be passed in
            var options = CertificateWebRequestHandlerModifierOptions.Parse("StoreName=My;StoreLocation=LocalMachine;FindType=FindByThumbprint;FindValue=" + thumbprint);

            // Optional timeout modifier
            IWebRequestHandlerModifier[] handlers = { new CertificateWebRequestHandlerModifier(options) };

            return(handlers);
        }
        public ActionResult SlackSearch(SlackSearchViewModel model)
        {
            #region Setting things up for xConnect

            // TO DO: This should be in app.config
            //var xConnectCertificateConnectionString = ConfigurationManager.AppSettings["xConnectCertificateConnectionString"];
            var xConnectCertificateConnectionString = "StoreName=My;StoreLocation=LocalMachine;FindType=FindByThumbprint;FindValue=3DE93B08A1C99FDC874B5A035EF02C66F3CB77E0";

            // (CTW) Getting xConnect Root Url from config
            //var xConnectRootUrl = ConfigurationManager.AppSettings["xConnectRootUrl"];
            var xConnectRootUrl = "https://hc.sc.xconnect";

            CertificateWebRequestHandlerModifierOptions options =
                CertificateWebRequestHandlerModifierOptions.Parse(xConnectCertificateConnectionString);
            var certificateModifier = new CertificateWebRequestHandlerModifier(options);

            List <IHttpClientModifier> clientModifiers = new List <IHttpClientModifier>();
            var timeoutClientModifier = new TimeoutHttpClientModifier(new TimeSpan(0, 0, 20));
            clientModifiers.Add(timeoutClientModifier);

            var collectionClient    = new CollectionWebApiClient(new Uri(xConnectRootUrl + "/odata"), clientModifiers, new[] { certificateModifier });
            var searchClient        = new SearchWebApiClient(new Uri(xConnectRootUrl + "/odata"), clientModifiers, new[] { certificateModifier });
            var configurationClient = new ConfigurationWebApiClient(new Uri(xConnectRootUrl + "/configuration"), clientModifiers, new[] { certificateModifier });

            var cfg = new XConnectClientConfiguration(
                new XdbRuntimeModel(CollectionModel.Model), collectionClient, searchClient, configurationClient);

            #endregion

            try
            {
                cfg.Initialize();
            }
            catch (XdbModelConflictException ce)
            {
                Console.WriteLine("ERROR:" + ce.Message);
                return(null);
            }

            // Initialize a client using the validated configuration
            using (var client = new XConnectClient(cfg))
            {
                // TO DO: This should be loaded via reflection
                IArticleProvider articleProvider = new SimpleArticleProvider
                {
                    Client = client
                };

                model.ArticleList = articleProvider.GetArticles("SLACK_ALIAS", model.SlackId);

                return(View("slacksearchview", model));
            }
        }
Ejemplo n.º 6
0
        public static void GetContact()
        {
            // Valid certificate thumbprints must be passed in
            CertificateWebRequestHandlerModifierOptions options =
                CertificateWebRequestHandlerModifierOptions.Parse("StoreName=My;StoreLocation=LocalMachine;FindType=FindByThumbprint;FindValue=DAEDD8105CFFAD6E95F25488E72EF0B5C6C9328B");

            var certificateModifier = new CertificateWebRequestHandlerModifier(options);

            // Optional timeout modifier
            List <IHttpClientModifier> clientModifiers = new List <IHttpClientModifier>();
            var timeoutClientModifier = new TimeoutHttpClientModifier(new TimeSpan(0, 0, 20));

            clientModifiers.Add(timeoutClientModifier);

            // This overload takes three client end points - collection, search, and configuration
            var collectionClient    = new CollectionWebApiClient(new Uri("https://sc902.xconnect/odata"), clientModifiers, new[] { certificateModifier });
            var searchClient        = new SearchWebApiClient(new Uri("https://sc902.xconnect/odata"), clientModifiers, new[] { certificateModifier });
            var configurationClient = new ConfigurationWebApiClient(new Uri("https://sc902.xconnect/configuration"), clientModifiers, new[] { certificateModifier });

            var cfg = new XConnectClientConfiguration(
                new XdbRuntimeModel(CollectionModel.Model, MySiteCollectionModel.Model), collectionClient, searchClient, configurationClient);

            try
            {
                cfg.Initialize();
            }
            catch (XdbModelConflictException ce)
            {
                System.Console.WriteLine("ERROR:" + ce.Message);
                return;
            }

            using (var client = new XConnectClient(cfg))
            {
                var reference = new IdentifiedContactReference("Website", "*****@*****.**");

                var contact = client.Get <Sitecore.XConnect.Contact>(reference, new ContactExpandOptions(PersonalInformation.DefaultFacetKey, BusinessIndustry.DefaultFacetKey, EmailAddressList.DefaultFacetKey)
                {
                    Interactions = new RelatedInteractionsExpandOptions(IpInfo.DefaultFacetKey)
                    {
                        StartDateTime = DateTime.MinValue,
                        EndDateTime   = DateTime.MaxValue,
                        Limit         = 3
                    }
                });
            }
        }
        private XConnectClient GetClient()
        {
            // Valid certificate thumbprint must be passed in
            CertificateWebRequestHandlerModifierOptions options =
                CertificateWebRequestHandlerModifierOptions.Parse($"StoreName=My;StoreLocation=LocalMachine;FindType=FindByThumbprint;FindValue={XConnectThumbprint}");

            // Optional timeout modifier
            var certificateModifier = new CertificateWebRequestHandlerModifier(options);

            List <IHttpClientModifier> clientModifiers = new List <IHttpClientModifier>();

            var timeoutClientModifier = new TimeoutHttpClientModifier(new TimeSpan(0, 0, 20));

            clientModifiers.Add(timeoutClientModifier);

            // This overload takes three client end points - collection, search, and configuration
            var collectionClient    = new CollectionWebApiClient(new Uri($"{XConnectUrl.TrimEnd(new char['/'])}/odata"), clientModifiers, new[] { certificateModifier });
            var searchClient        = new SearchWebApiClient(new Uri($"{XConnectUrl.TrimEnd(new char['/'])}/odata"), clientModifiers, new[] { certificateModifier });
            var configurationClient = new ConfigurationWebApiClient(new Uri($"{XConnectUrl.TrimEnd(new char['/'])}/configuration"), clientModifiers, new[] { certificateModifier });

            //Reference: https://sitecore.stackexchange.com/questions/8910/the-type-of-this-instance-does-not-correspond-to-any-type-in-the-model
            XdbModel[] models = { CollectionModel.Model, GoogleApiModel.Model };

            var xConnectClientConfiguration = new XConnectClientConfiguration(
                new XdbRuntimeModel(models),
                collectionClient,
                searchClient,
                configurationClient);

            try
            {
                xConnectClientConfiguration.Initialize();
            }
            catch (XdbModelConflictException ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }

            return(new XConnectClient(xConnectClientConfiguration));
        }
Ejemplo n.º 8
0
        public static async Task <XConnectClient> Create()
        {
            const string XCONNECT_ENDPOINT_KEY = "xconnect.collection";

            var connectionStrings = WebConfigurationManager.ConnectionStrings;
            var endpoint          = connectionStrings[XCONNECT_ENDPOINT_KEY]?.ConnectionString;

            Uri endpointUri;

            if (!Uri.TryCreate(endpoint, UriKind.Absolute, out endpointUri))
            {
                throw new Exception($"Endpoint to xConnect has not been specified.  The key name must be [{XCONNECT_ENDPOINT_KEY}]");
            }

            CollectionWebApiClient      collectionClient;
            SearchWebApiClient          searchClient;
            ConfigurationWebApiClient   configurationClient;
            XConnectClientConfiguration cfg;

            var certificate = connectionStrings["xconnect.collection.certificate"]?.ConnectionString;

            List <IHttpClientModifier> modifiers = null;

            CertificateWebRequestHandlerModifier[] certificateModifiers = null;

            //if a certificate was specified in config
            if (string.IsNullOrEmpty(certificate) == false)
            {
                var certOptions = CertificateWebRequestHandlerModifierOptions.Parse(certificate);
                certificateModifiers = new[] { new CertificateWebRequestHandlerModifier(certOptions) };
                modifiers            = new List <IHttpClientModifier>()
                {
                    new TimeoutHttpClientModifier(new TimeSpan(0, 0, 20))
                };
            }

            collectionClient    = new CollectionWebApiClient(new Uri(endpointUri, "odata/"), modifiers, certificateModifiers);
            searchClient        = new SearchWebApiClient(new Uri(endpointUri, "odata/"), modifiers, certificateModifiers);
            configurationClient = new ConfigurationWebApiClient(new Uri(endpointUri, "configuration/"), modifiers, certificateModifiers);
            cfg = new XConnectClientConfiguration(new XdbRuntimeModel(ModelFactory.Instance), collectionClient, searchClient, configurationClient, true);

            await cfg.InitializeAsync();

            return(new XConnectClient(cfg));
        }
Ejemplo n.º 9
0
        private static XConnectClient GetClient()
        {
            // Valid certificate thumbprint must be passed in
            CertificateWebRequestHandlerModifierOptions options =
                CertificateWebRequestHandlerModifierOptions.Parse("StoreName=My;StoreLocation=LocalMachine;FindType=FindByThumbprint;FindValue=99BCB5C8EC438A165CE3BDE23A53A15E4E3F2FCB");

            // Optional timeout modifier
            var certificateModifier = new CertificateWebRequestHandlerModifier(options);

            List <IHttpClientModifier> clientModifiers = new List <IHttpClientModifier>();
            var timeoutClientModifier = new TimeoutHttpClientModifier(new TimeSpan(0, 0, 20));

            clientModifiers.Add(timeoutClientModifier);

            // This overload takes three client end points - collection, search, and configuration
            var collectionClient    = new CollectionWebApiClient(new Uri(xConnectURL + "/odata"), clientModifiers, new[] { certificateModifier });
            var searchClient        = new SearchWebApiClient(new Uri(xConnectURL + "/odata"), clientModifiers, new[] { certificateModifier });
            var configurationClient = new ConfigurationWebApiClient(new Uri(xConnectURL + "/configuration"), clientModifiers, new[] { certificateModifier });

            var config = new XConnectClientConfiguration(
                new XdbRuntimeModel(CollectionModel.Model),
                collectionClient,
                searchClient,
                configurationClient);

            try
            {
                config.Initialize();
            }
            catch (XdbModelConflictException ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }

            return(new XConnectClient(config));
        }
Ejemplo n.º 10
0
        private static XConnectClient GetClient()
        {
            string XconnectUrl        = ConfigurationManager.AppSettings["xconnect.url"];
            string XconnectThumbprint = ConfigurationManager.AppSettings["xconnect.thumbprint"];

            System.Console.WriteLine("XconnectThumbprint:" + XconnectThumbprint);
            System.Console.WriteLine("XconnectUrl:" + XconnectUrl);


            XConnectClientConfiguration cfg;

            if (string.IsNullOrEmpty(XconnectThumbprint))
            {
                cfg = new XConnectClientConfiguration(
                    new XdbRuntimeModel(Sitecore.XConnect.Collection.Model.CollectionModel.Model),
                    new Uri(XconnectUrl),
                    new Uri(XconnectUrl));
            }
            else
            {
                CertificateWebRequestHandlerModifierOptions options =
                    CertificateWebRequestHandlerModifierOptions.Parse("StoreName=My;StoreLocation=LocalMachine;FindType=FindByThumbprint;FindValue=" + XconnectThumbprint);
                var certificateModifier = new CertificateWebRequestHandlerModifier(options);

                // Step 2 - Client Configuration

                var collectionClient    = new CollectionWebApiClient(new Uri(XconnectUrl + "/odata"), null, new[] { certificateModifier });
                var searchClient        = new SearchWebApiClient(new Uri(XconnectUrl + "/odata"), null, new[] { certificateModifier });
                var configurationClient = new ConfigurationWebApiClient(new Uri(XconnectUrl + "/configuration"), null, new[] { certificateModifier });


                cfg = new XConnectClientConfiguration(
                    new XdbRuntimeModel(Sitecore.XConnect.Collection.Model.CollectionModel.Model), collectionClient, searchClient, configurationClient);
            }

            cfg.Initialize();

            var client = new XConnectClient(cfg);

            return(client);
        }
Ejemplo n.º 11
0
        private XConnectClient BuildClient()
        {
            string XconnectUrl = ConfigurationManager.ConnectionStrings["xconnect.collection"].ConnectionString;

            string XconnectThumbprint = ConfigurationManager.ConnectionStrings["xconnect.collection.certificate"].ConnectionString;

            XConnectClientConfiguration cfg;

            if (string.IsNullOrEmpty(XconnectThumbprint))
            {
                cfg = new XConnectClientConfiguration(
                    new XdbRuntimeModel(FaceApiModel.Model),
                    new Uri(XconnectUrl),
                    new Uri(XconnectUrl));
            }
            else
            {
                CertificateWebRequestHandlerModifierOptions options =
                    CertificateWebRequestHandlerModifierOptions.Parse(XconnectThumbprint);
                var certificateModifier = new CertificateWebRequestHandlerModifier(options);

                // Step 2 - Client Configuration

                var collectionClient    = new CollectionWebApiClient(new Uri(XconnectUrl + "/odata"), null, new[] { certificateModifier });
                var searchClient        = new SearchWebApiClient(new Uri(XconnectUrl + "/odata"), null, new[] { certificateModifier });
                var configurationClient = new ConfigurationWebApiClient(new Uri(XconnectUrl + "/configuration"), null, new[] { certificateModifier });


                cfg = new XConnectClientConfiguration(
                    new XdbRuntimeModel(FaceApiModel.Model), collectionClient, searchClient, configurationClient);
            }

            cfg.Initialize();

            var client = new XConnectClient(cfg);

            return(client);
        }
        private static async Task MainAsync(string[] args)
        {
            CertificateWebRequestHandlerModifierOptions options =
                CertificateWebRequestHandlerModifierOptions.Parse("StoreName=My;StoreLocation=LocalMachine;FindType=FindByThumbprint;FindValue=75980C7DD01B535796DEE0A8E682F28EB465536D");

            var certificateModifier = new CertificateWebRequestHandlerModifier(options);

            List <IHttpClientModifier> clientModifiers = new List <IHttpClientModifier>();
            var timeoutClientModifier = new TimeoutHttpClientModifier(new TimeSpan(0, 0, 20));

            clientModifiers.Add(timeoutClientModifier);

            var collectionClient    = new CollectionWebApiClient(new Uri("https://schackwishingwebz01xconnect/odata"), clientModifiers, new[] { certificateModifier });
            var searchClient        = new SearchWebApiClient(new Uri("https://schackwishingwebz01xconnect/odata"), clientModifiers, new[] { certificateModifier });
            var configurationClient = new ConfigurationWebApiClient(new Uri("https://schackwishingwebz01xconnect/configuration"), clientModifiers, new[] { certificateModifier });

            var cfg = new XConnectClientConfiguration(
                new XdbRuntimeModel(ConsentModel.Model), collectionClient, searchClient, configurationClient);

            var json = XdbModelWriter.Serialize(ConsentModel.Model);

            Console.WriteLine(json);
        }
        /// <summary>
        /// Builds a client configuration object for connecting to xConnect.
        /// Includes certificate and timeout modifiers, and sets up client connections.
        /// </summary>
        /// <param name="collectionHost">The host name where the collection endpoint is located</param>
        /// <param name="searchHost">The host name where the search endpoint is located</param>
        /// <param name="configHost">The host name where configuration info should be retrieved</param>
        /// <param name="thumbprint">The thumbprint for the certificate to connect with</param>
        /// <returns>A new configuration instance</returns>
        public virtual XConnectClientConfiguration GetClientConfiguration(string collectionHost, string searchHost, string configHost, string thumbprint)
        {
            //Set up the certificate used to connect to xConnect endpoints
            var options             = CertificateWebRequestHandlerModifierOptions.Parse("StoreName=My;StoreLocation=LocalMachine;FindType=FindByThumbprint;FindValue=" + thumbprint);
            var certificateModifier = new CertificateWebRequestHandlerModifier(options);

            //Set up timeout modifier for the client
            var timeoutClientModifier = new TimeoutHttpClientModifier(new TimeSpan(0, 0, 20));
            var clientModifiers       = new List <IHttpClientModifier>
            {
                timeoutClientModifier
            };

            //Initialize the clients. Each requires the certificate in order to open the connection
            var collectionClient    = new CollectionWebApiClient(new Uri(collectionHost + "/odata"), clientModifiers, new[] { certificateModifier });
            var searchClient        = new SearchWebApiClient(new Uri(searchHost + "/odata"), clientModifiers, new[] { certificateModifier });
            var configurationClient = new ConfigurationWebApiClient(new Uri(configHost + "/configuration"), clientModifiers, new[] { certificateModifier });

            //Create the configuration object with all clients
            var cfg = new XConnectClientConfiguration(
                new XdbRuntimeModel(CollectionModel.Model), collectionClient, searchClient, configurationClient);

            return(cfg);
        }
Ejemplo n.º 14
0
        //Demo Code
        public void createUpdateContactDemo()
        {
            var offlineGoal = Guid.Parse("A9948719-E6E4-46D2-909B-3680E724ECE9"); //offline goal - KioskSubmission goal
            var channelId   = Guid.Parse("3FC61BB8-0D9F-48C7-9BBD-D739DCBBE032"); // /sitecore/system/Marketing Control Panel/Taxonomies/Channel/Offline/Store/Enter store - offline enter storl channel

            CertificateWebRequestHandlerModifierOptions options =
                CertificateWebRequestHandlerModifierOptions.Parse("StoreName=My;StoreLocation=LocalMachine;FindType=FindByThumbprint;FindValue=587d948806e57cf511b37a447a2453a02dfd3686");

            // Optional timeout modifier
            var certificateModifier = new CertificateWebRequestHandlerModifier(options);

            List <IHttpClientModifier> clientModifiers = new List <IHttpClientModifier>();
            var timeoutClientModifier = new TimeoutHttpClientModifier(new TimeSpan(0, 0, 20));

            clientModifiers.Add(timeoutClientModifier);

            // This overload takes three client end points - collection, search, and configuration
            var collectionClient    = new CollectionWebApiClient(new Uri("https://sc9.xconnect/odata"), clientModifiers, new[] { certificateModifier });
            var searchClient        = new SearchWebApiClient(new Uri("https://sc9.xconnect/odata"), clientModifiers, new[] { certificateModifier });
            var configurationClient = new ConfigurationWebApiClient(new Uri("https://sc9.xconnect/configuration"), clientModifiers, new[] { certificateModifier });



            var config = new XConnectClientConfiguration(
                new XdbRuntimeModel(CollectionModel.Model), collectionClient, searchClient, configurationClient);

            config.Initialize();


            using (Sitecore.XConnect.Client.XConnectClient client = new XConnectClient(config))
            {
                try
                {
                    bool isExist         = false;
                    var  existingContact = client.Get <Contact>(new IdentifiedContactReference("HIxConnect", contactIdentifierPrefix + txtEmailAddress.Text), new ContactExpandOptions(new string[] { PersonalInformation.DefaultFacetKey, EmailAddressList.DefaultFacetKey }));
                    if (existingContact != null)
                    {
                        var personalInfoFacet = existingContact.GetFacet <PersonalInformation>(PersonalInformation.DefaultFacetKey);
                        if (personalInfoFacet != null)
                        {
                            personalInfoFacet.FirstName         = txtFName.Text;
                            personalInfoFacet.LastName          = txtLname.Text;
                            personalInfoFacet.MiddleName        = txtMName.Text;
                            personalInfoFacet.PreferredLanguage = ddLanguage.SelectedValue;
                            personalInfoFacet.Title             = ddTitle.SelectedValue;
                            personalInfoFacet.Gender            = ddGender.SelectedValue;
                            personalInfoFacet.JobTitle          = txtJobRole.Text;
                            client.SetFacet <PersonalInformation>(existingContact, PersonalInformation.DefaultFacetKey, personalInfoFacet);
                        }
                    }
                    else
                    {
                        // Identifier for a 'known' contact
                        var identifier = new ContactIdentifier[]
                        {
                            new ContactIdentifier("HIxConnect", contactIdentifierPrefix + txtEmailAddress.Text, ContactIdentifierType.Known)
                        };
                        // Create a new contact with the identifier
                        Contact knownContact = new Contact(identifier);
                        client.AddContact(knownContact);
                        #region Personal Information Facet
                        //Persona information facet
                        PersonalInformation personalInfoFacet = new PersonalInformation();
                        personalInfoFacet.FirstName         = txtFName.Text;
                        personalInfoFacet.LastName          = txtLname.Text;
                        personalInfoFacet.MiddleName        = txtMName.Text;
                        personalInfoFacet.PreferredLanguage = ddLanguage.SelectedValue;
                        personalInfoFacet.Title             = ddTitle.SelectedValue;
                        personalInfoFacet.Gender            = ddGender.SelectedValue;
                        personalInfoFacet.JobTitle          = txtJobRole.Text;
                        client.SetFacet <PersonalInformation>(knownContact, PersonalInformation.DefaultFacetKey, personalInfoFacet);
                        #endregion

                        //Create a new interaction for that contact
                        Interaction interaction = new Interaction(knownContact, InteractionInitiator.Contact, channelId, "");
                        // Add events - all interactions must have at least one event
                        var xConnectEvent = new Goal(offlineGoal, DateTime.UtcNow);
                        interaction.Events.Add(xConnectEvent);

                        #region EmailAddress Facet
                        EmailAddressList emails = new EmailAddressList(new EmailAddress(txtEmailAddress.Text, true), EmailAddressList.DefaultFacetKey);
                        //OR the following code
                        //var emails = existingContact.GetFacet<EmailAddressList>(EmailAddressList.DefaultFacetKey);
                        //emails.PreferredEmail = new EmailAddress("*****@*****.**", true);
                        client.SetFacet <EmailAddressList>(knownContact, EmailAddressList.DefaultFacetKey, emails);
                        #endregion


                        #region Set Avatar
                        var userAvatar = new Avatar("image/jpeg", userImage);
                        client.SetAvatar(knownContact, userAvatar);
                        #endregion


                        #region IPInfo Facet
                        //IpInfo ipInfo = new IpInfo("127.0.0.1");
                        //ipInfo.BusinessName = "Kiosk Desk";
                        //client.SetFacet<IpInfo>(knownContact, IpInfo.DefaultFacetKey, ipInfo);
                        #endregion
                        //Add interaction to client
                        client.AddInteraction(interaction);
                    }
                    client.Submit();

                    #region  Display Purpose - Operations display
                    //var operations = client.LastBatch;
                    //// Loop through operations and check status
                    //foreach (var operation in operations)
                    //{
                    //    ltrl_status.Text += operation.OperationType + operation.Target.GetType().ToString() + " Operation: " + operation.Status + "<br/>";
                    //}
                    // ltrl_status.Text= "<p class=\"success\">Thank you for sharing your contact details!</p>";
                    #endregion
                    ltrl_status.Text = "Thank you for sharing your details";
                }
                catch (XdbExecutionException ex)
                {
                    // Manage exception
                    //ltrl_status.Text += "Error Occured while Xdb Execution:" + ex.Message + "<br/>" + ex.StackTrace;
                    ltrl_status.Text = " <p style=\"color:red;\">Something went wrong!</p>";
                }
                catch (Exception ex)
                {
                    //ltrl_status.Text += "Error Occured:" + ex.Message + "<br/>" + ex.StackTrace;
                    ltrl_status.Text = " <p style=\"color:red;\">Something went wrong!</p>";
                }
            }
        }
Ejemplo n.º 15
0
        private static async Task MainAsync(string[] args)
        {
            CertificateWebRequestHandlerModifierOptions options =
                CertificateWebRequestHandlerModifierOptions.Parse("StoreName=My;StoreLocation=LocalMachine;FindType=FindByThumbprint;FindValue=‎DE12BF44CAC821F2E5AD5C0C8E6158B65C98C4D4");

            var certificateModifier = new CertificateWebRequestHandlerModifier(options);

            List <IHttpClientModifier> clientModifiers = new List <IHttpClientModifier>();
            var timeoutClientModifier = new TimeoutHttpClientModifier(new TimeSpan(0, 0, 20));

            clientModifiers.Add(timeoutClientModifier);

            var collectionClient    = new CollectionWebApiClient(new Uri("https://Sc91.xconnect/odata"), clientModifiers, new[] { certificateModifier });
            var searchClient        = new SearchWebApiClient(new Uri("https://Sc91.xconnect/odata"), clientModifiers, new[] { certificateModifier });
            var configurationClient = new ConfigurationWebApiClient(new Uri("https://Sc91.xconnect/configuration"), clientModifiers, new[] { certificateModifier });

            var cfg = new XConnectClientConfiguration(
                new XdbRuntimeModel(CollectionModel.Model), collectionClient, searchClient, configurationClient);

            try
            {
                await cfg.InitializeAsync();

                // Print xConnect if configuration is valid
                var arr = new[]
                {
                    @"            ______                                                       __     ",
                    @"           /      \                                                     |  \    ",
                    @" __    __ |  $$$$$$\  ______   _______   _______    ______    _______  _| $$_   ",
                    @"|  \  /  \| $$   \$$ /      \ |       \ |       \  /      \  /       \|   $$ \  ",
                    @"\$$\/  $$| $$      |  $$$$$$\| $$$$$$$\| $$$$$$$\|  $$$$$$\|  $$$$$$$ \$$$$$$   ",
                    @" >$$  $$ | $$   __ | $$  | $$| $$  | $$| $$  | $$| $$    $$| $$        | $$ __  ",
                    @" /  $$$$\ | $$__/  \| $$__/ $$| $$  | $$| $$  | $$| $$$$$$$$| $$_____   | $$|  \",
                    @"|  $$ \$$\ \$$    $$ \$$    $$| $$  | $$| $$  | $$ \$$     \ \$$     \   \$$  $$",
                    @" \$$   \$$  \$$$$$$   \$$$$$$  \$$   \$$ \$$   \$$  \$$$$$$$  \$$$$$$$    \$$$$ "
                };
                Console.WindowWidth = 160;
                foreach (string line in arr)
                {
                    Console.WriteLine(line);
                }
            }
            catch (XdbModelConflictException ce)
            {
                Console.WriteLine("ERROR:" + ce.Message);
                return;
            }

            // Initialize a client using the validated configuration
            using (var client = new XConnectClient(cfg))
            {
                try
                {
                    // Identifier for a 'known' contact
                    var identifier = new ContactIdentifier[]
                    {
                        new ContactIdentifier("twitter", "myrtlesitecore" + Guid.NewGuid().ToString("N"), ContactIdentifierType.Known)
                    };

                    // Print out the identifier that is going to be used
                    Console.WriteLine("Identifier:" + identifier[0].Identifier);

                    // Create a new contact with the identifier
                    Contact knownContact = new Contact(identifier);

                    client.AddContact(knownContact);

                    // Submit contact and interaction - a total of two operations
                    await client.SubmitAsync();

                    // Get the last batch that was executed
                    var operations = client.LastBatch;

                    Console.WriteLine("RESULTS...");

                    // Loop through operations and check status
                    foreach (var operation in operations)
                    {
                        Console.WriteLine(operation.OperationType + operation.Target.GetType().ToString() + " Operation: " + operation.Status);
                    }

                    Console.ReadLine();
                }
                catch (XdbExecutionException ex)
                {
                    // Deal with exception
                }
            }
        }
Ejemplo n.º 16
0
        private static async Task MainAsync(string[] args)
        {
            Console.WriteLine(" ");

            CertificateWebRequestHandlerModifierOptions options =
                CertificateWebRequestHandlerModifierOptions.Parse("StoreName=My;StoreLocation=LocalMachine;FindType=FindByThumbprint;FindValue=587d948806e57cf511b37a447a2453a02dfd3686");

            var certificateModifier = new CertificateWebRequestHandlerModifier(options);

            List <IHttpClientModifier> clientModifiers = new List <IHttpClientModifier>();
            var timeoutClientModifier = new TimeoutHttpClientModifier(new TimeSpan(0, 0, 20));

            clientModifiers.Add(timeoutClientModifier);

            var collectionClient    = new CollectionWebApiClient(new Uri("https://sc9.xconnect/odata"), clientModifiers, new[] { certificateModifier });
            var searchClient        = new SearchWebApiClient(new Uri("https://sc9.xconnect/odata"), clientModifiers, new[] { certificateModifier });
            var configurationClient = new ConfigurationWebApiClient(new Uri("https://sc9.xconnect/configuration"), clientModifiers, new[] { certificateModifier });

            var cfg = new XConnectClientConfiguration(
                new XdbRuntimeModel(CollectionModel.Model), collectionClient, searchClient, configurationClient);

            try
            {
                cfg.Initialize(); // cfg.InitializeAsync();
                Console.WindowWidth = 160;

                var arr1 = new[]
                {
                    @"                                                                                ",
                    @" __    __  _____                                                                ",
                    @"\  \  \ \ \     \                                                               ",
                    @"|##|  |## |######                                                               ",
                    @"|##|  |##  \ ##                                                                 ",
                    @"|##| _|##   |##                                                                 ",
                    @"|########|  |##                                                                 ",
                    @"|##|   ##   |##|                                                                ",
                    @"|##|   ##   |## \                                                               ",
                    @"|##|   ## |######|                                                              "
                };
                foreach (string line in arr1)
                {
                    Console.WriteLine(line);
                }
                Console.WriteLine();
                Console.WriteLine();
                Console.WriteLine();
                // Print xConnect if configuration is valid
                var arr = new[]
                {
                    @"            ______                                                       __     ",
                    @"           /      \                                                     |  \    ",
                    @" __    __ |  $$$$$$\  ______   _______   _______    ______    _______  _| $$_   ",
                    @"|  \  /  \| $$   \$$ /      \ |       \ |       \  /      \  /       \|   $$ \  ",
                    @"\$$\/  $$| $$      |  $$$$$$\| $$$$$$$\| $$$$$$$\|  $$$$$$\|  $$$$$$$ \$$$$$$   ",
                    @" >$$  $$ | $$   __ | $$  | $$| $$  | $$| $$  | $$| $$    $$| $$        | $$ __  ",
                    @" /  $$$$\ | $$__/  \| $$__/ $$| $$  | $$| $$  | $$| $$$$$$$$| $$_____   | $$|  \",
                    @"|  $$ \$$\ \$$    $$ \$$    $$| $$  | $$| $$  | $$ \$$     \ \$$     \   \$$  $$",
                    @" \$$   \$$  \$$$$$$   \$$$$$$  \$$   \$$ \$$   \$$  \$$$$$$$  \$$$$$$$    \$$$$ "
                };

                foreach (string line in arr)
                {
                    Console.WriteLine(line);
                }
                Console.WriteLine();
                Console.WriteLine();
                Console.WriteLine();
            }
            catch (XdbModelConflictException ce)
            {
                Console.WriteLine("ERROR:" + ce.Message);
                return;
            }

            Console.WriteLine("Enter the Contact Id:");
            var contactid = Console.ReadLine();

            // Initialize a client using the validated configuration
            using (var client = new XConnectClient(cfg))
            {
                try
                {
                    // Get a known contact
                    IdentifiedContactReference reference = new IdentifiedContactReference("HIxConnect", contactid);

                    Contact existingContact = await client.GetAsync <Contact>(reference, new ContactExpandOptions(new string[] { PersonalInformation.DefaultFacetKey, EmailAddressList.DefaultFacetKey }));


                    PersonalInformation existingPsnlContactFacet = existingContact.GetFacet <PersonalInformation>(PersonalInformation.DefaultFacetKey);
                    Console.WriteLine();
                    Console.WriteLine();
                    Console.WriteLine("-=-=-=-=-=-=-=-=-Contact Details-=-=-=-=-=-=");
                    Console.WriteLine();
                    Console.WriteLine("Contact ID: " + existingContact.Id.ToString());
                    Console.WriteLine();
                    Console.WriteLine("Contact Name: " + existingPsnlContactFacet.Title + " " + existingPsnlContactFacet.FirstName + " " + existingPsnlContactFacet.LastName);
                    Console.WriteLine();
                    Console.WriteLine("Preferred Langauge: " + existingPsnlContactFacet.PreferredLanguage);
                    Console.WriteLine();
                    EmailAddressList emailAddressListFacet = existingContact.GetFacet <EmailAddressList>(EmailAddressList.DefaultFacetKey);
                    if (emailAddressListFacet != null)
                    {
                        Console.WriteLine("Email Address:" + emailAddressListFacet.PreferredEmail.SmtpAddress);
                    }
                    Console.WriteLine("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
                    #region IP Information
                    IpInfo existingContactIPFacet = existingContact.GetFacet <IpInfo>(IpInfo.DefaultFacetKey);
                    if (existingContactIPFacet != null)
                    {
                        Console.WriteLine("---------===--------===--------IP Information-------====-------===-------");
                        Console.WriteLine("IP used:" + existingContactIPFacet.IpAddress);
                        Console.WriteLine("IP Business Name:" + existingContactIPFacet.BusinessName);
                    }
                    #endregion
                    Console.ReadLine();
                }
                catch (XdbExecutionException ex)
                {
                    // Deal with exception
                }
            }
        }
Ejemplo n.º 17
0
        private static async Task MainAsync(string[] args)
        {
            bool UnitTesting = false;

            #region Setting things up for xConnect

            // (CTW) Getting xConnect settings from config
            var xConnectCertificateConnectionString = ConfigurationManager.AppSettings["xConnectCertificateConnectionString"];
            var xConnectRootUrl = ConfigurationManager.AppSettings["xConnectRootUrl"];

            CertificateWebRequestHandlerModifierOptions options =
                CertificateWebRequestHandlerModifierOptions.Parse(xConnectCertificateConnectionString);
            var certificateModifier = new CertificateWebRequestHandlerModifier(options);

            List <IHttpClientModifier> clientModifiers = new List <IHttpClientModifier>();
            var timeoutClientModifier = new TimeoutHttpClientModifier(new TimeSpan(0, 0, 20));
            clientModifiers.Add(timeoutClientModifier);

            var collectionClient    = new CollectionWebApiClient(new Uri(xConnectRootUrl + "/odata"), clientModifiers, new[] { certificateModifier });
            var searchClient        = new SearchWebApiClient(new Uri(xConnectRootUrl + "/odata"), clientModifiers, new[] { certificateModifier });
            var configurationClient = new ConfigurationWebApiClient(new Uri(xConnectRootUrl + "/configuration"), clientModifiers, new[] { certificateModifier });

            var cfg = new XConnectClientConfiguration(
                new XdbRuntimeModel(CollectionModel.Model), collectionClient, searchClient, configurationClient);

            #endregion

            try
            {
                await cfg.InitializeAsync();

                // Print Poutine if configuration is valid (Thanks Martina)
                var arr = new[]
                {
                    @"__________              __  .__                                   ",
                    @"\______   \____  __ ___/  |_|__| ____   ____   ___________  ______",
                    @" |     ___/  _ \|  |  \   __\  |/    \_/ __ \_/ __ \_  __ \/  ___/",
                    @" |    |  (  <_> )  |  /|  | |  |   |  \  ___/\  ___/|  | \/\___ \ ",
                    @" |____|   \____/|____/ |__| |__|___|  /\___  >\___  >__|  /____  >",
                    @"                                    \/     \/     \/           \/ "
                };

                Console.WindowWidth = 160;
                foreach (string line in arr)
                {
                    Console.WriteLine(line);
                }
            }
            catch (XdbModelConflictException ce)
            {
                Console.WriteLine("ERROR:" + ce.Message);
                return;
            }

            // Initialize a client using the validated configuration
            using (var client = new XConnectClient(cfg))
            {
                while (1 == 1)
                {
                    try
                    {
                        #region Slack Message Onboarding

                        var slackManager = new SlackManager
                        {
                            SlackRootUrl = ConfigurationManager.AppSettings["SlackRootUrl"],
                            OAuthToken   = ConfigurationManager.AppSettings["SlackOAuthToken"]
                        };

                        var messagesJson = string.Empty;
                        if (UnitTesting)
                        {
                            // If unit testing you can use this to debug
                            messagesJson = "{\"ok\":true,\"messages\":[{\"type\":\"message\",\"user\":\"U9HVD2DMJ\",\"text\":\"Ok Poutineers this message is about sitecore commerce\",\"ts\":\"1520047207.000024\"},{\"user\":\"U9HVD2DMJ\",\"text\":\"<@U9HVD2DMJ> has joined the channel\",\"type\":\"message\",\"subtype\":\"channel_join\",\"ts\":\"1520045546.000096\"},{\"user\":\"U9HT438RZ\",\"text\":\"<@U9HT438RZ> has joined the channel\",\"type\":\"message\",\"subtype\":\"channel_join\",\"ts\":\"1520044764.000002\"},{\"user\":\"U9HVAPFMJ\",\"text\":\"<@U9HVAPFMJ> has joined the channel\",\"type\":\"message\",\"subtype\":\"channel_join\",\"ts\":\"1520044582.000044\"}],\"has_more\":false}";
                        }
                        else
                        {
                            messagesJson = slackManager.GetChannelHistory(ConfigurationManager.AppSettings["SlackChannelName"]);
                        }


                        XConnectManager xConnectManager = new XConnectManager
                        {
                            Client = client
                        };

                        // Use JObject to parse it
                        var o = JObject.Parse(messagesJson);
                        foreach (var message in o["messages"].Children())
                        {
                            var userId      = message["user"].ToString();
                            var text        = message["text"].ToString();
                            var ts          = message["ts"].ToString();
                            var messageText = message.ToString();

                            // TO DO: This is where the provider gets loaded
                            #region List Determination Code

                            // passes in additional meta that may assist more advanced providers determine the list
                            var settings = new Dictionary <string, string>
                            {
                                { "full_history", o["messages"].ToString() }
                            };

                            // TO DO: Look up the right provider to load

                            // If not provider specified use the simple one.
                            var    simpleListDeterminationProvider = new SimpleListDeterminationProvider();
                            string listId = simpleListDeterminationProvider.DetermineList(messageText);

                            #endregion

                            // Look up the contact in xDB
                            Contact contact = xConnectManager.GetContactByIndentifier("SLACK", userId, true);

                            // if the contact does not exist then we need to load the profile
                            if (contact == null)
                            {
                                var userJson = slackManager.GetUserProfile(userId);
                                var oUser    = JObject.Parse(userJson);

                                // WARNING: Assuming the way name is parsed. Should really be looking at algorithm for name split.
                                var nameParts = oUser["profile"]["display_name"].ToString().Split(' ');

                                // Save the new contact
                                xConnectManager.InsertContactAndAddContactToList("SLACK", userId, oUser["profile"]["real_name"].ToString(), nameParts[0], (nameParts.Length > 1 ? nameParts[1] : ""), oUser["profile"]["title"].ToString(), oUser["profile"]["email"].ToString(), listId);
                            }
                            else
                            {
                                if (contact.Identifiers.FirstOrDefault(x => x.Source.ToString().ToUpperInvariant() == "SLACK_ALIAS") == null)
                                {
                                    var userJson = slackManager.GetUserProfile(userId);
                                    var oUser    = JObject.Parse(userJson);
                                    client.AddContactIdentifier(contact, new ContactIdentifier("SLACK_ALIAS", oUser["profile"]["real_name"].ToString(), ContactIdentifierType.Known));
                                }

                                // Since contact exists it is possible they already have message so need to check for duplicates.
                                if (contact.ListSubscriptions().Subscriptions.FirstOrDefault(x => x.ListDefinitionId == new Guid(listId)) == null)
                                {
                                    // Add the interaction to the contact
                                    xConnectManager.AddContactToList(contact, listId);
                                }
                            }
                        }

                        #endregion

                        // We will check slack and then rest
                        Console.WriteLine("Waiting");
                        Thread.Sleep(300000);
                    }
                    catch (XdbExecutionException ex)
                    {
                        // Deal with exception
                    }
                }
            }
        }
Ejemplo n.º 18
0
        public override async Task <Customer> Run(Customer customer, CommercePipelineExecutionContext context)
        {
            CertificateWebRequestHandlerModifierOptions options =
                CertificateWebRequestHandlerModifierOptions.Parse("StoreName=My;StoreLocation=LocalMachine;FindType=FindByThumbprint;FindValue=BC9B7186102910E8F34EE8D9F38138203F7555BA");

            var certificateModifier = new CertificateWebRequestHandlerModifier(options);

            List <IHttpClientModifier> clientModifiers = new List <IHttpClientModifier>();
            var timeoutClientModifier = new TimeoutHttpClientModifier(new TimeSpan(0, 0, 20));

            clientModifiers.Add(timeoutClientModifier);

            var collectionClient    = new CollectionWebApiClient(new Uri("https://cateringdemo.xconnect.dev.local/odata"), clientModifiers, new[] { certificateModifier });
            var searchClient        = new SearchWebApiClient(new Uri("https://cateringdemo.xconnect.dev.local/odata"), clientModifiers, new[] { certificateModifier });
            var configurationClient = new ConfigurationWebApiClient(new Uri("https://cateringdemo.xconnect.dev.local/configuration"), clientModifiers, new[] { certificateModifier });

            var cfg = new XConnectClientConfiguration(
                new XdbRuntimeModel(LoyaltyModel.Model), collectionClient, searchClient, configurationClient);

            try
            {
                await cfg.InitializeAsync();
            }
            catch (XdbModelConflictException ce)
            {
                context.Logger.LogError(string.Format("{0}-Error in UpdateCustomerInxDBBlock connecting to xDB : {1}", (object)this.Name, (object)ce.Message), Array.Empty <object>());
            }
            using (var client = new XConnectClient(cfg))
            {
                try
                {
                    IdentifiedContactReference reference = new IdentifiedContactReference("CommerceUser", string.Concat(customer.Domain, "\\", customer.Email));
                    Contact existingContact = client.Get <Contact>(reference, new ContactExpandOptions(new string[] { PersonalInformation.DefaultFacetKey, LoyaltyPointsFacet.DefaultFacetKey, LoyaltyCommerceFacet.DefaultFacetKey }));

                    if (existingContact != null)
                    {
                        //Add an identifier for the contact with the Commerce Customer Id
                        string identifierSource          = "LoyaltyCustomerId";
                        var    loyaltyCustomerIdentifier = existingContact.Identifiers.Where(i => i.Source == identifierSource).FirstOrDefault();
                        if (loyaltyCustomerIdentifier == null)
                        {
                            client.AddContactIdentifier(existingContact, new ContactIdentifier(identifierSource, customer.Id.ToString(), ContactIdentifierType.Known));
                            client.Submit();
                        }

                        //Add or Update Loyalty Points for the customer
                        LoyaltyPointsFacet loyaltyPointFacet = existingContact.GetFacet <LoyaltyPointsFacet>(LoyaltyPointsFacet.DefaultFacetKey);
                        if (loyaltyPointFacet == null)
                        {
                            loyaltyPointFacet = new LoyaltyPointsFacet();
                        }

                        loyaltyPointFacet.PointsEarned = customer.GetComponent <LoyaltyComponent>().PointsEarned;
                        loyaltyPointFacet.PointsSpent  = customer.GetComponent <LoyaltyComponent>().PointsSpent;

                        client.SetFacet <LoyaltyPointsFacet>(existingContact, LoyaltyPointsFacet.DefaultFacetKey, loyaltyPointFacet);
                        client.Submit();

                        //Add or Update the Commerce Customer ID
                        LoyaltyCommerceFacet loyaltyCommerceFacet = existingContact.GetFacet <LoyaltyCommerceFacet>(LoyaltyCommerceFacet.DefaultFacetKey);
                        if (loyaltyCommerceFacet == null)
                        {
                            loyaltyCommerceFacet = new LoyaltyCommerceFacet();
                        }

                        loyaltyCommerceFacet.CommerceCustomerId = customer.Id.ToString();
                        client.SetFacet <LoyaltyCommerceFacet>(existingContact, LoyaltyCommerceFacet.DefaultFacetKey, loyaltyCommerceFacet);
                        client.Submit();
                    }
                }
                catch (XdbExecutionException ex)
                {
                    context.Logger.LogError(string.Format("{0}-Error in UpdateCustomerInxDBBlock updating customer {2} to xDB : {1}", (object)this.Name, (object)ex.Message, customer.Id.ToString()), Array.Empty <object>());
                }
            }
            return(customer);
        }
Ejemplo n.º 19
0
        public static CreateContactViewModel RegisterContact(CreateContactViewModel contactVM)
        {
            CreateContactViewModel conctVMLocal = contactVM;
            // var offlineGoal = Guid.Parse("A9948719-E6E4-46D2-909B-3680E724ECE9");//offline goal - KioskSubmission goal
            // var channelId = Guid.Parse("3FC61BB8-0D9F-48C7-9BBD-D739DCBBE032"); // /sitecore/system/Marketing Control Panel/Taxonomies/Channel/Offline/Store/Enter store - offline enter storl channel
            var goal      = Guid.Parse("D59F316C-8C87-44A9-8347-E66C5A996CF5"); //online goal- directsitesubmission goal
            var channelId = Guid.Parse("B418E4F2-1013-4B42-A053-B6D4DCA988BF"); // /sitecore/system/Marketing Control Panel/Taxonomies/Channel/Online/Direct/Direct - online direct channel
            CertificateWebRequestHandlerModifierOptions options =
                CertificateWebRequestHandlerModifierOptions.Parse("StoreName=My;StoreLocation=LocalMachine;FindType=FindByThumbprint;FindValue=587d948806e57cf511b37a447a2453a02dfd3686");

            // Optional timeout modifier
            var certificateModifier = new CertificateWebRequestHandlerModifier(options);

            List <IHttpClientModifier> clientModifiers = new List <IHttpClientModifier>();
            var timeoutClientModifier = new TimeoutHttpClientModifier(new TimeSpan(0, 0, 20));

            clientModifiers.Add(timeoutClientModifier);

            // This overload takes three client end points - collection, search, and configuration
            var collectionClient    = new CollectionWebApiClient(new Uri("https://sc9.xconnect/odata"), clientModifiers, new[] { certificateModifier });
            var searchClient        = new SearchWebApiClient(new Uri("https://sc9.xconnect/odata"), clientModifiers, new[] { certificateModifier });
            var configurationClient = new ConfigurationWebApiClient(new Uri("https://sc9.xconnect/configuration"), clientModifiers, new[] { certificateModifier });



            var config = new XConnectClientConfiguration(
                new XdbRuntimeModel(CollectionModel.Model), collectionClient, searchClient, configurationClient);

            config.Initialize();


            using (Sitecore.XConnect.Client.XConnectClient client = new XConnectClient(config))
            {
                bool    isExist    = false;
                Contact extContact = client.Get <Contact>(new IdentifiedContactReference("HIxConnect", contactIdentifierPrefix + contactVM.FormEmailAddress), new ContactExpandOptions(new string[] { PersonalInformation.DefaultFacetKey, EmailAddressList.DefaultFacetKey }));
                if (extContact != null)
                {
                    isExist = true;
                }

                try
                {
                    // Identifier for a 'known' contact
                    var identifier = new ContactIdentifier[]
                    {
                        new ContactIdentifier("HIxConnect", contactIdentifierPrefix + contactVM.FormEmailAddress, ContactIdentifierType.Known)
                    };
                    Contact knownContact = null;
                    if (isExist)
                    {
                        knownContact = extContact;
                    }
                    else
                    {
                        // Create a new contact with the identifier
                        knownContact = new Contact(identifier);
                        client.AddContact(knownContact);
                    }
                    //Persona information facet
                    PersonalInformation personalInfoFacet = new PersonalInformation();

                    personalInfoFacet.FirstName = contactVM.FormFirstName;
                    personalInfoFacet.LastName  = contactVM.FormLastName;
                    personalInfoFacet.JobTitle  = contactVM.FormJobTitle;

                    client.SetFacet <PersonalInformation>(knownContact, PersonalInformation.DefaultFacetKey, personalInfoFacet);

                    Interaction interaction = null;
                    if (!isExist)
                    {
                        // Create a new interaction for that contact
                        interaction = new Interaction(knownContact, InteractionInitiator.Contact, channelId, "");

                        // Add events - all interactions must have at least one event
                        var xConnectEvent = new Goal(goal, DateTime.UtcNow);
                        interaction.Events.Add(xConnectEvent);
                    }
                    #region EmailAddress Facet
                    EmailAddressList emails = new EmailAddressList(new EmailAddress(contactVM.FormEmailAddress, true), EmailAddressList.DefaultFacetKey);
                    //OR the following code
                    //var emails = existingContact.GetFacet<EmailAddressList>(EmailAddressList.DefaultFacetKey);
                    //emails.PreferredEmail = new EmailAddress("*****@*****.**", true);
                    client.SetFacet <EmailAddressList>(knownContact, EmailAddressList.DefaultFacetKey, emails);
                    #endregion

                    IpInfo ipInfo = new IpInfo("127.0.0.1");

                    ipInfo.BusinessName = "WebSiteSitecore";

                    client.SetFacet <IpInfo>(interaction, IpInfo.DefaultFacetKey, ipInfo);

                    // Submit contact and interaction - a total of two operations
                    if (!isExist)
                    {
                        // Add the contact and interaction
                        client.AddInteraction(interaction);
                    }
                    client.Submit();

                    var operations = client.LastBatch;
                    contactVM.OperationStatus = "created";
                }
                catch (XdbExecutionException ex)
                {
                    // Manage exception
                    conctVMLocal.OperationStatus = "false";
                }
                catch (Exception ex)
                {
                    conctVMLocal.OperationStatus = "false";
                }
                return(conctVMLocal);
            }
        }
        public override async Task <IssueCouponArgument> Run(IssueCouponArgument arg, CommercePipelineExecutionContext context)
        {
            // Sitecore docs on hitting xConnect in a non-Sitecore context:
            // https://doc.sitecore.net/developers/xp/xconnect/xconnect-client-api/xconnect-client-api-overview/get-client-outside-sitecore.html

            // See https://doc.sitecore.net/developers/privacy-guide/user-contact-customer.html for how you get from Customer to Contact.



            if (!arg.Coupons.Any())
            {
                return(arg);
            }

            LoyaltyPointsPolicy policy = context.GetPolicy <LoyaltyPointsPolicy>();

            if (string.IsNullOrEmpty(policy.XConnectClientCertConnectionString))
            {
                await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().Error, this.Name,
                                                         new Object[] {}, $"{nameof(policy.XConnectClientCertConnectionString)} not set.");

                return(arg);
            }

            if (string.IsNullOrEmpty(policy.XConnectUrl))
            {
                await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().Error, this.Name,
                                                         new Object[] { }, $"{nameof(policy.XConnectUrl)} not set.");

                return(arg);
            }


            CertificateWebRequestHandlerModifierOptions options =
                CertificateWebRequestHandlerModifierOptions.Parse(policy.XConnectClientCertConnectionString);
            var certificateModifier = new CertificateWebRequestHandlerModifier(options);
            List <IHttpClientModifier> clientModifiers = new List <IHttpClientModifier>();
            var timeoutClientModifier = new TimeoutHttpClientModifier(new TimeSpan(0, 0, 20));

            clientModifiers.Add(timeoutClientModifier);

            var collectionClient    = new CollectionWebApiClient(new Uri($"{policy.XConnectUrl}/odata"), clientModifiers, new[] { certificateModifier });
            var searchClient        = new SearchWebApiClient(new Uri($"{policy.XConnectUrl}/odata"), clientModifiers, new[] { certificateModifier });
            var configurationClient = new ConfigurationWebApiClient(new Uri($"{policy.XConnectUrl}/configuration"), clientModifiers, new[] { certificateModifier });

            var cfg = new XConnectClientConfiguration(
                new XdbRuntimeModel(CollectionModel.Model), collectionClient, searchClient, configurationClient);

            try
            {
                await cfg.InitializeAsync();
            }
            catch (XdbModelConflictException ce)
            {
                await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().Error, this.Name,
                                                         new Object[] { ce }, $"{Name}: Exception: {ce.Message} ");

                return(arg);
            }

            using (var client = new XConnectClient(cfg))
            {
                try
                {
                    string externalId = $"CommerceUsers\\{arg.Customer.Email}";
                    var    reference  = new IdentifiedContactReference(Constants.CommerceUser, externalId);

                    Task <Contact> contactTask = client.GetAsync <Contact>(reference, new ContactExpandOptions()
                    {
                    });

                    Contact contact = await contactTask;

                    if (contact == null)
                    {
                        return(arg);
                    }

                    var channel     = policy.ChannelId;
                    var interaction = new Interaction(contact, InteractionInitiator.Brand,
                                                      channel, this.GetType().FullName); // TODO Not sure what a logical device would be for a commerce plugin.  Ask the Slackers.

                    // TODO Replace with custom model, and include coupon entity ID.
                    arg.Coupons.ForEach(
                        couponCode =>
                        interaction.Events.Add(new Event(policy.EventId, DateTime.UtcNow)
                    {
                        Text = "Loyalty points coupon awarded", Data = couponCode, DataKey = "Coupon Code"
                    }));

                    client.AddInteraction(interaction);

                    await client.SubmitAsync();
                }
                catch (XdbExecutionException ex)
                {
                    context.Abort(ex.Message, ex);
                    // Manage exceptions
                }
            }



            return(arg);
        }
Ejemplo n.º 21
0
        //Only Creates new contact
        public void createContact()
        {
            //Goals and Channels to tracke the event - interaction
            var offlineGoal = Guid.Parse("A9948719-E6E4-46D2-909B-3680E724ECE9"); //offline goal - KioskSubmission goal
            var channelId   = Guid.Parse("3FC61BB8-0D9F-48C7-9BBD-D739DCBBE032"); // /sitecore/system/Marketing Control Panel/Taxonomies/Channel/Offline/Store/Enter store - offline enter storl channel

            CertificateWebRequestHandlerModifierOptions options =
                CertificateWebRequestHandlerModifierOptions.Parse("StoreName=My;StoreLocation=LocalMachine;FindType=FindByThumbprint;FindValue=587d948806e57cf511b37a447a2453a02dfd3686");

            // Optional timeout modifier
            var certificateModifier = new CertificateWebRequestHandlerModifier(options);

            List <IHttpClientModifier> clientModifiers = new List <IHttpClientModifier>();
            var timeoutClientModifier = new TimeoutHttpClientModifier(new TimeSpan(0, 0, 20));

            clientModifiers.Add(timeoutClientModifier);

            // This overload takes three client end points - collection, search, and configuration
            var collectionClient    = new CollectionWebApiClient(new Uri("https://sc9.xconnect/odata"), clientModifiers, new[] { certificateModifier });
            var searchClient        = new SearchWebApiClient(new Uri("https://sc9.xconnect/odata"), clientModifiers, new[] { certificateModifier });
            var configurationClient = new ConfigurationWebApiClient(new Uri("https://sc9.xconnect/configuration"), clientModifiers, new[] { certificateModifier });



            var config = new XConnectClientConfiguration(
                new XdbRuntimeModel(CollectionModel.Model), collectionClient, searchClient, configurationClient);

            config.Initialize();

            using (Sitecore.XConnect.Client.XConnectClient client = new XConnectClient(config))
            {
                try
                {
                    // Identifier for a 'known' contact
                    var identifier = new ContactIdentifier[]
                    {
                        new ContactIdentifier("HIxConnect", contactIdentifierPrefix + txtEmailAddress.Text, ContactIdentifierType.Known)
                    };

                    // Create a new contact with the identifier
                    Contact knownContact = new Contact(identifier);
                    client.AddContact(knownContact);


                    #region Personal Information Facet
                    //Persona information facet
                    PersonalInformation personalInfoFacet = new PersonalInformation();
                    personalInfoFacet.FirstName         = txtFName.Text;
                    personalInfoFacet.LastName          = txtLname.Text;
                    personalInfoFacet.MiddleName        = txtMName.Text;
                    personalInfoFacet.PreferredLanguage = ddLanguage.SelectedValue;
                    personalInfoFacet.Title             = ddTitle.SelectedValue;
                    personalInfoFacet.Gender            = ddGender.SelectedValue;
                    personalInfoFacet.JobTitle          = txtJobRole.Text;
                    client.SetFacet <PersonalInformation>(knownContact, PersonalInformation.DefaultFacetKey, personalInfoFacet);
                    #endregion

                    #region Email Address Facet
                    EmailAddressList emails = new EmailAddressList(new EmailAddress(txtEmailAddress.Text, true), EmailAddressList.DefaultFacetKey);
                    client.SetFacet <EmailAddressList>(knownContact, EmailAddressList.DefaultFacetKey, emails);
                    #endregion

                    #region Set Avatar
                    var userAvatar = new Avatar("image/jpeg", userImage);
                    client.SetAvatar(knownContact, userAvatar);
                    #endregion

                    #region Interaction and Event

                    // Create a new interaction for that contact
                    Interaction interaction = new Interaction(knownContact, InteractionInitiator.Contact, channelId, "");

                    // Add events - all interactions must have at least one event
                    var xConnectEvent = new Goal(offlineGoal, DateTime.UtcNow);
                    interaction.Events.Add(xConnectEvent);
                    #endregion


                    // Submit contact and interaction - a total of two operations

                    // Add the contact and interaction
                    client.AddInteraction(interaction);

                    client.Submit();
                    #region Displaying Operations
                    var operations = client.LastBatch;



                    // Loop through operations and check status
                    foreach (var operation in operations)
                    {
                        ltrl_status.Text += operation.OperationType + operation.Target.GetType().ToString() + " Operation: " + operation.Status + "<br/>";
                    }
                    #endregion
                }
                catch (XdbExecutionException ex)
                {
                    // Manage exception
                    ltrl_status.Text += "Error Occured:" + ex.Message + "<br/>" + ex.StackTrace;
                }
                catch (Exception ex)
                {
                    ltrl_status.Text += "Error Occured:" + ex.Message + "<br/>" + ex.StackTrace;
                }
            }
        }
Ejemplo n.º 22
0
        private static async Task ProcessCustomers()
        {
            CertificateWebRequestHandlerModifierOptions options =
                CertificateWebRequestHandlerModifierOptions.Parse("StoreName=My;StoreLocation=LocalMachine;FindType=FindByThumbprint;FindValue=BC9B7186102910E8F34EE8D9F38138203F7555BA");

            var certificateModifier = new CertificateWebRequestHandlerModifier(options);

            List <IHttpClientModifier> clientModifiers = new List <IHttpClientModifier>();
            var timeoutClientModifier = new TimeoutHttpClientModifier(new TimeSpan(0, 0, 20));

            clientModifiers.Add(timeoutClientModifier);

            var collectionClient    = new CollectionWebApiClient(new Uri("https://cateringdemo.xconnect.dev.local/odata"), clientModifiers, new[] { certificateModifier });
            var searchClient        = new SearchWebApiClient(new Uri("https://cateringdemo.xconnect.dev.local/odata"), clientModifiers, new[] { certificateModifier });
            var configurationClient = new ConfigurationWebApiClient(new Uri("https://cateringdemo.xconnect.dev.local/configuration"), clientModifiers, new[] { certificateModifier });

            var cfg = new XConnectClientConfiguration(
                new XdbRuntimeModel(LoyaltyModel.Model), collectionClient, searchClient, configurationClient);

            try
            {
                await cfg.InitializeAsync();
            }
            catch (XdbModelConflictException ce)
            {
                System.Console.WriteLine("ERROR:" + ce.Message);
                return;
            }

            using (var client = new XConnectClient(cfg))
            {
                try
                {
                    //search for an existing contact based on an identifier
                    IdentifiedContactReference reference = new IdentifiedContactReference("CommerceUser", "Storefront\\[email protected]");
                    Contact existingContact = client.Get <Contact>(reference, new ContactExpandOptions(new string[] { PersonalInformation.DefaultFacetKey, LoyaltyPointsFacet.DefaultFacetKey, LoyaltyCommerceFacet.DefaultFacetKey }));

                    if (existingContact != null)
                    {
                        LoyaltyPointsFacet loyaltyPointFacet = existingContact.GetFacet <LoyaltyPointsFacet>(LoyaltyPointsFacet.DefaultFacetKey);

                        if (loyaltyPointFacet == null)
                        {
                            loyaltyPointFacet = new LoyaltyPointsFacet()
                            {
                                PointsEarned = 33,
                                PointsSpent  = 44
                            };
                            client.SetFacet <LoyaltyPointsFacet>(existingContact, LoyaltyPointsFacet.DefaultFacetKey, loyaltyPointFacet);

                            client.Submit();
                        }

                        LoyaltyCommerceFacet loyaltyCommerceFacet = existingContact.GetFacet <LoyaltyCommerceFacet>(LoyaltyCommerceFacet.DefaultFacetKey);
                        if (loyaltyCommerceFacet == null)
                        {
                            loyaltyCommerceFacet = new LoyaltyCommerceFacet()
                            {
                                CommerceCustomerId = "001"
                            };
                            client.SetFacet <LoyaltyCommerceFacet>(existingContact, LoyaltyCommerceFacet.DefaultFacetKey, loyaltyCommerceFacet);

                            client.Submit();
                        }
                    }

                    //Get all contacts and process them
                    //var contacts = client.Contacts.WithExpandOptions(new ContactExpandOptions(PersonalInformation.DefaultFacetKey)).ToEnumerable();
                    ////var contacts = client.Contacts.ToEnumerable();
                    //foreach (var contact in contacts)
                    //{
                    //    Console.WriteLine("Contact ID: " + contact.Id.ToString());

                    //    var rsonalInformationFacet = contact.GetFacet<PersonalInformation>();
                    //    PersonalInformation personalInformationFacet = contact.GetFacet<PersonalInformation>(PersonalInformation.DefaultFacetKey);
                    //    if (personalInformationFacet != null)
                    //        Console.WriteLine("Contact Name: " + personalInformationFacet.FirstName + " " + personalInformationFacet.LastName);
                    //    else
                    //        Console.WriteLine("Contact Personal Information not found.");

                    //    LoyaltyPointsFacet loyaltyPointFacet = contact.GetFacet<LoyaltyPointsFacet>(LoyaltyPointsFacet.DefaultFacetKey);

                    //    if (loyaltyPointFacet == null)
                    //    {
                    //        Console.WriteLine("Contact Loyalty Information not found.");
                    //        LoyaltyPointsFacet visitorInfo = new LoyaltyPointsFacet()
                    //        {
                    //            PointsEarned = 0,
                    //            PointsSpent = 0
                    //        };
                    //        client.SetFacet<LoyaltyPointsFacet>(contact, LoyaltyPointsFacet.DefaultFacetKey, visitorInfo);
                    //    }
                    //    else
                    //        Console.WriteLine("Contact Loyalty Found: " + loyaltyPointFacet.PointsEarned);


                    //}

                    Console.ReadLine();
                }
                catch (XdbExecutionException ex)
                {
                    System.Console.WriteLine("ERROR:" + ex.Message);
                    return;
                }
            }
        }