Wednesday, May 18, 2022

Sitecore Unit Test Examples

 The examples of  Unit tests are listed below..

1.  Constructor test

         [Fact]

        public void ProcessorConstructorTest()

        {

            var repo = Substitute.For<IService>();

            CreateProcessor processor = new CreateProcessor(repo);

            Assert.NotNull(processor);

        }



2.   Controller rendering action method

         [Fact]

        public void SubmitUserDetailsTest()

        {

            //Assign

            var repo = Substitute.For<IUserRepository>();

            var userData = UserMockData.UserMockDetails();

            UserResponse model = new UserResponse();

            repo.SubmitUserDetails(userData).ReturnsForAnyArgs(model);

            //Act

            var controller = new CustomerController(repo);

            var result = controller.SubmitUserData(userData);


            //Assert

            Assert.NotNull(controller);

            Assert.NotNull(result);

            Assert.IsType<CustJsonResult>(result);

            var returnresult = (UserResponse )(result.Data);

            Assert.IsType<UserResponse >(returnresult);

        }

public static UserMockData UserMockDetails()

        {

            return new UserMockData()

            {

                Station= "XYZ",

                LocatorList = new System.Collections.Generic.List<string>{ "{56ZR-GF67856-dfgd56-GHGH5767HJ}", "{HJ678J-HJ67-7HJK-&JKKL-JK789JKL}" },

                Endpoints = new System.Collections.Generic.List<string> { "{JK578KL-68HJ-HJK67-A7D0-KLH78HJ}", "{HJ678J-HJ67-7HJK-&JKKL-JK789JKL}", "{HJ678J-JKL78-HJK567-JKKL-JK789JKL}" },

                 IsMigrated= true

            };

        }

     [DataContract]

    [Bind(Include = "")]

    public class UserMockData

    {

        [DataMember]

        public string Station{ get; set; }

        [DataMember]

        public List<string>  LocatorList { get; set; }

        [DataMember]

        public List<string> Endpoints { get; set; }

        [DataMember]

        public bool IsMigrated{ get; set; }

    }



3. Mock Sitecore Pipeline Processor and Commerce user request

[Fact]

        public void Index()

        {

            var args = new ServicePipelineArgs(new GetUserInfoRequest("12345"),new GetUserInfoResult()

            {

                CommerceUser= new CommerceUser

                {

                    UserName = "XYZ"

                }

                

            });

            using (var db = new Sitecore.FakeDb.Db())

            {

                var processor =

                    Substitute.For<Sitecore.FakeDb.Pipelines.IPipelineProcessor>();


                processor

                    .When(p => p.Process(args))

                    .Do(ci => ci.Arg<ServicePipelineArgs>()

                        .CustomData["Result"] = "Ok");


                db.PipelineWatcher.Register("commerce.customers.User", processor);

                //Assign

                var repo = Substitute.For<ICustInfoRepository>();

                CustInfoApiController controller = new CustInfoApiController(repo);

                SetupCallContext();

                CallContext.Current.Shopping.ShoppingSite = "commtest";

                CallContext.Current.User.IsLoggedIn = true;

                CallContext.Current.User.UserId = "12345";   

            

                SetCustInfoData(CallContext.Current.User.UserId ?? CallContext.Current.User.CurrentUserId);

            

                var result = controller.Index("12345");

                //Assert

                Assert.NotNull(controller);

                Assert.NotNull(result); 

            }

        }

public void SetCustInfoData(string userId)

        {

            var custInfoData = GetCustInfoData();

            SessionCacheHelper.Set<Customer>(ABCCookieHelper.GetCustomerSessionKey(userId), custInfoData );

        }


        public Customer GetCustInfoData()

        {

            return new Customer()

            {


                CardId= "12345",

                Lane = "6",

                Email = "sdfgh@xyz.com",

                Mobileno = "1234567890",

                FullName = "SSSSS",

                Nationality = "DF",

                Gender = "M",

                Dob = Convert.ToDateTime("09/05/1990"),

                ContactId = "6687888787",

                CustomerId = "fghhg777hjhjh"

            };

        }


4. Create Sitecore datasource/Item

using Sitecore.Data;

using Sitecore.FakeDb;

using Sitecore.Sites;

using System;

using Xunit;

