Tuesday, May 23, 2017

Sitecore 404 and 500 handle

Today we discuss, how we can handle 404 and 500 in Sitecore.
I found below URL useful as well.
https://www.akshaysura.com/2016/08/02/secure-sitecore-why-use-a-custom-500-error-page/ 
http://findgnosis.com/2015/05/14/ideal-error-handling-for-sitecore/ 

Handle 500 Error:
So first I talk about 500 error handle for that I use to replace below line in web.config

<customErrors mode="RemoteOnly"/>

to

<customErrors mode="On" defaultRedirect="~/Error/500Error.html" redirectMode="ResponseRewrite"/>

According to Akshay sura blog that is the good approach to take static HTML page for handle 500 error.

Handle 404 Error:

Now come to 404 error. For this I take two settings as below:

<?xml version="1.0"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
        <settings>
      <!--For handle 404 error-->
      <setting name=CustomError.Page404Resolver" value="ItemId"/>
      <setting name="RequestErrors.UseServerSideRedirect" value="true" />
    </settings>
  </sitecore>
</configuration>

The first one takes the item id for the 404-page item that is shown when 404 error occurs.
Second setting just keeps maintaining the same address which we request for. If you don't use this setting then after resolving item it shows 404 item name in URL instead of address which you type.

For handle 404 we place our code after item resolve that makes significant action if item not found(404).

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <httpRequestBegin>
        <processor type="CustomError.ErrorHandler.Page404Resolver, CustomError"

                   patch:after="processor[@type='Sitecore.Pipelines.HttpRequest.ItemResolver, Sitecore.Kernel']"/>
      </httpRequestBegin>
    </pipelines>
  </sitecore>
</configuration>

Page404Resolver.cs:


namespace CustomError.ErrorHandler
{
    public class Page404Resolver : HttpRequestProcessor
    {
        public override void Process(Sitecore.Pipelines.HttpRequest.HttpRequestArgs args)
        {
            if (Sitecore.Context.Item != null || Sitecore.Context.Site == null || Sitecore.Context.Database == null || WebUtil.GetRawUrl().IndexOf("/sitecore") > -1)
            {
                if (Sitecore.Context.Database != null && ID.IsNullOrEmpty(LanguageManager.GetLanguageItemId(Sitecore.Context.Language, Sitecore.Context.Database)))
                {
                    SetCustomErrorPage(args);
                }
                else
                {
                    return;
                }
            }
            SetCustomErrorPage(args);
        }

        private void SetCustomErrorPage(HttpRequestArgs args)
        {
            string errorPagePath = Settings.GetSetting("CustomError.Page404Resolver");

            var item = args.GetItem(errorPagePath);
            if (Sitecore.Context.Item != null && Sitecore.Context.Item.Versions.Count == 0)
            {
                item = item.Database.GetItem(item.ID, Sitecore.Globalization.Language.Parse("en"));
                Sitecore.Context.Language = Sitecore.Globalization.Language.Parse("en");
            }
            if (item != null)
            {
                Sitecore.Context.Item = item;
                args.Context.Response.StatusCode = 200;
                args.Context.Response.TrySkipIisCustomErrors = true;
            }
        }

    }
}


In case if item not found(sitecore context item have null value) on that case above code get the 404 page item id from setting variable and resolve the item of 404 and replace with context item.

Hope that may help you to resolve 404 and 500 error.
Till that happy Sitecoring :)

Please leave your comments or share this article if it’s useful for you.

Tuesday, April 11, 2017

Sitecore EditFrame in MVC

Hi All,
Today we discuss about Editframe in sitecore MVC.
This is use for edit the associated fields value by providing content editor look to experience editor user. Like there are many fields which are not easily edit in experience mode for that we can use editframe.
Steps are below:
1. Navigate to code db "/sitecore/content/Applications/WebEdit/Edit Frame Buttons"
2. Under this node create a seprate directory for you project like "DemoProject"
3. Right click and insert "Field Editor Button" as below:


