Friday, June 3, 2016

How Use Sitecore Web Services

Hi All,
Hope all is well there.
Today I discuss about Sitecore Web Services for updating the sitecore Item value via using sitecore web service.

First question why I need to update the Sitecore item value by Web services nor directly.
I explain via issue that I face during my project. I call a controller on radio button click as I defined in my previous blog that link is here. In this I update the count values based on yes or no click. If user press Yes then Yes field counter increase by one same for NO.
But this is not issue i just update the value by helping of this blog. Its work fine for me as well I uses Sitecore.Context.Database for getting the current database Its work fine for me at local or stage but Its goes live on CD server that hold only "web" database so according to my code my context database is now "web" its update the value for web but when client publish the content fron CD server my fields that hold the count value that is overridden. So one of my colleague suggest me to use sitecore web service for update the item in master database via contact to master database from CD server. So here below I just show you how i can update my value via sitecore web service.
I also getting help from this blog as well.
In my controller i Just do update as:
       

public class FeedbackResultController : Controller
    {
        /// 
        /// Call Web service for update the value in master database on CD server
        /// 
        private readonly VisualSitecoreService _webReference = new VisualSitecoreService();
        private readonly Credentials _credentials = new Credentials();
        private ILog _feedbackLog;

        public FeedbackResultController()
        {
            _webReference.Url = Sitecore.Configuration.Settings.GetSetting("Feedback.Webservice.Url");
            _credentials.UserName = Sitecore.Configuration.Settings.GetSetting("Feedback.Webservice.Credentials.UserName");
            _credentials.Password = Sitecore.Configuration.Settings.GetSetting("Feedback.Webservice.Credentials.Password");
            _feedbackLog = LogManager.GetLogger("WR.Feedback");
            _feedbackLog.Info("-- Initializing Log for feedback controller, " + DateTime.Now + " --");
            _feedbackLog.Info("-- Current web url set in config is: " + _webReference.Url + " --");
            _feedbackLog.Info("-- Current username for logon is: " + _credentials.UserName + " --");
            _feedbackLog.Info("-- Current password for logon is: " + _credentials.Password + " --");
        }
 public ActionResult Feedback(String inlineRadioOptions)
        {
         
       //Get context Item
      Item itm=GetContextItem();;
     if (item != null)
            {
                if (!inlineRadioOptions.IsNullOrEmpty() && inlineRadioOptions.Equals("yes"))
                {

                    if (!item["Yes"].IsNullOrEmpty())
                    {
                        feedbackResult = Convert.ToInt32(item["Yes"]);
                        AlertItem(feedbackResult, item, inlineRadioOptions);
                    }
                    else
                    {
                        AlertItem(feedbackResult, item, inlineRadioOptions);
                    }
                }
                else if (!inlineRadioOptions.IsNullOrEmpty() && inlineRadioOptions.Equals("no"))
                {
                    if (!item["No"].IsNullOrEmpty())
                    {
                        feedbackResult = Convert.ToInt32(item["No"]);
                        AlertItem(feedbackResult, item, inlineRadioOptions);
                    }
                    else
                    {
                        AlertItem(feedbackResult, item, inlineRadioOptions);
                    }
                }
            }
               
            if (Request.UrlReferrer != null)
            {
                WebUtil.Redirect(new Sitecore.Text.UrlString(Request.UrlReferrer.OriginalString).ToString());
            }
            return null;
        }


        private void AlertItem(int feedbackResult, Item item, string inlineRadioOptions)
        {
            const string targetDb = "master";
            //Use a security disabler to allow changes
            using (new Sitecore.SecurityModel.SecurityDisabler())
            {
                try
                {
                    var fieldValue = (feedbackResult + 1).ToString();
                    var fieldId = item.Fields[inlineRadioOptions].InnerItem.ID.ToString();
                    var feedbackValue = SaveToSitecoreField(fieldValue, item.ID.ToString(),
                            fieldId);
                    // Save value by Sitecore Web Api
                    _webReference.Save(feedbackValue.ToString(), targetDb, _credentials);
                }
                catch (Exception ex)
                {
                    _feedbackLog.Info("-- Leaving Log for feedback controller --");
                }
                finally
                {
                    _feedbackLog.Info("-- Leaving Log for feedback controller --");
                }
            }
        }

        private object SaveToSitecoreField(string fieldValue, string itemId, string fieldId)
        {
            XDocument fieldXml = new XDocument(
                new XElement("sitecore",
                    new XElement("field",
                        new XAttribute("itemid", itemId),
                        new XAttribute("language", "de-De"),
                        new XAttribute("version", 1),
                        new XAttribute("fieldid", fieldId),
                        new XElement("value", fieldValue))));

            return fieldXml;
        }

        public Item GetContextItem()
        {
            Item item = null;
            if (Sitecore.Context.PageMode.IsExperienceEditor || Sitecore.Context.PageMode.IsExperienceEditorEditing || Sitecore.Context.PageMode.IsPreview)
            {
                if (Request.UrlReferrer != null)
                {
                    UrlString url = new Sitecore.Text.UrlString(Request.UrlReferrer.OriginalString);
                    var id = url.Parameters["sc_itemid"];
                    item = Sitecore.Context.Item;
                    // if a query string ID was found, get the item for page editor and front-end preview mode
                    if (!string.IsNullOrEmpty(id))
                    {
                        item = Sitecore.Context.Database.GetItem(id);
                    }
                }
            }
            else
            {
                item = Sitecore.Context.Item;
            }
            return item;
        }
      }
}
            
 




Url, UserName & Password I am passing by patch config as:

<?xml version="1.0" encoding="utf-8" ?>
<!-- For more information on using transformations
     see the web.config examples at http://go.microsoft.com/fwlink/?LinkId=214134. -->
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <sitecore>
    <settings>
 <!-- Url to FeedbackResult Sitecore web service -->
      <setting name="Feedback.Webservice.Url">
        <patch:attribute name="value">http://{hostName}/sitecore/shell/Webservice/Service.asmx</patch:attribute>
      </setting>
      <setting name="Feedback.Webservice.Credentials.UserName">
        <patch:attribute name="value">sitecore\admin</patch:attribute>
      </setting>
      <setting name="Feedback.Webservice.Credentials.Password">
        <patch:attribute name="value">b</patch:attribute>
      </setting>
      <log4net>
        <appender name="CommentsLogFileAppender" type="log4net.Appender.SitecoreLogFileAppender, Sitecore.Logging">
          <file value="$(dataFolder)/logs/Comments.log.{date}.txt" />
          <appendToFile value="true" />
          <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%4t %d{ABSOLUTE} %-5p %m%n" />
          </layout>
          <encoding value="utf-8" />
        </appender>
        <logger name="WR.Feedback" additivity="false">
          <level value="INFO" />
          <appender-ref ref="CommentsLogFileAppender" />
        </logger>
      </log4net>
 </sitecore>
</configuration>

Hope you understand now how we can update value via Sitecore Web Services.

Happy Coding!

Thanks
Arun Sharma

No comments:

Post a Comment