using NSubstitute;

 private static DbItem SetFakeContentRoot()

        {

            var PageID1 = new ID(Guid.NewGuid());

            var PageID2 = new ID(Guid.NewGuid());


            var FakeContentRoot = new DbItem("FakeContentRoot")

            {

                new DbItem("PageID1", PageID1),

                new DbItem("PageID2", PageID2)

            };

            return FakeContentRoot;

        }

Tuesday, May 3, 2022

Sitecore Experience Editor - Edit Field support examples

 Link: Render HTML tags in link text

1.     @Html.Sitecore().Field("Link", dataSourceItem, new { text = arrowLink.Text + "<i class='arrow_icon' aria-hidden='true'></i>" })

2.     @Html.Sitecore().Field("Link", dataSourceItem, new

                           {

                               @class = "button " + buttonColorclass + " " + buttonAnimationClass,

                               text = isDonateButton == true ? @Html.Sitecore().Field("Button Image", dataSourceItem, new { @aria_hidden = "true" }) + @linkText : @linkText

                           })

 3.    using (Html.EditFrame(RenderingContext.Current.Rendering.DataSource, "Image Links Block", "Image Links Block", "Edit Image Link Block", null, null))

    {

        <div class="cell large-4 medium-6 small-6 figure">

            <a href="@imageLinkURL">

                @Html.Sitecore().Field("Cover Image", ds)

                <span class="figcaption grid-x align-center-middle">@Html.Sitecore().Field("Image Title", ds)</span>

            </a>

        </div>

    }

4.       @Html.Sitecore().Field("Link", dataSourceItem, new

       {

    text = Html.Raw("<div class='icons'>" + @Html.Sitecore().Field("Icon", dataSourceItem) + "</div><div class='info'><h2>" + @Html.Sitecore().Field("Title", dataSourceItem) + "</h2><h4>" + @Html.Sitecore().Field("Text", dataSourceItem) + "</h4></div>")

    })

Image: 

          @Html.Sitecore().Field("Cover Image", ds, new { @class = "promotion-right-img" })

           @Html.Sitecore().Field("Icon", dataSourceItem, new { @aria_hidden = "true" })


Single line Text/Richtext/Multiline Text:

@Html.Sitecore().Field("Content", renderItem)

How to update Sitecore xConnect Profile programmatically?

 1.     Create custom profile list to update Interaction programmatically

        List<ProfileDetails> profileDetails  = new List<ProfileDetails> profileDetails();

2.     Check whether analytics tracking is enable or not.

                     if (!Tracker.Enabled)

            {

                return;

            }

            if (!Tracker.IsActive)

            {

                Tracker.StartTracking();

            }

3.     Get the user interaction from the user context

        var interaction = Tracker.Current.Session.Interaction;

4.    Update Analytics Tracking Profile

        foreach (var profile in profileDetails)

            {

                var profileName = profile.CategoryName;

                var profileScores = profile.ProfileScores;

                if (!string.IsNullOrEmpty(profileName) && (profileScores?.Any() ?? false))

                {

                    updated = true;

                    Profile xConnectProfile;

                    if (interaction.Profiles.ContainsProfile(profileName))

                    {

                        xConnectProfile = interaction.Profiles[profileName];

                    }

                    else

                    {

                        var profiles = new List<ProfileData>

                            {

                                new ProfileData(profileName)

                            };


                        interaction.Profiles.Initialize(profiles);

                        xConnectProfile = interaction.Profiles[profileName];

                    }

                    xConnectProfile.Score(profileScores);

                    xConnectProfile.UpdatePattern();

                }

            }

5.   Update the interaction and persist the changes to contact

         if (updated)

                {

                    interaction.AcceptModifications();

                    try

                    {

                        var contact = Tracker.Current.Session.Contact;

                        var contactManager = Sitecore.Configuration.Factory.CreateObject("tracking/contactManager", true) as ContactManager;

                        contactManager?.SaveContactToCollectionDb(contact);

                    }

                    catch (Exception ex)

                    {

                        Logger.ABCLogger.Error($"CreateOrUpdateProfileData Exception: ", ex);

                    }

                }

How to Create a Public Link Using the Sitecore Content Hub REST API

Creating a public link using the Sitecore Content Hub REST API is a straightforward process that enables you to share content externally whi...