This button create from "/sitecore/templates/System/WebEdit/Field Editor Button" template.
Give a suitable name to button like "CustomTextEdit".
4.Fill the Name in "Header", choose icon in "Icon" and in "Tooltip" type description which you want that come in hover.
5. In "Fields - pipe-separated list of field names to be edited by the Field Editor [shared]:" Place the name of fields which you want to edit like:
ex: Title
ex: Title|Description   etc.
6.Now in code use editframe as below:

@using (Html.BeginEditFrame(Html.Sitecore().CurrentRendering.DataSource, "//sitecore/content/Applications/WebEdit/Edit Frame Buttons/DemoProject"))
{

}



Alternative:
If you don't wanna use above method then there is alternative as well:
1. Navigate to in core db "/sitecore/content/Applications/WebEdit/Custom Experience Buttons"
2. Insert a field editor item based on "/sitecore/templates/System/WebEdit/Field Editor Button" button
3. Same as above in "Fields" fill the field name as below:
ex: Title

ex: Title|Description   etc.
4. now come in master db and found the rendering for which you wanna this editframe.
5. On specific rendering under "Experience Editor Buttons" select your custom button.

Reference:
http://www.awareweb.com/awareblog/11-25-14-custombuttonspageeditor
https://visionsincode.wordpress.com/2015/01/08/how-to-use-editframe-in-sitecore-mvc/

I hope you enjoy this Sitecore blog. Stay tuned for more Sitecore related articles.

Till that happy Sitecoring :)

Please leave your comments or share this article if it’s useful for you.

Thursday, April 6, 2017

Change SQL Server Password if forget

Hi,

Some time we come in a situation where we forgot our ssms or squeal server password.
Here is way to unlock sa user account or change the password:
  1. Login into SQL Server using Windows Authentication.
  2. In Object Explorer, open Security folder, open Logins folder under Security->Logins . Right click on sa account and go to Properties.
  3. Type new password and confim password.
  4. That's done!

Note: If you face issue that password is not changed and having some error then please have a look under Status option and check 'sql server authentication' is unchecked 





I hope you enjoy this Sitecore blog. Stay tuned for more Sitecore related articles.

Till that happy Sitecoring :)

Please leave your comments or share this article if it’s useful for you.

Wednesday, April 5, 2017

Coveo setup for Sitecore 8


Hi,

Today we discuss how setup coveo for Sitecore 8.

Step 1: Download Coveo for Sitecore, Coveo Enterprise Search and Coveo Search API

Note: Download coveo based on your sitecore version.
Step 2: Create an admin user for Coveo on your computer
  • Open Control Panel -> System and Security -> Administrative Tools
  • Open Computer Management
  • Go to Local users and groups -> Users
  • Right click -> New User
  • Name: Coveo
  • Full Name: Coveo Search
  • Password: search (use something more secure in a production environment)
  • Uncheck user much change password at next login & account disabled
  • Check user cannot change & password never expires
  • Make the user a member of Administrators and Users
Step 3: Install Coveo Enterprise Search
  • You cannot run the installer from a network drive
  • Let it install any necessary files
  • Agree to terms
  • Choose typical Installation
  • Configure Account for Access
    • Use the user account created in step 2
  • Do not change config for other options
    • Secure access not necessary for a local instance
    • Take note if you change the RabbitMQ username: password, you will need these during the Sitecore package install
  • Allow Firewall Access if prompted
Note:
1. It also asks for the install coveo diagnostic tool. Install that and open below URL:
Here 8081 is default port you also can change that.
2. Please also create a folder C:\CES7 , this is default folder you also can change that but keep in mind if you change here then you also select that folder in during Sitecore coveo package installation.
Step 4: Install Coveo Search API
Note: Select the check box “This installation is part of a Sitecore installation” and after click next select “Generate Random Token”
If you found any difficulties in above step then Please have a look on below URL:
Step 5: Make sure Coveo services are running
  • View Local Services by search “View Local Services”
  • Start all Coveo services
Step 6: Restart IIS
  • This may not be necessary. But it makes sure the localhost:8080 and localhost/AdminService are working correctly.
Step 7: Verify Admin Service

