Thursday, September 15, 2016

Sitecore best practices guideline

I have got some Sitecore best practices guideline. We can follow those guideline during Sitecore development. Thnaks to our Sitecore gladiator Kapil NakerOshyn.

Template best practices:
1. Group the fields into logical sections based on business sections or data type sections thereby avoiding a huge form, and provide for a compartmentalized form, that can be collapsed as needed.
2. Identify reusable fields when designing templates. Avoid excessive customization; simplify.
3. Use Data templates for normal data entry templates. Use Branch templates when you have a predefined structure of items, sub items to be created. Branch templates have the ability to also create “children” (descendants) of the new item at the same time the parent item is created.
4. Choose names which are understood by business users. Display Name and Field Titles are the important ones that Sitecore uses.
5. Define separate fields for display name, breadcrumb title, and navigation title fields for a page item.
6. Avoid using a lot of RTE fields within the template and keep the templates small.
7. Use icons wherever applicable to facilitate visual differentiation and understood by business user.
8. Place the section of fields that are modified frequently at the top of the data template or place them in order they appear on pages.
9. Always have default values in the form of standard values.
10. Provide proper context sensitive help for the fields, and sections in templates.
11. Make the field names unique between sections, do provide a prefix, suffixes indicating types, for example Title Name, Product Name as field name to avoid conflicts in field names when the templates are inherited by another template.
12. Avoid Circular Inheritance in templates.
13. Avoid modifying templates in Sitecore/Templates/System section
14. Centrally manage the layout settings, initial workflow, Insert Options in template standard values than in individual items.
15. Use Tilda (~) character in source for image fields with caution, as this will allow the user access to the entire media library tree.
16. Use TreelistEx in comparison to Treelist to make the rendering faster.
17. Use Droplink and Grouped Droplink instead of Droplist and Grouped Droplist.
18. Do not use the Internal Link, Layout, Rules, and Template Field Source field types in your data template as they are deprecated data types.
19. Make base template components, which then can be inherited by other templates to provide for foundation templates.
20. Wherever required, have field validations been set. For instance, content cannot be published if the SEO metadata has not been entered and this should be ensured through field validations.
21. Have insert options been defined for data templates to ensure that content taxonomy is maintained in the content tree.
22. All image fields in the data template have their data sources set so as to ensure that images are only uploaded to the right folder.
23. All sub layouts / renderings have content-author friendly screenshots set so as to provide a better page editing experience. However this practice we follow on need basis after evaluation of the need.
24. For some of the common non-visual content fields (like SEO, tagging), ensure there are options for an author to enter content within the Page Editor without having to go back to Content Editor , however this practice we follow on need basis after evaluation of the need.


 Presentation component best practices:
1. Store the layouts inside /Sitecore/Layout/Layouts/, sub layouts inside /Sitecore/Layout/Sub layout. You can create sub-directories within these as needed with added access restrictions.
2. Do not have more than 2 or 3 layouts per device or per site and handle the different structures using placeholders and sub layouts respectively.
3. Assign the layout details in the standard values rather than on items or template definition item.
4. If different items based on a template require different layouts, then create a new template that inherits from the existing template.
5. Use FieldRenderer object to render the fields on presentation
6. Sort the sub layouts containing the placeholders to be before the controls that bind to those placeholders as Sitecore layout engine builds and binds the controls based on this order.
7. Caching options should be configured whenever the controls are used, based on the control definitions.
8. Use sublayouts, renderings, xslt appropriately with below guidelines
a. Global.asax, pipeline processor, or event handler - Logic to be done on application start/end, session start/end, request process cycle, event cycle.
b. Layouts – Page level code ,
c. Xslt - Module level Code with simple little logic, ex: breadcrumb, Sitecore controls – Module level Code with simple logic, where separation of data from presentation is not required.
d. Sub layouts - Module level Code with complex logic
9. Site should be compliant to content authoring using Page editor and not require access login to Desktop interface of Sitecore for content editors.

