Ejemplo n.º 1
0
        public async Task <RecoResult> Recommendtion(string id)
        {
            var result = new RecoResult();

            using (XConnectClient client
                       = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
            {
                var reference = new ContactReference(Guid.Parse(id));

                var expandOptions = new ContactExpandOptions(CollectionModel.FacetKeys.PersonalInformation, ProductRecommendationFacet.DefaultFacetKey)
                {
                    Interactions = new RelatedInteractionsExpandOptions()
                };

                Task <Contact> contactTask = client.GetAsync <Contact>(reference, expandOptions);

                Contact contact = await contactTask;

                if (contact != null)
                {
                    result.FirstName = contact.Personal()?.FirstName;
                    result.LastName  = contact.Personal()?.LastName;
                    var purchaseOutcome = contact.Interactions.Select(i => i.Events.OfType <ProductPurchasedOutcome>()).FirstOrDefault();
                    result.PurchasedProductId = purchaseOutcome.FirstOrDefault().ProductId;
                    var recommendationFacet = contact.GetFacet <ProductRecommendationFacet>();
                    if (recommendationFacet != null)
                    {
                        result.Recommends = recommendationFacet.ProductRecommendations;
                    }
                }
            }
            return(result);
        }
     internal Contact GetContactByOptions(Guid contactId, ExpandOptions options = null)
     {
         using (XConnectClient client = SitecoreXConnectClientConfiguration.GetClient("xconnect/clientconfig"))
         {
             if (options == null)
             {
                 options = (ExpandOptions) new ContactExpandOptions(Array.Empty <string>())
                 {
                     Interactions = new RelatedInteractionsExpandOptions(new string[1]
                     {
                         "IpInfo"
                     })
                 }
             }
             ;
             ContactReference contactReference = new ContactReference(contactId);
             Contact          contact          = XConnectSynchronousExtensions.Get <Contact>((IXdbContext)client, (IEntityReference <Contact>)contactReference, options);
             if (contact == null)
             {
                 throw new ContactNotFoundException(string.Format("No Contact with id [{0}] found", (object)contactId));
             }
             return(contact);
         }
     }
 }
Ejemplo n.º 3
0
    static void Main()
    {
        Event myEvent = new Event();

        ContactReference myContactReference = new ContactReference("*****@*****.**");
        myContactReference.setName("John Doe");

        myEvent.setOrganizer(myContactReference);
    }
Ejemplo n.º 4
0
    static void Main()
    {
        Event myEvent = new Event();

        ContactReference myContactReference = new ContactReference("*****@*****.**");

        myContactReference.setName("John Doe");

        myEvent.setOrganizer(myContactReference);
    }
        /// <summary>
        /// Gets a contact from the xDb using xConnect
        /// </summary>
        /// <param name="contactId"></param>
        /// <returns></returns>
        public Contact GetContact(string contactId)
        {
            var reference = new ContactReference(Guid.Parse(contactId));

            Sitecore.XConnect.Contact xConnectContact = Client.Get(reference, new ContactExpandOptions()
            {
            });

            // TO DO: If there are any other fields to add

            return(xConnectContact);
        }
Ejemplo n.º 6
0
 public Contact GetContact(Guid contactId, string[] facets)
 {
     using (XConnectClient client = SitecoreXConnectClientConfiguration.GetClient("xconnect/clientconfig"))
     {
         ContactReference contactReference = new ContactReference(contactId);
         Contact          contact          = facets == null || facets.Length == 0 ? client.Get <Contact>((IEntityReference <Contact>)contactReference, (ExpandOptions) new ContactExpandOptions(Array.Empty <string>())) : client.Get <Contact>((IEntityReference <Contact>)contactReference, (ExpandOptions) new ContactExpandOptions(facets));
         if (contact == null)
         {
             throw new ContactNotFoundException(string.Format("No Contact with id [{0}] found", (object)contactId));
         }
         return(contact);
     }
 }