Step 8: Verify RabbitMQ
Step 9: Verify Coveo Search API
  • Go to http://localhost:8080
    • You should get a message the search page is not configured yet
Step 10: Verify Coveo Admin Tool
  • Go to http://localhost:8081
    • You should see the coveo admin tool
Step 11: Install Coveo for Sitecore (sitecore package)
  • Open Sitecore Desktop -> Developer Tools -> Installation Wizard
  • Upload Sitecore package and Install
  • Follow wizard prompts
    • Coveo is on the same server as the sitecore instance
    • Coveo Index Path: c:\CES7 (create this folder if it does not exist)
    • Search API Url: http://localhost:8080/
    • Application Secret: (the secret key created in step 4)
    • Configure RabbitMQ: (leave defaults or enter credentials used in step 3)
    • Admin Service URI: http://localhost/AdminService
    • Username and Password: (for the sitecore admin account)
    • Sitecore license: Copy and paste your license file contents
    • Rename Coveo files /websiteroot/Website/App_Config/Includes/
      • Coveo.SearchProvider.config.example to Coveo.SearchProvider.config.
      • Coveo.SearchProvider.Rest.config.example to Coveo.SearchProvider.Rest.config.
      • Coveo.UI.Controls.config.example to Coveo.UI.Controls.config
    • Restart Sitecore client and server.
    • I personally didn’t disable lucene config.
Step 12: Check Coveo Diagnostics
  • Open Sitecore Control Panel -> Coveo Diagnostic Page
  • All components should have a green light and message “up and running”
    • Coveo Search REST Endpoint can have a red X and an error and the site will still function correctly
Note: If Coveo Search Web Service is not running or give Failed to obtain resource located at 'http://sc8initial/coveo/rest?indexName=Coveo_web_index'. [BEGIN RESPONSE BODY]{"statusCode":408 error.
It means you don't have any serverCertificatePath or clientCertificatePath in your config.yml. Those settings are mandatory.

serverCertificatePath should be the path to the CES7 index's cert-ca.pem certificate file.

clientCertificatePath should be the path to the CES7 index's cert-iis.p12 certificate file.
serverCertificatePath: C:\CES7\Config\Certificates\cert-ca.pem (default)
clientCertificatePath: C:\CES7\Config\Certificates\cert-iis.p12 (default)

Or have a look same issue on below URL:

After giving the path go to “view local services” and restart the “Coveo search api”.
Now you can access :
http://{HostName}/coveo/rest

After this when you open diagnose page you found that all services are up and running smooth.

Ex: http://{HostName}/sitecore%20modules/Web/Coveo/Admin/CoveoDiagnosticPage.aspx




///////////////////////////////////////////////////////////////////////////////////////
Some Useful Coveo local system URL:
http://localhost:8081/Configuration/InitialSetup/InitialSetup.aspx  (Coveo Admin Tool): For index configuration handled by sitecore
or
http://localhost:8081 (Coveo Admin Tool): For index configuration handled by sitecore
http://localhost/adminservice  (Admin Service)
http://localhost:8080 (Coveo Search API)
http://{HostName}/coveo/rest
http://{HostName}/sitecore%20modules/Web/Coveo/Admin/CoveoDiagnosticPage.aspx


//////////////////////////////////////////////////////////////////////////////////////




I hope you enjoy this Sitecore blog. Stay tuned for more Sitecore related articles.

Till that happy Sitecoring :)

Please leave your comments or share this article if it’s useful for you.

Tuesday, April 4, 2017

Setup custom smtp for Sitecore EXM 3.0 and 3.4

For setup custom SMTP for EXM 3.0:  You just need to add one patch config for SMTP setting which I previously described on my blog. You can found here.

Just move this patch file under include folder of Sitecore.

When you try for sending test email via EXM it show message "
The connection to the Sitecore App Center could not be established.". 
For removing this because you are usingIf you are using custom mail server instead of Sitecore App Center then you need to set the “UseLocalMTA” as “true” in Sitecore.EmailCampaign.config with SMTP details.
Now you are able to send an email via EXM 3.0.

For setup custom SMTP for EXM 3.4: For setup EXM 3.4 with Sitecore 8.2 you just need to update following config