Content structure best practices:
1. As standard practice, we would recommend not having more than 50 items under any item node. Try to maintain the hierarchy in such a way that it reduces the number of children per node.
2. Make sure the indexes are frequently updated.
3. Identify the different roles and access restrictions for items in order to provide access based on minimal access requirements.
4. Avoid using special characters in Item names.
5. Check for version compatibility when using Sitecore modules.
6. Turn off the visibility of Standard Values on content items, “Entire tree” view for Content Editors in general, which can be toggled as needed by them.
7. Use Clones instead of Proxy items since proxy items are deprecated in Sitecore 6.5.
8. Identify the security related requirements in multisite in one instance environment and design your site structure, media structure that meets the requirements of separation.
9. Maintain only a few versions of each item in the implementation.
10. Separate the content that is to be managed versus the content that is transactional.
11. In case of multisites in one instance, separate the structures as follows and appropriately set the websites in web.config <sites> node.
a. Templates structure: /sitecore/Templates/Global, /sitecore/Templates/Site1, /sitecore/Templates/Site2.
b. Layouts structure: /sitecore/Layout/Layouts/ Global, /sitecore/Layout/Layouts/Site1, / sitecore/Layout/Layouts/Site2.
c. Sites structures: /sitecore/Content/GlobalData, /sitecore/Content/Site1, /sitecore/Content/Site2.
d. Media Library structures: /sitecore/Media Library/Global, /sitecore/Media Library/Site1,


Media asset best practices:
1. Use database as the storage mechanism for media in general instead of file based storage.
2. Use File system in scenarios where the number of assets is large (running into Gigabytes).
3. Organize the media assets in business user friendly way.
4. In a multisite, one instance scenario, make sure you organize the structure in such a way to meet any restriction requirements related to access of different media library folders to different site authors. For example Media library/site1/Images, Media library/site2/Images

Storage locations best practices:
1. Datafolder is responsible for logs, viewstates, diagnostic counters, debug traces and packages—making this location a high-write situation for both the CMS and the web nodes. Ensuring the datafolder is located on a disk that can handle the write requirements aids in performance. You will want to consider this set-up for the tempFolder, as well, which is used as a temporary processing location.
2. Media.CacheFolder, which is used to store media that has been extracted from the database, is most relevant for the published site. Writes to disk are generally infrequent for this folder, making high-speed reading a greater priority

Security best practices:
25. Create the roles in Sitecore Domain instead of specific domain.
26. Prevent .config, .xml, .xslt,files from being served by web server
27. Make sure /data, /indexes folders are not accessible to anonymous users and are outside of the website directory context.
28. Turn off anonymous access to / App_Config, /Sitecore/admin, / Sitecore/debug, /Sitecore/shell/ Web Service.
29. Deny Execute scripts Permissions and disable upload folder on the Delivery Server. On the Authoring Server, enable upload folder if the content authors use it to upload files.
30. Provide the minimal set of roles to user accounts for performing their duties.


Caching best practices:
1. Combined size of all the caches should not exceed available memory.
2. Use Sitecore Debugger, Firebug, /Sitecore/ admin/stats.aspx, and /Sitecore/admin/cache.aspx to measure the performance of the sites.
3. During cache monitoring, if the Delta value keeps changing consistently with the size of the cache being more than 80% of the max size limit for that cache, then consider increasing the max size for that cache by 50%.
4. Tweak Pre-fetch cache appropriately by caching key items deemed to be required for the site.
5. Sitecore provides recommended values for Data cache, Items cache to be around 150MB on Delivery Servers.
6. In case of usage of custom caching solution being used in your application, use the publish:begin or publish:end events of Sitecore to handle eviction strategies, based on updates to Sitecore item that is cached.
7. Building a site with a higher number of small renderings and sublayouts gives greater flexibility to control the caching of HTML

Development best practices:
1. Set up continuous integration environment process flow for the project in order to have scripted compilation and coding style checks ,run through set of unit tests, merge\replace different environment specific config tokens, and deploy to respective DEV, QA and PROD environments.
2. Content Editing should be done on the master database(CM), and then pushed to web database(CD).
3. Site context should be considered when programmatically creating links in a multisite or multi device scenario.
4. Identify the controls that can be cached and appropriately assign the values for caching the markups.
5. Log debug, error statements to log file, or to Sitecore log file, to be able to check these logs for errors.
6. Use GUID’s instead of Sitecore paths where possible. If paths, then consider the differences between Fast query results versus normal query results.
7. Encapsulate the Content types or templates using one of object mapper modules available at shared source, to be able to address as Product.Name instead of productItem. Fields[“Name”] all over the code.
8. Use Sitecore Rocks plug-in in Visual studio for development.
9. Place the item in editing mode before it is edited programmatically.
10. Separate the configurations of Sitecore from the custom configurations being added as part of the solution.
11. Hide all files in Solution Explorer, especially before debugging.
12. Minimize long statements that use the ternary operator.
13. Remove the extension for the page URL and for the media items.
14. Creating new hooks or pipeline additions in Sitecore is a common means to extend functionality; however, before deciding on this approach, be sure understand when this new code fires. If  unsure, create a simple stub and have it log out, or trace it through debugger
15. Use of automated tools to test .NET code.Tools like the Red Gate suite of products for profiling our .NET code and locating potential problem points
16. Use of .NET profilers to find .NET issues
17. Set the copy local property to false when reference an assembly in the /bin directory of the solution, or Visual Studio compilation may delete assemblies.
18. When accessing Sitecore.Data.Items.Item.Children, Sitecore invokes a database query. This doesn’t matter in a foreach loop, but should put Children in a Sitecore.Collections.ChildList before iterating with a for loop.
19. Stress-test  code with realistic volumes of data and users—make the test scenario as close as you can to the reality of your eventual implementation environment.