Ejemplo n.º 7
0
        public static async Task <bool?> isConsented(Sitecore.Analytics.Tracking.Contact contact, SiteContext context)
        {
            Boolean?isConsented = null;

            if (contact != null && context != null)
            {
                using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
                {
                    try
                    {
                        var            contactReference = new ContactReference(contact.ContactId);
                        Task <Contact> contactTask      = client.GetContactAsync(contactReference, new ContactExpandOptions()
                        {
                        });

                        Contact XContact = await contactTask;

                        var facet = XContact.GetFacet <ConsentInfo>(ConsentInfo.DefaultFacetKey);

                        if (facet != null)
                        {
                            if (facet.Consents != null)
                            {
                                Item           rootItem            = Sitecore.Context.Database.GetItem(context.RootPath);
                                ReferenceField xconsentPolicyField = rootItem.Fields["XConsent Policy"];
                                Item           xconsentPolicy      = xconsentPolicyField.TargetItem;

                                ConsentObject obj = facet.Consents.FirstOrDefault <ConsentObject>(x => x.rootId.Equals(rootItem.ID) &&
                                                                                                  x.language.Equals(context.Language) &&
                                                                                                  x.policyId.Equals(xconsentPolicy.ID) &&
                                                                                                  x.policyVersion.Equals(xconsentPolicy.Version.Number));
                                if (obj != null && obj.consent)
                                {
                                    isConsented = true;
                                }
                                else if (obj != null && !obj.consent)
                                {
                                    isConsented = false;
                                }
                            }
                        }
                    }
                    catch (XdbExecutionException ex)
                    {
                        //do something
                    }
                }
            }
            return(isConsented);
        }
Ejemplo n.º 8
0
        private async Task BtnSaveReferenceCommandAsync()
        {
            var pop = await _dialogService.OpenLoadingPopup();

            ContactReference reference = new ContactReference
            {
                EmployerName  = _employer,
                Position      = _position,
                ReferenceName = _referenceName,
                Relationship  = _relationship,
                Phone         = _phone,
                Contacted     = _isContacted,
            };
            Dictionary <string, object> obj = await _candidateDetailsService.AddReference(reference);

            if (obj != null)
            {
                try
                {
                    if (obj["Success"].ToString() == "true") //success
                    {
                        await _dialogService.PopupMessage("Add new Reference Successefully", "#52CD9F", "#FFFFFF");

                        await PopupNavigation.Instance.PopAllAsync();

                        await _navigationService.NavigateToAsync <CandidateMainViewModel>();
                    }
                    else if (obj["Success"].ToString() == "false")
                    {
                        if (obj["Message"].ToString() == "Fail")
                        {
                            await _dialogService.PopupMessage("An error has occurred, please try again!!", "#CF6069", "#FFFFFF");
                        }
                        else if (obj["Message"].ToString() == "AttachFail")
                        {
                            await _dialogService.PopupMessage("Attach file Fail, please try again!!", "#CF6069", "#FFFFFF");
                        }
                    }
                }
                catch
                {
                    await _dialogService.PopupMessage("An error has occurred, please try again!!", "#CF6069", "#FFFFFF");

                    await _dialogService.CloseLoadingPopup(pop);
                }
            }
            await _dialogService.CloseLoadingPopup(pop);
        }