At first, I follow the instruction which is shown when we install EXM that are shown below:


***Important! Copy and save this information***
==========================================================
    BEFORE YOU CLICK NEXT:
    - Add two empty connection strings with the names "exm.master" and "exm.web" to /App_Config/ConnectionStrings.config e.g. <add name="exm.master" connectionString="" /> and <add name="exm.web" connectionString="" />.
    - Add two connection strings with the names "EXM.CryptographicKey" and "EXM.AuthenticationKey" to \App_Config\ConnectionStrings.config. The keys should be represented in hexadecimal format by 64 characters. For more information please see the installation guide.

    BEFORE YOU CLOSE THE WIZARD:
    - Click the checkbox ‘Restart the Sitecore client’.

    AFTER YOU CLOSE THE WIZARD:
    After the package is installed, follow these steps to complete the EXM installation:
    1. Attach the Sitecore.Exm and Sitecore.Exm_Web databases. The files can be located in the Data folder.
    2. Update the connection strings "exm.master" and "exm.web" in /App_Config/ConnectionStrings.config, e.g. <add name="exm.master" connectionString="user id=user;password=password;Data Source=(server);Database=Sitecore_EXM" /> and <add name="exm.web" connectionString="user id=user;password=password;Data Source=(server);Database=Sitecore_EXM.Web" />.
    3. Enable the Sitecore MTA or the Custom SMTP provider files in the /App_Config/Include/EmailExperience folder by removing the .disabled extension from the files.
    4. In the /App_Config/Include/Sitecore.Analytics.Tracking.config file, ensure the value of the Analytics.ClusterName setting is set to your instance host name.
    5. Publish your site using smart publish. 
    6. In the App Center, configure the Email Delivery service if you are using the Sitecore MTA provider.
    7. In the App Center, sign up for the Email Preview and Spam Detect services. [optional]

I just do some update in few config files that are listed below.
1. Sitecore.EDS.Provider.CustomSmtp.config


In this config I do following changes:


<smtpSettings type="Sitecore.EDS.Core.Net.Smtp.SmtpSettings, Sitecore.EDS.Core" singleInstance="true">
                    <server>smtp.gmail.com</server>
                    <port>587</port>
                    <userName>xxxxxxxx@gmail.com</userName>
                    <password>xxxxxxx</password>
                    <authenticationMethod>Login</authenticationMethod>
                    <startTls>true</startTls>
                    <proxySettings ref="exm/eds/proxySettings" />
</smtpSettings>

      2.  Sitecore.EDS.Provider.CustomSmtp.Sync.config



<pop3Settings>
          <pop3Setting type="Sitecore.EDS.Core.Net.Pop3.Pop3Settings, Sitecore.EDS.Core" singleInstance="true">
            <server>pop.gmail.com</server>
            <port>995</port>
            <userName>xxxxxxxxx@gmail.com</userName>
            <password>xxxxxxxxx</password>
            <useSsl>true</useSsl>
            <startTls>true</startTls>
            <proxySettings ref="exm/eds/proxySettings"/>
          </pop3Setting>
 </pop3Settings>

        3. Sitecore.Analytics.Tracking.config


<s<setting name="Analytics.ClusterName" value="{Hostname}" />

I I also path a custom config as well that include following entry.


<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <settings>
      <setting name="MailServer" value="smtp.gmail.com"/>
      <!--  MAIL SERVER USER
        If the SMTP server requires login, enter the user name in this setting
  -->
      <setting name="MailServerUserName" value="xxxxx@gmail.com"/>
      <!--  MAIL SERVER PASSWORD
        If the SMTP server requires login, enter the password in this setting
  -->
      <setting name="MailServerPassword" value="xxxxxx"/>
      <!--  MAIL SERVER PORT
        If the SMTP server requires a custom port number, enter the value in this setting.
        The default value is: 25
  -->
      <setting name="MailServerPort" value="587"/>
   
    </settings>
  </sitecore>
</configuration>

After these changes I am able to send email via EXM 3.4 for Sitecore 8.2.

Note: Instead of setting up the custom email account for testing I strongly recommend to use papercut for this. this is use for setup custom SMTP setup for the local system. You can found here.

I also found one blog by Brijesh Patel more useful as well. You can found that blog here.

I hope you enjoy this Sitecore blog. Stay tuned for more Sitecore related articles.

Till that happy Sitecoring :)

Please leave your comments or share this article if it’s useful for you.

Wednesday, March 29, 2017

Setup Local SMTP server for Sitecore local Email test.

Step-by-step guide

  1. Go to http://papercut.codeplex.com/
  2. Download and install the application
  3. Once installed and running, go to the "Options" menu and set IP Address to you local IP address
  4. That's it, you can now tell your application to send out emails to your local SMTP server

After this create a .config file for use this:


<?xml version="1.0"?>
<configuration>
  <sitecore>
    <settings>
      <!--Email configuration-->
      <setting name="Analytics.ClusterName" value="{HostName}" />
      <setting name="UseLocalMTA" value="true"/>
      <setting name="SMTP.Port" value="25" />
      <!-- SMTP server address (IP). -->
      <setting name="SMTP.Server" value="{localIpAddress}" />
    </settings>
  </sitecore>
</configuration>

Tuesday, March 14, 2017

Watchout! You are in the web db!

Watchout! You are in the web db!: Based on a vent by @cassidydotdk on the Sitecore Slack chat the other day, we were all laughing about the (multiple)times when we forget that we have switched to teh web database to check something ou

Right Click Unlock Item with Sitecore PowerShell Extensions