Monday, September 12, 2016

Error in sitecore mvc routing: An illegal route has been detected: '{controller}/{action}/{id}'

If you are working with Sitecore with MVC and you face the below issue then you can resolve the below issue by commenting the below lines from RouteConfig.cs file(screenshot) and publish.

Issue:
The following fatal error have been detected:
1: An illegal route has been detected: '{controller}/{action}/{id}'. If you wish to keep this route, please remove it from the Mvc.IllegalRoutes setting.


Resolution:


Sunday, September 11, 2016

Version conflict with System.Web.Mvc

Few days back while compiling our project we are getting the below error.We spend a long time to resolve the issue and finally got the solution..


Assembly 'System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'
 uses 'System.Web.WebPages, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'
 which has a higher version than referenced assembly 'System.Web.WebPages, Version=2.0.0.0,
 Culture=neutral, PublicKeyToken=31bf3856ad364e35'      
  c:\inetpub\wwwroot\WebsiteSiteCM\Website\bin\System.Web.Mvc.dll website.Retail.Web

You may also try to reinstall Microsoft.AspNet.WebPages nuget packages using this command in the package manager console
> Update-Package reinstall Microsoft.AspNet.WebPages 

How to reset Admin password to default password b in Sitecore

It might happen we forgot or lost admin password in Sitecore. Then there is a simple way to reset the admin password to "b"

Steps:
1. Navigate to Core database.
2. Run the below query in core database and it will update to default password to b.

UPDATE dbo.aspnet_Membership
SET
    Password='qOvF8m8F2IcWMvfOBjJYHmfLABc=',
    PasswordSalt='OM5gu45RQuJ76itRvkSPFw=='
WHERE  UserId = (SELECT UserId FROM dbo.aspnet_Users WHERE UserName = 'sitecore\Admin')


Wednesday, June 22, 2016

If there is mongodb connectivity issue in production what will happen?

Yesterday I have got a query from our client that in production if there is a mongodb connectivity issue for time being what will happen to website from user end? The question was really interesting to me. I thought the website might not be available for that time period and gave the answer to client.

Later I thought that I am doing some mistake and searched google and from SDN I got to know that if mongodb  is not available then..

1. From a user's perspective, the site will continue to function normally unless  we are doing any personalization or custom logic based on data directly from MongoDB.
2. The Experience Analytics dashboard pulls data from the reporting SQL Server database, which contains aggregated data from MongoDB, so it will continue to function, however, our metrics will eventually flat-line as new data will not being captured with an invalid/broken MongoDB connection
3. Will see errors in the Sitecore logs file related to failed connection attempts.
4.  Website will be available but traffic will not be logged on xDB.





Wednesday, May 25, 2016

Custom Processors in Sitecore


If the processor has a method, the method must accept a PipelineArgs object and return type will be void. Below code snippet will help us to write simple custom processor in Sitecore.


 public void Process(AverageRatingProcessorArguments args)
        {

            double average = 0;
            String ConStringName = Sitecore.Configuration.Settings.GetSetting("ratingconstring");

            using (SqlConnection connection = new SqlConnection(ConStringName))
            {
                connection.Open();
                using (SqlCommand command = new SqlCommand("Getaverage", connection))
                {
                    command.CommandType = CommandType.StoredProcedure;
                    command.Parameters.AddWithValue("@BlogItemID", args.itemID);
                    average = (double)command.ExecuteScalar();
                }
            }
       
            args.CustomData.Add("averagerating", Convert.ToString(average));
        }


 public class AverageRatingProcessorArguments:PipelineArgs
    {
        public string itemID { get; set; }

    }

//Invoking the custom processor
public string AverageRatingWithProcessor(string itemID)
        {
             
            RatingModule.Processors.AverageRatingProcessorArguments ARarg = new RatingModule.Processors.AverageRatingProcessorArguments();
            ARarg.itemID = itemID;          
           
            CorePipeline.Run(AVERAGE_RATING_PROCESSOR, ARarg);
            var AvgRating = ARarg.CustomData["averagerating"];

            return AvgRating.ToString();
        }