Ejemplo n.º 9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void OnClick_LoadContact(object sender, EventArgs e)
        {
            using (var client = _xConnectClientFactory.GetXConnectClient())
            {
                try
                {
                    ContactReference           contactReference           = null;
                    IdentifiedContactReference identifiedContactReference = null;

                    identifiedContactReference = new IdentifiedContactReference("ListManager", tbContactIdentifierValue.Text);

                    var selectedFacetKeys = new List <string>();
                    foreach (ListItem lbFacetsItem in lbFacets.Items)
                    {
                        if (lbFacetsItem.Selected)
                        {
                            selectedFacetKeys.Add(lbFacetsItem.Value);
                        }
                    }

                    Contact contact = client.Get((IEntityReference <Contact>)contactReference ?? identifiedContactReference, new ContactExpandOptions(selectedFacetKeys.ToArray())
                    {
                        Interactions = new RelatedInteractionsExpandOptions()
                        {
                            StartDateTime = DateTime.MinValue,
                            Limit         = int.MaxValue
                        }
                    });

                    var serializerSettings = new JsonSerializerSettings
                    {
                        ContractResolver = new XdbJsonContractResolver(client.Model,
                                                                       serializeFacets: chkIncludeFacets.Checked,
                                                                       serializeContactInteractions: chkIncludeInteractions.Checked),
                        DateTimeZoneHandling = DateTimeZoneHandling.Utc,
                        DefaultValueHandling = DefaultValueHandling.Ignore,
                        Formatting           = Formatting.Indented
                    };

                    Json          = JsonConvert.SerializeObject(contact, serializerSettings);
                    lblError.Text = string.Empty;
                }
                catch (Exception ex)
                {
                    lblError.Text = ex.ToString();
                }
            }
        }
Ejemplo n.º 10
0
        public async Task <ContactDto> GetContact(Guid contactId)
        {
            using (XConnectClient client = GetClient())
            {
                ContactDto result = new ContactDto();
                try
                {
                    ContactReference reference = new ContactReference(contactId);
                    var contactTask            = client.GetAsync <Contact>(
                        reference,
                        new ContactExpandOptions(
                            PersonalInformation.DefaultFacetKey,
                            EmailAddressList.DefaultFacetKey,
                            PhoneNumberList.DefaultFacetKey,
                            Avatar.DefaultFacetKey)
                        );

                    var contact = await contactTask;

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

                    result.ContactId           = contact.Id ?? Guid.Empty;
                    result.PersonalInformation = new PersonalDto(contact.Personal());
                    result.Email    = contact.Emails()?.PreferredEmail?.SmtpAddress;
                    result.Phone    = contact.PhoneNumbers()?.PreferredPhoneNumber?.Number;
                    result.IsAvatar = contact.Avatar() != null && contact.Avatar().Picture != null;
                    if (result.IsAvatar)
                    {
                        result.Avatar = contact.Avatar().Picture;
                    }
                    return(result);
                }
                catch (XdbExecutionException ex)
                {
                    Sitecore.Diagnostics.Log.Error(ex.Message, this);
                }
            }

            return(null);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Adds profile ids to a contacts "contact list" with filtering its own
        /// profile id and preventing doubletts.
        /// </summary>
        /// <param name="contact"> The contact (source of the link). </param>
        /// <param name="profileIds"> The profile ids to be added as link targets. </param>
        /// <param name="baseline"> The baseline. </param>
        /// <param name="added"> The number of targets added so far. </param>
        /// <returns> The number of links added </returns>
        private int AddContactIdsToStdContact(StdContact contact, List <string> profileIds, IEnumerable <MatchingEntry> baseline, int added)
        {
            var profileIdentifierType = this.WebSideParameters.ProfileIdentifierType;

            contact.Contacts = contact.Contacts ?? new List <ContactReference>(profileIds.Count);

            foreach (var extract in profileIds)
            {
                var profileId = string.Format(this.WebSideParameters.ProfileIdFormatter, extract);
                var stdId     =
                    (from x in baseline
                     where x.ProfileId.GetProfileId(profileIdentifierType) == profileId
                     select x.Id).FirstOrDefault();

                // we ignore contacts we donn't know
                if (stdId == default(Guid))
                {
                    continue;
                }

                // lookup an existing entry in this contacts contact-list
                var contactInList = (from x in contact.Contacts where x.Target == stdId select x).FirstOrDefault();

                if (contactInList == null)
                {
                    // add a new one if no existing entry has been found
                    contactInList = new ContactReference {
                        Target = stdId
                    };
                    contact.Contacts.Add(contactInList);
                    added++;
                }

                // update the flag that this entry is a private contact
                var connectorDescriptionAttribute = this.ConnectorDescription;
                contactInList.IsPrivateContact  = connectorDescriptionAttribute.ContentIsPrivate;
                contactInList.IsBusinessContact = connectorDescriptionAttribute.ContentIsBusiness;
            }

            return(added);
        }
        public Contact GetContactById(Guid contactId)
        {
            Contact toReturn = null;

            if (contactId != Guid.Empty)
            {
                try
                {
                    var contactReference = new ContactReference(contactId);
                    if (contactReference != null)
                    {
                        toReturn = Client.Get(contactReference, new ContactExpandOptions()
                        {
                        });
                    }
                }
                catch (Exception ex)
                {
                    Errors.Add(ex.Message);
                }
            }

            return(toReturn);
        }
Ejemplo n.º 13
0
        public async Task <IReadOnlyDictionary <string, Facet> > GetContactFacets(Guid contactId)
        {
            using (XConnectClient client = GetClient())
            {
                try
                {
                    var availableFacetDefinitions = client.Model.Facets.Where(f => f.Target == EntityType.Contact);

                    List <string> availableKeys = new List <string>();
                    foreach (var defenition in availableFacetDefinitions)
                    {
                        availableKeys.Add(defenition.Name);
                    }

                    ContactReference reference = new ContactReference(contactId);
                    var contactTask            = client.GetAsync <Contact>(
                        reference,
                        new ContactExpandOptions(availableKeys.ToArray())
                        );

                    var contact = await contactTask;

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

                    return(contact.Facets);
                }
                catch (XdbExecutionException ex)
                {
                }
            }

            return(null);
        }
Ejemplo n.º 14
0
        public async Task <dynamic> AddReference(ContactReference reference)
        {
            var result = await _requestService.postDataFromServiceAuthority("api/CandidateDetails/AddEditContactReferences", reference);

            return(result);
        }
Ejemplo n.º 15
0
        public static async void setConsented(Sitecore.Analytics.Tracking.Contact contact, SiteContext context, Boolean consent)
        {
            if (contact != null && context != null)
            {
                Item           rootItem            = Sitecore.Context.Database.GetItem(context.RootPath);
                ReferenceField xconsentPolicyField = rootItem.Fields["XConsent Policy"];
                Item           xconsentPolicy      = xconsentPolicyField.TargetItem;

                if (rootItem != null && xconsentPolicy != null)
                {
                    using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
                    {
                        try
                        {
                            var            contactReference = new ContactReference(contact.ContactId);
                            Task <Contact> contactTask      = client.GetContactAsync(contactReference, new ContactExpandOptions()
                            {
                            });

                            Contact XContact = await contactTask;

                            var facet = XContact.GetFacet <ConsentInfo>(ConsentInfo.DefaultFacetKey);


                            if (facet != null)
                            {
                                if (facet.Consents != null)
                                {
                                    ConsentObject obj = facet.Consents.FirstOrDefault <ConsentObject>(x => x.rootId.Equals(rootItem.ID) &&
                                                                                                      x.language.Equals(context.Language) &&
                                                                                                      x.policyId.Equals(xconsentPolicy.ID) &&
                                                                                                      x.policyVersion.Equals(xconsentPolicy.Version.Number));

                                    if (obj != null)
                                    {
                                        obj.consent = consent;
                                    }
                                    else
                                    {
                                        facet.Consents.Add(new ConsentObject(rootItem.ID, xconsentPolicy.ID, xconsentPolicy.Version.Number, context.Language, consent));
                                    }

                                    // Set the updated facet
                                    client.SetFacet(XContact, ConsentInfo.DefaultFacetKey, facet);
                                }
                            }
                            else
                            {
                                facet = new ConsentInfo();
                                facet.Consents.Add(new ConsentObject(rootItem.ID, xconsentPolicy.ID, xconsentPolicy.Version.Number, context.Language, consent));
                            }

                            await client.SubmitAsync();
                        }
                        catch (XdbExecutionException ex)
                        {
                            // Handle exception
                        }
                    }
                }
            }
        }
Ejemplo n.º 16
0
        protected override void Execute(CodeActivityContext executionContext)
        {
            //Create the tracing service
            ITracingService tracingService = executionContext.GetExtension <ITracingService>();

            //Create the context
            IWorkflowContext            context        = executionContext.GetExtension <IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            tracingService.Trace("Loaded UpsertSupplierWorkflow");
            tracingService.Trace("CREATING Contact object with the input values");
            tracingService.Trace("Checkpoint 1");

            Contact contact = new Contact();

            int partyid = PartyID.Get <int>(executionContext);


            tracingService.Trace("Starting assigning attribute variables.");

            contact.First_Name = FirstName.Get <string>(executionContext).ToString();
            tracingService.Trace("First Name Populated");

            tracingService.Trace(string.Format("Setting party id = {0}", partyid));
            contact.Party_Id = partyid;
            tracingService.Trace("Party ID populated");

            contact.Last_Name = LastName.Get <string>(executionContext).ToString();
            tracingService.Trace("Last Name Populated");

            contact.Payment_Method = PaymentMethod.Get <string>(executionContext).ToString();
            tracingService.Trace("Payment Method Populated");

            contact.SIN = SIN.Get <string>(executionContext).ToString();
            tracingService.Trace("SIN Populated");

            contact.Address1 = Address1.Get <string>(executionContext).ToString();
            tracingService.Trace("Address1 Populated");

            contact.Country_Code = Country.Get <string>(executionContext).ToString();
            tracingService.Trace("Country Populated");

            contact.City = City.Get <string>(executionContext).ToString();
            tracingService.Trace("City Populated");

            contact.Province_Code = Province.Get <string>(executionContext).ToString();
            tracingService.Trace("Province Populated");

            contact.Postal_Code = PostalCode.Get <string>(executionContext).ToString();
            tracingService.Trace("Postal Code Populated");
            tracingService.Trace("Checkpoint 2");


            EntityReference contactRef = ContactReference.Get <EntityReference>(executionContext);

            contact.ID = contactRef.Id;

            tracingService.Trace("Fetching the Configs");
            ////Get the configuration record for Oracle_T4A group from the configs entity and get the connection value from the record.
            var configs = Helper.GetSystemConfigurations(service, ConfigEntity.Group.ORACLE_T4A, string.Empty);

            tracingService.Trace("Fetching Connection");
            string connection = Helper.GetConfigKeyValue(configs, ConfigEntity.Key.CONNECTION, ConfigEntity.Group.ORACLE_T4A);

            try
            {
                tracingService.Trace("Fetching Oracle Response by making call to Helper.UpsertSupplierInOracle()");
                OracleResponse response = Helper.UpsertSupplierInOracle(contact, connection, tracingService);

                if (response.TransactionCode == OracleResponse.T4A_STATUS.OK)
                {
                    tracingService.Trace("Inside OracleResponse.T4A_STATUS.OK \nRetriving and setting response values to output");
                    PartyID.Set(executionContext, response.PartyId);
                    tracingService.Trace("Party ID Output Param is set");
                }

                tracingService.Trace("Setting up transaction code and transaction message");
                TransactionCode.Set(executionContext, response.TransactionCode.Trim());
                TransactionMessage.Set(executionContext, response.TransactionMessage);
            }
            catch (InvalidWorkflowException ex)
            {
                Helper.LogIntegrationError(service, ErrorType.CONTACT_ERROR, IntegrationErrorCodes.UPSERT_SUPPLIER.GetIntValue(), Strings.T4A_FER_ERROR,
                                           string.Format("Error Description: {0} ", ex.Message), contactRef);
            }
            catch (Exception ex)
            {
                Helper.LogIntegrationError(service, ErrorType.CONTACT_ERROR, IntegrationErrorCodes.UPSERT_SUPPLIER.GetIntValue(), Strings.T4A_FER_ERROR,
                                           string.Format("Error Description: {0} ", ex.Message), contactRef);
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Implements the method to fill the contact with additional links to other contacts.
        /// </summary>
        /// <param name="contactToFill"> The contact to be filled. </param>
        /// <param name="baseline"> The baseline that does contain possible link targets. </param>
        /// <returns> the manipulated contact </returns>
        public override StdElement FillContacts(StdElement contactToFill, ICollection <MatchingEntry> baseline)
        {
            var contact = contactToFill as StdContact;
            const ProfileIdentifierType ProfileIdentifierType = ProfileIdentifierType.WerKenntWenUrl;
            const string ProfilePhpId = "/person/";

            if (contact == null || !contact.ExternalIdentifier.ContainsKey(ProfileIdentifierType))
            {
                return(contactToFill);
            }

            var profileIdInformation = contact.ExternalIdentifier[ProfileIdentifierType];

            if (profileIdInformation == null || string.IsNullOrWhiteSpace(profileIdInformation.Id))
            {
                return(contactToFill);
            }

            var offset = 0;
            var added  = 0;

            while (true)
            {
                this.LogProcessingEvent("reading contacts ({0})", offset);
                this.HttpRequester.ContentCredentials = this;

                // get the contact list
                var url = string.Format(
                    CultureInfo.InvariantCulture,
                    "http://www.wer-kennt-wen.de/people/friends/{0}/sort/friends/0/0/{1}",
                    profileIdInformation.Id.Replace(ProfilePhpId, string.Empty),
                    offset);

                string profileContent;
                while (true)
                {
                    profileContent = this.HttpRequester.GetContent(url, string.Format(CultureInfo.InvariantCulture, "Wkw-{0}", offset));
                    if (profileContent.Contains(@"id=""loginform"""))
                    {
                        if (!this.GetLogon())
                        {
                            return(contactToFill);
                        }

                        continue;
                    }

                    if (profileContent.Contains(WkwCaptcha))
                    {
                        this.ResolveCaptcha();
                        continue;
                    }

                    break;
                }

                var extracts = Regex.Matches(profileContent, @"\<a href=""/person/(?<profileId>[0-9a-zA-Z]*)""\>", RegexOptions.Singleline);

                // if there is no contact in list, we did reach the end
                if (extracts.Count < 3)
                {
                    break;
                }

                // create a new instance of a list of references if there is none
                contact.Contacts = contact.Contacts ?? new List <ContactReference>(extracts.Count);

                foreach (Match extract in extracts)
                {
                    var profileId = ProfilePhpId + extract.Groups["profileId"];
                    var stdId     =
                        (from x in baseline
                         where x.ProfileId.GetProfileId(ProfileIdentifierType) == profileId
                         select x.Id).FirstOrDefault();

                    // we ignore contacts we donn't know
                    if (stdId == default(Guid))
                    {
                        continue;
                    }

                    // lookup an existing entry in this contacts contact-list
                    var contactInList = (from x in contact.Contacts where x.Target == stdId select x).FirstOrDefault();

                    if (contactInList == null)
                    {
                        // add a new one if no existing entry has been found
                        contactInList = new ContactReference {
                            Target = stdId
                        };
                        contact.Contacts.Add(contactInList);
                        added++;
                    }

                    // update the flag that this entry is a private contact
                    // todo: private/business contact
                    contactInList.IsPrivateContact = true;
                }

                Thread.Sleep(new Random().Next(230, 8789));

                offset += 64; // extracts.Count;
            }

            this.LogProcessingEvent(contact, "{0} contacts found, {1} new added", offset, added);

            return(contactToFill);
        }
Ejemplo n.º 18
0
        public HttpResponseMessage GetContactData(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return(new HttpResponseMessage(HttpStatusCode.NotFound));
            }
            try
            {
                Guid contactId = new Guid(id);
                using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
                {
                    try
                    {
                        var contactReference = new ContactReference(contactId);

                        // Get all available contact facets in current model
                        var contactFacets = client.Model.Facets.Where(c => c.Target == EntityType.Contact).Select(x => x.Name);

                        // Get all available interaction facets in current model
                        var interactionFacets = client.Model.Facets.Where(c => c.Target == EntityType.Interaction).Select(x => x.Name);

                        var contact = client.Get <Contact>(contactReference, new ContactExpandOptions(contactFacets.ToArray())
                        {
                            Interactions = new RelatedInteractionsExpandOptions(interactionFacets.ToArray())
                            {
                                // Get all interactions
                                EndDateTime   = DateTime.MaxValue,
                                StartDateTime = DateTime.MinValue
                            }
                        });


                        // Serialize response
                        // Note special XdbJsonContractResolver - mandatory for serializing xConnect entities
                        var serializerSettings = new JsonSerializerSettings
                        {
                            ContractResolver = new XdbJsonContractResolver(client.Model,
                                                                           serializeFacets: true,
                                                                           serializeContactInteractions: true),
                            Formatting           = Formatting.Indented,
                            DateTimeZoneHandling = DateTimeZoneHandling.Utc,
                            DefaultValueHandling = DefaultValueHandling.Ignore
                        };

                        string allData   = JsonConvert.SerializeObject(contact, serializerSettings);
                        var    fileBytes = Encoding.Default.GetBytes(allData);
                        var    response  = new HttpResponseMessage(HttpStatusCode.OK)
                        {
                            Content = new ByteArrayContent(fileBytes)
                        };

                        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                        {
                            FileName = "ContactData.json",
                        };

                        response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                        return(response);
                    }
                    catch (XdbExecutionException)
                    {
                        return(new HttpResponseMessage(HttpStatusCode.NotFound));
                    }
                }
            }
            catch (XdbExecutionException)
            {
                return(new HttpResponseMessage(HttpStatusCode.NotFound));
            }
        }
Ejemplo n.º 19
0
        public async Task <bool> UpdateContactFacet(FacetDto facet)
        {
            using (XConnectClient client = GetClient())
            {
                try
                {
                    var availableFacetDefinitions = client.Model.Facets.Where(f => f.Target == EntityType.Contact);

                    List <string> availableKeys = new List <string>();
                    foreach (var defenition in availableFacetDefinitions)
                    {
                        availableKeys.Add(defenition.Name);
                    }

                    ContactReference reference = new ContactReference(Guid.Parse(facet.ContactId));
                    var contactTask            = client.GetAsync <Contact>(
                        reference,
                        new ContactExpandOptions(availableKeys.ToArray())
                        );

                    var contact = await contactTask;

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

                    var facets = contact.Facets;
                    foreach (var f in facets)
                    {
                        var facetName = f.Key;

                        if (facetName == facet.FacetName)
                        {
                            Type type = f.Value.GetType();
                            if (string.IsNullOrEmpty(facet.Container))
                            {
                                var property = type.GetProperty(facet.FieldName);
                                if (property == null)
                                {
                                    return(false);
                                }
                                property.SetValue(f.Value, Convert.ChangeType(facet.Value, property.PropertyType),
                                                  null);
                            }
                            else
                            {
                                var          paths = facet.Container.Split(new[] { "$" }, StringSplitOptions.RemoveEmptyEntries).ToList();
                                PropertyInfo property;
                                while (paths.Count > 0)
                                {
                                    var current = paths[0];
                                    paths.RemoveAt(0);
                                    property = type.GetProperty(current);
                                    if (property != null)
                                    {
                                        var value = property.GetValue(f.Value);
                                        type     = property.PropertyType;
                                        property = type.GetProperty(facet.FieldName);
                                        if (property != null)
                                        {
                                            property.SetValue(value, Convert.ChangeType(facet.Value, property.PropertyType), null);
                                        }
                                    }
                                }
                            }
                            client.SetFacet <Facet>(contact, facet.FacetName, f.Value);
                            await client.SubmitAsync();

                            return(true);
                        }
                    }
                }
                catch (XdbExecutionException ex)
                {
                }
            }

            return(false);
        }
Ejemplo n.º 20
0
        public async Task <bool> UpdateContactInformation(
            Guid contactId,
            string firstName,
            string middleName,
            string lastName,
            string title,
            string jobTitle,
            string phone,
            string email,
            string gender,
            byte[] avatar = null)
        {
            using (XConnectClient client = GetClient())
            {
                try
                {
                    ContactReference reference = new ContactReference(contactId);

                    var contactTask = client.GetAsync <Contact>(
                        reference,
                        new ContactExpandOptions(
                            PersonalInformation.DefaultFacetKey,
                            EmailAddressList.DefaultFacetKey,
                            PhoneNumberList.DefaultFacetKey,
                            Avatar.DefaultFacetKey)
                        );

                    Contact contact = await contactTask;

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

                    var personal = contact.Personal();

                    if (personal == null)
                    {
                        personal = new PersonalInformation();
                    }

                    personal.FirstName  = firstName;
                    personal.MiddleName = middleName;
                    personal.LastName   = lastName;
                    personal.Title      = title;
                    personal.JobTitle   = jobTitle;
                    personal.Gender     = gender;

                    var phoneNumbers         = contact.PhoneNumbers();
                    var preferredPhoneNumber = new PhoneNumber(string.Empty, phone);

                    if (phoneNumbers == null)
                    {
                        phoneNumbers = new PhoneNumberList(preferredPhoneNumber, "Work phone");
                    }
                    else
                    {
                        phoneNumbers.PreferredPhoneNumber = preferredPhoneNumber;
                    }

                    var emails         = contact.Emails();
                    var preferredEmail = new EmailAddress(email, true);

                    if (emails == null)
                    {
                        emails = new EmailAddressList(preferredEmail, "Work email");
                    }
                    else
                    {
                        emails.PreferredEmail = preferredEmail;
                    }

                    if (avatar != null)
                    {
                        var avatarFacet = contact.Avatar();

                        if (avatarFacet == null)
                        {
                            avatarFacet = new Avatar("image/jpeg", avatar);
                        }
                        else
                        {
                            avatarFacet.Picture = avatar;
                        }

                        client.SetAvatar(contact, avatarFacet);
                    }

                    client.SetPhoneNumbers(contact, phoneNumbers);
                    client.SetPersonal(contact, personal);
                    client.SetEmails(contact, emails);

                    await client.SubmitAsync();

                    return(true);
                }
                catch (XdbExecutionException ex)
                {
                    return(false);
                }
            }
        }
Ejemplo n.º 21
0
        public void FillAllContacts(ICollection <StdElement> contactsToFill, ICollection <MatchingEntry> baseline)
        {
            var offset = 0;

            while (true)
            {
                var content = this.GetTextContent(string.Format(HttpUrlProfileContacts, offset), string.Empty);
                var results = Regex.Matches(content, PatternGetContactContacts, RegexOptions.Singleline);

                if (results.Count == 0)
                {
                    return;
                }

                foreach (Match item in results)
                {
                    var sourceId      = item.Groups["source"].ToString();
                    var sourceContact =
                        baseline.Where(
                            x => x.ProfileId.GetProfileId(ProfileIdentifierType.XingNameProfileId) == sourceId).
                        FirstOrDefault();

                    if (sourceContact == null)
                    {
                        continue;
                    }

                    var source = contactsToFill.Where(x => x.Id == sourceContact.Id).FirstOrDefault() as StdContact;
                    if (source == null)
                    {
                        continue;
                    }

                    var targets = Regex.Matches(item.Groups["targets"].ToString(), @"(\<a href=./profile/(?<target>[^/]*))", RegexOptions.Singleline);
                    foreach (Match target in targets)
                    {
                        var targetId = target.Groups["target"].ToString();

                        var targetEntry =
                            baseline.Where(
                                x =>
                                x.ProfileId.GetProfileId(ProfileIdentifierType.XingNameProfileId) == targetId).
                            FirstOrDefault();

                        if (targetEntry == null)
                        {
                            continue;
                        }

                        var reference = new ContactReference {
                            IsBusinessContact = true, Target = targetEntry.Id
                        };
                        if (!source.Contacts.Contains(reference))
                        {
                            source.Contacts.Add(reference);
                            Debug.Print("adding reference: " + reference);
                        }
                        else
                        {
                            Debug.Print("already existing: " + reference);
                        }
                    }
                }

                offset += results.Count;
            }
        }