Right Click Unlock Item with Sitecore PowerShell Extensions: I have been asked many times if it is possible for non admin users in Sitecore to be able to unlock items that have been locked by others. The short answer is no, the Sitecore command (Sitecore.Shell.

Friday, March 10, 2017

Sitecore Content Migration

Hi All,

Sometimes we need to migrate some existing website content or SQL server content into Sitecore website.
For this I found below post very useful by Kiran Patil:

https://blog.horizontalintegration.com/2014/04/01/sitecore-content-migration-basics/

Hope that's help you lot.

Friday, March 3, 2017

Mongo DB for sitecore

Hi All,

Today we discuss Mongo DB for the Sitecore developer.
For understanding basic of mongo DB and installation process please follow this blog.

In the above described blog, you can understand basic of MongoDB and how to install as window service.

But in above blog, there is some limitation for creating window service.
For make that process simpler I created a bat file for that named as below:
1.mongo create service.bat
2.mongo remove service.bat

#mongo create service.bat:
   This is used for creating window service for mongo
    That prompt you some basic things fill those according to your configuration.
Like it's asking for some input as below:
1. Please enter mongod.exe path: Copy and paste the path of the mongod.exe file which is generally found under mongo DB \bin folder.
eg: c:\Program Files\MongoDB\Server\3.4\bin\mongod.exe or
      c:\mongodb\bin\mongod.exe

2.Please enter dbPath: Here you can specify the path where you want to store mongo database.
eg: E:\Projects\sampleproject\mongodb\reports

3.Please enter logpath: That point to a .log file that store the logging information of mongo server.
eg: E:\Projects\sampleproject\mongodb\reports\log\mongodb.log

4.Please enter serviceName: Here just specify the MogoService name.
eg: MongoDB
5.Please enter serviceDisplayName: Here just specify the MogoService display name.
eg: MongoDB

After following these steps window service is created.

#mongo remove service.bat:

     That bat is used for delete exisiting window service which you wanna remove.
 it's ask for some input as below:

1. Please enter mongod.exe path: Copy and paste the path of mongod.exe file which is generally found under mongo db \bin folder.
eg: c:\Program Files\MongoDB\Server\3.4\bin\mongod.exe or
      c:\mongodb\bin\mongod.exe

2.Please enter serviceName : Here just specify the MogoService name.
eg: MongoDB

After follow these steps window service is removed.

Hope you enjoy this.

Note: Keep in mind that always run .bat file with admin privilege. For that right click on .bat file and select Run as administrator option.


References:
https://stevenstriga.wordpress.com/2017/02/25/sitecore-mongodb-blog-series-intro-to-mongodb-for-sitecore-developers/

https://stevenstriga.wordpress.com/2017/02/28/sitecore-mongodb-blog-series-out-of-the-box-sitecore-databases/

https://briancaos.wordpress.com/2014/10/01/sitecore-and-xdb-setting-up-mongodb-on-your-developer-machine/

https://www.mongodb.com/lp/contact/mongodb-sitecore

Wednesday, March 1, 2017

Sitecore certification in FREE of cost

Hi All,

At first very thankful to Surendra Sharma for sharing such a good blog on Sitecore certification training free of cost.
As all, you know Sitecore certification is a very costly process.

But now Sitecore launch new e-learning program where Developer, Business User and Marketers able to got e-learning training.

For this please have look on below URL:
https://elearning.sitecore.net/Catalog/TrainingCatalog.aspx

For developer please have a look at this URL:
https://elearning.sitecore.net/Catalog/BrowseCategory.aspx?id=2ED6A20460E441178D4CE61B584E9896

Sitecore give developer to the opportunity to do Sitecore® Developer Foundations eLearning free of cost. For that follow below blog:
http://www.sitecorelessons.com/2017/02/sitecore-certification-in-free-of-cost.html 


At the end of the course, you will be honored with below certificate





you also honored by certificate after completing each course module. like

                            

Thursday, February 23, 2017

Don't write logic into your Views, use a Controller

BAD
The view contains 4 lines of Markup but 15 lines of code. Don't do that - it's better to use a Controller that contains an Action which contains the logic and returns a model to the view.
BETTER
Change your Sitecore presentation Item from View rendering to Controller rendering and set the Controller assembly path and action:
The action should contain all logic:
And the view only the markup:
But even the Model.Count == 0 is too much logic. The model could contain a field "HasItems" that checks the model count, but this can be accepted. After refactoring, the view contains more lines of Markup than logic.

How-to structure Sitecore dictionary entries

Working with hundreds of translation labels for dozens of different website components (e.g. search, forms, settings, notifications, etc.) requires a certain amount of housekeeping.
Thus, structuring your dictionary entries into appropriate folders is always a good idea!
Two things matter here:
  1. the dictionary entry is contextualized by applying a use-case oriented folder structure (/Modules/Direct Links/...)
  2. the key of the dictionary entry resembles the actual item path, allowing a developer to easily find a given dictionary entry

And that's all you need to know about structuring Sitecore's dictionary entries.
Happy coding! (smile)

Wednesday, February 22, 2017

Thursday, February 9, 2017

How add Recaptcha on MVC layouts

For this please follow Sitecore documentation:
https://doc.sitecore.net/web_forms_for_marketers/working_with_actions_and_validations/fields/add_and_customize_a_recaptcha_field_on_mvc_layouts

Wednesday, February 8, 2017

Solr Configuration for providing search suggestions

Hi All,

Today we discuss how we configure solr for provide search suggestion.
For that I follow 2 blogs which are listed below the blog.

https://blog.horizontalintegration.com/2015/07/20/configuring-solr-to-provide-search-suggestions/

http://www.nttdatasitecore.com/Blog/2017/January/Faceted-Autocomplete-for-a-Sitecore-Multilingual-site-using-SOLR-Suggester-API

By using help of these blog I can configure solr with auto suggest. I use 1st blog for setup solr and using 2nd blog Building jQuery Autocomplete jquery : jquery function for autocomplete suggestion.

Note:
1.Keep in mind while follow first blog for updating solrconfig.xml field str contain the name of the field for example:
<searchComponent name="suggest" class="solr.SuggestComponent">
    <lst name="suggester">
        <str name="name">fuzzySuggester</str>
       ...
        <str name="field">page_title_t</str>
    ...
    </lst>
    <lst name="suggester">
        <str name="name">infixSuggester</str>
      ...
        <str name="field">page_title_t</str>
       ...
    </lst>
</searchComponent>

2. While using 2nd blog jquery function its give cross platform error , solution also provide in that blog but i am not able to resolve that so i use my solution that are below:
<script type="text/javascript">
        $('#search-field').autocomplete({
            source: function (request, response) {
                var currentLanguage = 'en';
                var url = "http://localhost:8983/solr/custom_index_autocomplete/suggest?suggest.q=" + request.term + "&suggest.cfq=" + currentLanguage + "&wt=json&json.wrf=?";
                $.getJSON(url, function (data) {
                    //response($.map(data.suggest.suggester[request.term].suggestions, function (value) { return value.term }));
                    response($.map(data.suggest.fuzzySuggester[request.term].suggestions, function (value) { return value.term }));
                });
            }
        });
</script>

3. For combined multiple indexes for autosuggestion please follow as below:

   <script type="text/javascript">
        $('#search-field').autocomplete({
            source: function (request, response) {
                var currentLanguage = 'en';
                var url = "http://localhost:8983/solr/custom_index_autocomplete/suggest?suggest.q=" + request.term + "&suggest.cfq=" + currentLanguage + "&wt=json&json.wrf=?";
                var url1 = "http://localhost:8038/solr/content/suggest?suggest.q=" + request.term + "&suggest.cfq=" + currentLanguage + "&wt=json&json.wrf=?";

                var res;
                var res1;
                $.getJSON(url, function (data) {
                    res = data.suggest.fuzzySuggester[request.term].suggestions;
                    $.getJSON(url1, function (data) {
                        res1 = res.concat(data.suggest.fuzzySuggester[request.term].suggestions);
                        response($.map(res1, function (value)
                        { return value.term }
                           ));
                    });
                });
            }
        });
    </script>

Wednesday, January 4, 2017

Sitecore Custom Logs

Hi All,

Sometimes we need a custom logger that report the error or some information about the flow of our Sitecore.
By using that we can found where we lack our flow. At first, we have many ways to do that.
But I only focus on 2 that are below:
1. By using Sitecore Log class of Sitecore.Diagnostics.
ex: Log.Error("message", exception, "logger name");
ex: Log.Error("CustomError", model.Exception, "CustomError.Intranet");
2. By using Log4net.
For that, you have to add log4net node in config. we can implement by adding in web config or add custom config recommended is add custom path like CustomError.config under include folder.
That have the code as:

<?xml version="1.0"?>
<configuration>
  <sitecore>
    <settings>
      <setting name="" value="" />
         </settings>
    <log4net>
      <appender name="IntranetIntegrationLogFileAppender" type="log4net.Appender.SitecoreLogFileAppender, Sitecore.Logging">
        <file value="$(customLogFolder)/logs/Extranet.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="CustomError.Intranet" additivity="false">
        <level value="INFO" />
        <appender-ref ref="IntranetIntegrationLogFileAppender" />
      </logger>
    </log4net>
  </sitecore>
  <system.web>

  </system.web>
</configuration>

Now you can use this in anywhere in a project like in code file you have to use this as below:

ex: Here model.Exception is a variable which I use in my code you can change according to your code.
              ILog _serviceLog;
            _serviceLog = LogManager.GetLogger("CustomError.Intranet");
            _serviceLog.Info("-- Start Intraner Custom error logger-- ");
            _serviceLog.Error("-- Error Message, " + model.Exception.Message + " -- ");
            _serviceLog.Error("-- Error , " + model.Exception + " -- ");
            _serviceLog.Info("-- End Intraner Custom error logger-- ");

When you look into your Website root folder you found $(customLogFolder)/logs
under this folder, you found your custom logs but unfortunately this is the blank log.
I investigate more and I found a solution from below reference:
https://blog.horizontalintegration.com/2015/10/02/empty-sitecore-custom-log-files/

Add reference of Sitecore.Logging.dll instead of log4net.dll directly

Now I get my custom log.

References:
https://blog.horizontalintegration.com/2015/10/02/empty-sitecore-custom-log-files/
http://firebreaksice.com/write-to-a-custom-sitecore-log-with-log4net/
http://sitecoreblog.blogspot.in/2011/05/write-you-messages-in-separated-file.html

Enjoy :)