Wednesday, May 18, 2016

MongoDb Data is updated after your session end

After session end the data is sent to MongoDb but during development phase will you wait for the time when the session will be abandoned?I think you will say "No". So we can do one thing on that time that we can explicitly kill our session.

Steps:
create a simple abandon.aspx page and place it within [Sitecore Instance Name]/sitecore/admin folder and call the abandon.aspx page explicitely like [Sitecore Instance Name]/sitecore/admin/abandon.aspx
Code snippet for abandon.aspx
<% Session.Abandon();%><html><head></head><body><h1>Kill the session</h1>
>
We forcefully Abandon the session.</body></html>
Calling the "abandon.aspx" page


?


Monday, May 16, 2016

What is difference between droplink and droplist in Sitecore?


Today one of my friend asked me what is the basic difference between Droplink vs Droplist in very simple words. I replied that...

Droplink:
Droplink  stores the GUID(Unique in space and time) of the item that was chosen by content editor.

Droplist:
Droplist data type only stores the string value of the item that was chosen by the content editor.

Saturday, March 19, 2016

How to invoke/Call custom Pipeline


To call the pipeline use the CorePipeline.Run method as follows:
var pipelineArgs = new MyPipelineArgs();
 pipelineArgs.DbName = master;
 pipelineArgs.Item = blogCommentItem;

 CorePipeline.Run("CustomPipeline", pipelineArgs);




Simple way to create Branch Template in Sitecore

Please follow the below steps to create branch template in Sitecore.

Step 1:
Create a folder "Region" and withing Region folder Create a simple template name "Country" with two fields "Title" and "Description".


Step 2:
Duplicate the Item and name it to "City" and "State".
Step 3:
Within "Branch" create new folder named "Region". Right click --> Insert-->New Branch -->popup will open--> choose "county" template.

Please follow the below screenshot....










Simple way to Sort Sitecore Items in the Content Editor


Right click on the item you want to sort, Just shown in below screenshot


Now you can sort Subitem like creation date,Display Name,Reverse order etc.

Creating sitecore item programmatically based on template


Creating sitecore item programmatically based on template:



    public void CreateItemBasedonTemplate()
        {
           
            using (new SecurityDisabler())
            {
                //First get the parent item from the master database
                Database masterDb = Sitecore.Configuration.Factory.GetDatabase("master");
                Item parentItem = masterDb.Items["/sitecore/content/home/MyItem"];
               
                //we need to get the template from which the item is created
                TemplateItem template = masterDb.GetTemplate("sample/sample item/My Template");
               
                //Now we can add the new item as a child to the parent
                parentItem.Add("NewItem", template);

             
            }
        }

Friday, March 4, 2016

How To Publish Item CM To CD with c# code

Very simple way to Publish any Item CM To CD using c# code
public static bool PublishItemCMTOCD(Database DbName, String ItemId)
        {
            Item item = DbName.GetItem(Sitecore.Data.ID.Parse(ItemId));
            bool flag = false;

            if (item != null)
            {
                Sitecore.Publishing.PublishOptions publishOptions =
                  new Sitecore.Publishing.PublishOptions(item.Database,
                                                         Database.GetDatabase("web"),
                                                         Sitecore.Publishing.PublishMode.SingleItem,
                                                         item.Language,
                                                         System.DateTime.Now);  
                Sitecore.Publishing.Publisher publisher = new Sitecore.Publishing.Publisher(publishOptions);

                // Choose where to publish from
                publisher.Options.RootItem = item;

                // Publish children as well?
                publisher.Options.Deep = true;

                // Do the publish!
                publisher.Publish();
                flag = true;
            }           

            return flag;
        }

Saturday, February 27, 2016

Step to install Mongodb

Step to install Mongodb:
1.  Install the mongo db by clicking on “mongodb-win32-x86_64-2008plus-2.6.3-signed.exe”
2. create “MongoDB” folder in D:\ drive.
3. Create two folders named Data and Log within MongoDB folder.
4. Create Mongo.log file in Log Folder.
5. Create “mongodbconfig.cfg” file in D:\ MongoDB floder.
6. run the below command
C:\Program Files\MongoDB\bin\mongod.exe --config "D:\MongoDB\Mongodbconfig.cfg" –install
7. go to services.msc and start the mongodb service.

That’s it. Mongo db is installed and started.

Validation:


INSTALL MONGODB Resources: