Sitecore Cookbook for Developers - Yogesh Patel - E-Book

Sitecore Cookbook for Developers E-Book

Yogesh Patel

0,0
43,19 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Over 70 incredibly effective and practical recipes to get you up and running with Sitecore development

About This Book

  • Build enterprise-level rich websites quickly and deliver the best possible content management to your website
  • Get maximum usage of functionalities like different user interfaces, workflow, publishing, search, analytics, etc and learn different rendering techniques using presentation components for data bindings, events, handlers, schedulers, media, etc.
  • Add a surprising amount of functionality just by customizing the Sitecore architecture through the best practices contained in this book

Who This Book Is For

If you are a Sitecore developer or a programmer who wants to expand your Sitecore development skills, this book is ideal for you. You will need working knowledge of ASP.NET WebForms or MVC, as well as HTML, and a basic knowledge of Sitecore installation.

What You Will Learn

  • Create, access, and personalize your website content using different Sitecore presentation components
  • Learn how to extend the presentation components to fulfill some real-life requiremnts such as improving the site's performance, generating Rss feeds and so on
  • Work with multiple websites on a single Sitecore instance and create multilingual websites
  • Customize the Sitecore interfaces as per your business requirements to provide easier and error-free user interface to content authors to save time and improve accuracy
  • Customize the Sitecore backend architecture as per your business needs
  • Automate tasks and achieve scalability by altering the development and configuration settings
  • Integrate external systems with Sitecore to import or export content and secure user interactions
  • Integrate the advanced features of analytics and personalization, to get the best possible customer experience and generate its reports

In Detail

This book will get you started on building rich websites, and customizing user interfaces by creating content management applications quickly. It will give you an insight into web designs and how to customize the Sitecore architecture as per your website's requirements using best practices.

Packed with over 70 recipes to help you achieve and solve real-world common tasks, requirements, and the problems of content management, content delivery, and publishing instance environments. It also presents recipes on Sitecore's backend processes of customizing pipelines, creating custom event handler and media handler, setting hooks and more. Other topics covered include creating a workflow action, publishing sublayouts and media files, securing your environment by customizing user profiles and access rights, boosting search capabilities, optimising performance, scalability and high-availability of Sitecore instances and much more.

By the end of this book, you will have be able to add virtually limitless features to your websites by developing and deploying Sitecore efficiently.

Style and approach

This easy-to-follow guide is full of hands-on recipes on real-world development tasks to improve your existing Sitecore system. Each topic is presented with its benefits and detailed steps to achieve it through well-explained code and images.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 387

Veröffentlichungsjahr: 2016

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Sitecore Cookbook for Developers
Credits
About the Author
About the Reviewer
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Instant updates on new Packt books
Preface
What this book covers
What you need for this book
Who this book is for
Sections
Getting ready
How to do it…
How it works…
There's more…
See also
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
1. Basic Presentation Components
Introduction
Creating a simple content page using template and layout
How to do it…
How it works…
Creating a sidebar menu using view rendering and RenderingModel
Getting ready
How to do it…
How it works…
There's more…
Creating breadcrumb using the view and custom model
Getting ready
How to do it…
How it works…
See also
Creating carousel using view and controller renderings
How to do it…
How it works…
See also
Placing renderings dynamically using placeholders
How to do it…
How it works…
See also
Empowering the Experience Editor using placeholder settings
Getting ready
How to do it…
How it works…
Restricting or swapping rendering controls on placeholders
Getting ready
How to do it…
How it works…
2. Extending Presentation Components
Introduction
Altering rendering behavior using component properties
Getting ready
How to do it…
How it works…
Creating strongly typed rendering parameters
Getting ready
How to do it…
Achieving asynchronous operations using a custom device
How to do it…
How it works…
Creating multilingual content pages
How to do it…
How it works…
There's more…
Generating RSS feeds for syndicated items
Getting ready
How to do it…
There's more…
Improving site performance by caching renderings
Getting ready
How to do it…
How it works…
HTML cache statistics
When to avoid caching
There's more…
See also
Personalizing components
Getting ready
How to do it…
How it works…
There's more…
3. Customizing the User Interface Framework
Introduction
Adding a custom command to item context menu
How to do it…
How it works…
There's more…
See also
Creating a gutter to show unpublished items
How to do it…
There's more…
Creating a Sheer UI application using XAML control to list products
How to do it…
How it works…
There's more…
xamlControls
Creating a SPEAK application to list and sort products
Getting ready
How to do it…
How it works…
See also
Searching and filtering products using SPEAK
How to do it…
There's more…
Building a custom form to bind product details using SPEAK
Getting ready
How to do it…
There's more…
See also
Creating a custom editor tab in the Content Editor
How to do it…
How it works…
There's more…
Creating a custom experience button using the Field Editor
Getting ready
How to do it…
There's more…
Creating a custom rule to validate item fields
How to do it…
How it works…
There's more…
Creating a custom sorting routine to sort the content tree items
Getting Ready
How to do it…
How it works…
Creating a custom field to save the date time with time zones
How to do it…
How it works…
Making fields editable from the Experience Editor
There's more…
4. Leveraging the Sitecore Backend
Introduction
Working with multiple sites
How to do it…
How it works…
There's more…
Customizing pipelines to achieve a custom 404 page
Getting ready
How to do it…
How it works…
Patch configuration
There's more…
Creating a custom event handler to auto-publish on an item save
Getting ready
How to do it…
How it works…
There's more…
See also
Achieving a site-specific URL pattern for a multisite environment
How to do it…
How it works…
There's more…
See also
Initializing hooks to subscribe events to prepare an audit trail
How to do it…
How it works…
There's more…
Creating jobs to accomplish long-running operations
Getting ready
How to do it…
How it works…
See also
Using a scheduling agent to delete older item versions
How to do it…
How it works…
Scheduling database tasks
How to do…
How it works…
5. Making Content Management More Efficient
Introduction
Using dictionary domains for multilingual sites on a multisite environment
How to do it…
How it works…
Bind a dictionary to a site
A fallback dictionary domain
See also
Creating vanity URLs for marketing purposes using an alias item
How to do…
How it works…
See also
Centralizing common content using a clone item
Getting ready
How to do it…
How it works…
See also
Using a wildcard item to integrate external content
Getting ready
How to do it…
How it works…
There's more…
Placing dynamic content in the Rich Text Editor by replacing tokens
Getting Ready
How to do it…
How it works…
There's more…
Adding a custom tool to the Rich Text Editor to generate tokens
Getting Ready
How to do it…
How it works…
Dealing with user-generated content using an Item Web API
Getting Ready
How to do it…
There's more…
Storing external content using a custom cache
Getting Ready
How to do it…
How it works…
There's more…
See also
6. Working with Media
Introduction
Restricting malicious files being uploaded to the media library
How to do it…
How it works…
There's more…
Downloading the media library folder
How to do it…
How it works…
See also
Protecting media files under a disclaimer
How to do it…
How it works…
Achieving responsive images
Getting ready
How to do it…
How it works…
There's more…
Serving media files from CDN or external storage
How to do it…
How it works…
There's more…
See also
7. Workflow and Publishing
Introduction
Creating a custom action using workflow
Getting ready
How to do it…
How it works…
There's more…
Achieving time-based automated publishing
How to do it…
How it works…
There's more…
Unpublishing of items
How to do it…
How it works…
There's more…
Using publishing events to send a publish completion e-mail
How to do it…
How it works…
There's more…
Publishing file-based items using web deploy
Getting ready
How to do it…
How it works…
There's more…
Clearing an HTML cache based on published items for a multisite environment
Getting ready
How to do it…
How it works…
There's more…
Customizing the publishItem pipeline to avoid duplicate names on a live site
How to do it…
How it works…
There's more…
8. Security
Introduction
Working with a custom user profile
How to do it…
How it works…
There's more…
Creating custom access rights for an item
How to do it…
How it works…
There's more…
Achieving a single sign-on by creating a virtual user with custom roles and rights
Getting ready
How to do it…
How it works…
There's more…
Preventing Sitecore from applying security
Getting ready
How to do it…
How it works…
Implementing extranet login
Getting ready
How to do it…
How it works…
9. Sitecore Search
Introduction
Indexing, searching, sorting, and paging content using a search query
Getting ready
How to do it…
How it works…
There's more…
Creating a computed index field for categorization
Getting ready
How to do it…
How it works…
Refining search results by tagging based facets
Getting ready
How to do it…
How it works…
There's more…
Achieving the autocomplete feature with a wildcard
Getting ready
How to do it…
How it works…
There's more…
Influencing search results with boosting
Getting ready
How to do it…
How it works…
There's more…
Hunting MoreLikeThis results
Getting ready
How to do it…
How it works…
There's more…
Correcting a search with did you mean
Getting ready
How to do it…
How it works…
There's more…
Managing millions of items using an item bucket
How to do it…
How it works…
10. Experience Personalization and Analytics Using xDB
Introduction
Personalizing experience based on goals and Engagement Values
Getting ready
How to do it…
How it works…
There's more…
Personalizing content by predicting a visitor's profile
Getting ready
How to do it…
How it works…
There's more…
Storing visitor information in xDB contacts
Getting ready
How to do it…
How it works…
There's more…
Extending xDB by creating a custom contact facet
Getting ready
How to do it…
How it works…
Creating a custom rule and condition for personalization
Getting ready
How to do it…
How it works…
There's more…
Automating the engagement plan
Getting ready
How to do it…
How it works…
Finding nearby places using the Geolocation service
Getting ready
How to do it…
How it works…
There's more…
Aggregating xDB data to generate custom reports
How to do it…
How it works…
There's more…
Extending analytics reports using custom dimensions
Getting ready
How to do it…
How it works…
There's more…
Creating section-specific analytics reports using custom dimensions
How to do it…
How it works…
11. Securing, Scaling, Optimizing, and Troubleshooting
Introduction
Profiling and tracing content pages to find out the slowest operations
Getting ready
How to do it…
There's more…
Transferring items from one database to another
Getting ready
How to do it…
How it works…
There's more…
Making security-hardened environments
How to do it…
There's more…
Adding multiple publishing targets for scalability or preproduction
Getting ready
How to do it…
How it works…
Creating clustered instances for scalability and performance
How to do it…
There's more…
Getting high availability of Sitecore instances
How to do it…
There's more…
Improving the performance of Sitecore instances
How to do it…
There's more…
Database tuning
CDN
A. Getting Started with Sitecore
Installing Sitecore
Creating a Visual Studio project
Creating a project in the web root
Creating a project outside the web root
Debugging a Sitecore application
B. Tools and Resources for Sitecore Developers
Useful tools for Sitecore developers
Sitecore Instance Manager
Sitecore Rocks
Reflecting on Sitecore
Source control for Sitecore databases
The Sitecore database comparer tool
Glass.Mapper
Continuous integration and deployment
Other products and modules
Useful resources for Sitecore developers
Sitecore documentation for developers
A knowledge base for developers
The Sitecore marketplace
Technical blogs
Social media
Community for Sitecore professionals
Sitecore Support
Sitecore MVP
Index

Sitecore Cookbook for Developers

Sitecore Cookbook for Developers

Copyright © 2016 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: April 2016

Production reference: 1260416

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78439-652-7

www.packtpub.com

Credits

Author

Yogesh Patel

Reviewer

Pavel Nezhencev

Commissioning Editor

Amarabha Banerjee

Acquisition Editor

Reshma Raman

Content Development Editor

Pooja Mhapsekar

Technical Editor

Manthan Raja

Copy Editor

Tasneem Fatehi

Project Coordinator

Judie Jose

Proofreader

Safis Editing

Indexer

Mariammal Chettiyar

Graphics

Disha Haria

Abhinash Sahu

Production Coordinator

Arvindkumar Gupta

Cover Work

Arvindkumar Gupta

About the Author

Yogesh Patel has been programming since the year 2000, and has been working in the IT industry for over ten years on a variety of technologies. He was mainly involved in Sitecore or .NET-based development in the Indian offices of US and UK-based organizations. He has worked at Investis Ltd as a technical architect and has lead a Sitecore development team. Yogesh has held a number of positions and has a lot of responsibilities, having worked at Investis since 2009. He has been recognized as a Most Valuable Professional (MVP) by Sitecore for 2014, 2015, and 2016.

As a developer, Yogesh enjoys learning new programming techniques, practices, and tactics. He has worked on .NET since 2005 and Sitecore since 2009. He has also spent plenty of time developing in C, VC++, MATLAB, VB6, ASP, Java, PHP, AppleScript, SQL, and MySQL, but his current focus is on .NET—especially Sitecore. His blog can be found at http://sitecoreblog.patelyogesh.in. You can find Yogesh on Twitter at @patelyogesh_in, as well as LinkedIn (yspatel) and Facebook (patelyogesh.in).

Avni, my beloved wife and my parents, I thank you for your love, support, and encouragement, without which I would have been unable to carry on this endeavor. I'd particularly like to thank Pavel Nezhencev for reviewing this book. I'd also like to thank my colleagues at Investis, Muktesh Mehta and Siddhi Kabra, for supporting me throughout the project.

About the Reviewer

Pavel Nezhencev is an experienced .NET/JS web developer working in the Denmark department of Creuna, which specializes in creating web platforms for businesses of any scale. Pavel has a bachelor's degree in software engineering from Kharkiv National University of Radio Electronics, Ukraine. He worked for five years with Sitecore and Episerver systems and successfully launched several solutions on these platforms.

www.PacktPub.com

eBooks, discount offers, and more

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Instant updates on new Packt books

Get notified! Find out when new books are published by following @PacktEnterprise on Twitter or the Packt Enterprise Facebook page.

Preface

Sitecore Experience Platform (XP), which is more than a content management system (CMS), is global leader in experience management. It continues to be very popular due to its robust framework, continuous innovations, and ease of implementations compared to other CMS available. Developers love Sitecore for its flexibility, scalability, and power. It has great out-of-the-box capabilities, but one of its great strengths is the ease of extending these capabilities.

Sitecore Cookbook for Developers is intended to provide a surprising amount of recipes to use out-of-the-box core capabilities and customize them. It also focuses on helping developers that are new to Sitecore to achieve maximum productivity and satisfaction with minimum efforts. It also includes tips, tricks, and best practices for working with the platform.

What this book covers

Chapter 1, Basic Presentation Components, focuses on creating information architecture and presenting it using out-of-the-box components and different Model-View-Controller (MVC) renderings. It also shows how effectively you can utilize out-of-the-box components to provide greater ease and flexibility for future enhancements.

Chapter 2, Extending Presentation Components, gives examples for extending out-of-the-box components to develop multilingual and multidevice websites, integrate the content with external systems, and provide easier content management for content owners.

Chapter 3, Customizing the User Interface Framework, demonstrates you how to create new interfaces or extend existing interfaces, using different framework components. It also provides some recipes to please content authors.

Chapter 4, Leveraging the Sitecore Backend, gets you completely involved in Sitecore backend architecture. This chapter gives you a brief tour of different the features to extend the core engine using pipelines, processors, events, handlers, hooks, jobs, schedulers, and so on.

Chapter 5, Making Content Management More Efficient, shows you different tricks and techniques to manage the content in a better way and provide better usability with the use of backend and frontend frameworks and different functionalities such as dictionary, validations, rule engine, Rich Text Editor, Item Web API, and so on.

Chapter 6, Working with Media, explores different techniques while working with Sitecore media items such as securing them, serving them through content delivery network (CDN), and utilizing them for responsive web designs.

Chapter 7, Workflow and Publishing, shows how you can extend the workflow and publishing architecture to achieve scheduled publishing and unpublishing, using web deploy while publishing and customizing pipeline and events.

Chapter 8, Security, explains how to create different user profiles and give custom permissions to it. It also explains how to achieve single sign-on (SSO) securely and allow extranet access in a secure way.

Chapter 9, Sitecore Search, describes different techniques for accessing data from indexing. It explains how to implement different search techniques, which modern search engines use such as tagging, autosuggest, boosting search results, finding more like this, and did you mean.

Chapter 10, Experience Personalization and Analytics Using xDB, explains how to provide the best user experience using different techniques of real-time personalization, it is the heart of marketing programs. It also briefs features for engaging users. This chapter will also provide good recipes to use and extend Experience Database (xDB) and generate different analytics reports.

Chapter 11, Securing, Scaling, Optimizing, and Troubleshooting, focuses on different techniques for making the Sitecore environment more secure. It also explains techniques to troubleshoot slowness, create clustered environments to get better performance, high availability, and scalability. It also briefs some techniques to troubleshoot.

Appendix A, Getting Started with Sitecore, contains information to help you in Sitecore installation, and create a project for your Sitecore solution using Microsoft Visual Studio.

Appendix B, Tools and Resources for Sitecore Developers, provides information on tools and resources available for Sitecore developers to install, and maximize their productivity and expertise by using it.

What you need for this book

The minimum requirements for this book would be Sitecore 8 or later, .NET Framework 4.5 or later, ASP.NET MVC 5.1 or later, MS SQL 2008 R2 or later, and IIS 7.5 or later. You can refer to Sitecore Compatibility Table at https://goo.gl/4kkCHe for more details.

It is recommended that you use a plain Sitecore setup to implement the recipes of this book in order to avoid unnecessary conflicts with existing implementations.

To download and install Sitecore and create a project, you can refer to Appendix A, Getting Started with Sitecore, which you will find at the end of this book.

Who this book is for

If you are a Sitecore developer or programmer who wants to expand your Sitecore development skills, this book is ideal for you. As this book targets readers of various experience levels, you should be able to find recipes of beginner, intermediate, and advanced nature. You will need working knowledge of ASP.NET WebForms or MVC, as well as HTML, and a basic knowledge of Sitecore installation.

Sections

In this book, you will find several headings that appear frequently (Getting ready, How to do it, How it works, There's more, and See also).

To give clear instructions on how to complete a recipe, we use these sections as follows:

Getting ready

This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.

How to do it…

This section contains the steps required to follow the recipe.

How it works…

This section usually consists of a detailed explanation of what happened in the previous section.

There's more…

This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.

See also

This section provides helpful links to other useful information for the recipe.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "Make sure that you have added a reference of Sitecore.Kernel.dll and Sitecore.Mvc.dll files to the SitecoreCookbook project."

A block of code is set as follows:

<div id="header"> <a href="/"> @Html.Sitecore().Field("Logo", Sitecore.Context.Database.GetItem( "/sitecore/Content/Global/Configurations")) </a> </div>

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

<div id="sidemenu"> @Html.Sitecore().Rendering("{2383A57F-21FF-4A77-9E2A-C467F0CEDA57}") </div>

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "From the ribbon, select Standard Values in the Builder Options tab."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/SitecoreCookbookForDevelopers_ColorImages.pdf.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/Content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.

Chapter 1. Basic Presentation Components

In this chapter, we will see how to build pages in Sitecore with the help of different rendering techniques using different Sitecore presentation components. You will learn the following recipes:

Creating a simple content page using template and layoutCreating a sidebar menu using view rendering and RenderingModelCreating breadcrumb using the view and custom modelCreating carousel using view and controller renderingsPlacing renderings dynamically using placeholdersEmpowering the Experience Editor using placeholder settingsRestricting or swapping rendering controls on placeholders

Introduction

If you are reading this book, you already know that Sitecore XP (Experience Platform) is not only an enterprise-level content management system (CMS) but also a web framework or web platform. Sitecore has robust and in-depth APIs to offer maximum flexibility to developers to implement custom solutions. It has many features designed to support enterprise-level requirements.

Sitecore provides extensive out-of-the-box components such as layout, device, placeholder, and some rendering controls, which play important role in designing and editing interfaces. We can also develop custom rendering components using Extensible Stylesheet Language Transformations (XSLT), ASP.NET Web Forms, and Model-View-Controller (MVC) frameworks to render content to the pages. All these frameworks currently exist in Sitecore, but MVC is now becoming widely used in Sitecore solutions and also provides better options compared to Web Forms and XSLT. Hence, we will prepare all the recipes using the MVC framework.

This chapter first serves recipes to create rendering components using model, view, and controller, and then explains how we can integrate them with Sitecore's out-of-the-box components. Looking into the depth of presentation components, you will learn extending these components in the next chapter.

Note

For this chapter, it's required that you create a Visual Studio solution. You can refer to Appendix A, Getting Started with Sitecore, which explains how you can set up Sitecore solutions. Make sure that you have added a reference of Sitecore.Kernel.dll and Sitecore.Mvc.dll files to the SitecoreCookbook project.

Creating a simple content page using template and layout

As a developer, you will first have to understand the architecture of how a web page works. To create web pages, you first need to create a data structure using data templates, based on which you can create content items. Layout is used to place content with some presentation logic on it. In this recipe, we will take a quick look at creating a simple content page showing the title, body, logo, and other details.

How to do it…

We will first create and define a data template for the Home item (that is, home page):

Log in to Sitecore. Open the Content Editor from Launch Pad. You will find a default /sitecore/Content/Home item with the Title and Text fields. Delete this item as we will create our own custom template for the Home item.In the /sitecore/Templates item, create a new Template Folder item, Cookbook. In this, create a Site Root template, leaving the base template set to the default Standard template, as shown in the following image:In template builder, create different fields, Title and Body, as shown in the following image, and save the details:We will now create a content page using this data template. Create a new content item, Home, in the /sitecore/Content path using the Site Root template that we created and fill in the appropriate information in these fields:To show common details of websites, such as logo, copyright text, and some other information, create another Site Configuration template with fields such as Company Name, Logo, CopyrightText, and so on.The Site Configuration item will be a non-visual item, so it should be created outside the Home item. Create a folder item Global in /sitecore/Content, and in this, create a content item, Configurations, using the preceding template, and fill in the appropriate details.We will now create a layout from Visual Studio. From the SitecoreCookbook project, create an MVC main.cshtml view in the /Views folder to render field values from the previously created items. For this, put the following code in the view file inside the <html/body> tag:
<div id="header"> <a href="/"> @Html.Sitecore().Field("Logo", Sitecore.Context.Database.GetItem("/sitecore/Content/Global/Configurations")) </a> </div> <div id="contentarea"> <h1>@Html.Sitecore().Field("Title")</h1> @Html.Sitecore().Field("Body") </div> <div id="footer"> @Html.Sitecore().Field("Copyright Text", Sitecore.Context.Database.GetItem("/sitecore/Content/Global/Configurations")) </div>
We will now register this view file as a layout in Sitecore. In the /sitecore/layout/Layouts item, create a layout folder, Cookbook. In this, create a layout named Main Layout. Set the path field of this layout to /Views/main.cshtml.Now we will assign the layout to the content items. Select the Site Root data template. From the ribbon, select Standard Values in the Builder Options tab. This will create the __Standard Values item for the template.Select the __Standard Values item. From the ribbon, select the Details button in the Layout group from the Presentation tab. It will open a Layout Details dialog. For a Default layout, click on the Edit button, which will open the Device Editor dialog. Here, in the Layout section, select Main Layout and select OK. See the following image, which represents both the dialogs:

Tip

Instead of standard values, you can also assign a layout directly to the Home item. However, it's a recommended practice to apply presentation components to a template's standard values so that all items created from the template will inherit the field values from standard values.

From the Content Editor, select the Home item. From the ribbon, click on the Preview button in the Publish group from the Publish tab. This will open your home page in preview mode, as shown in the following image, where you will find Logo, Title, Body, and Copyright Text.

Note

You can get the layout and style sheet files from the code bundle provided with this book to make it work, as shown in the following image:

Tip

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

How it works…

Sitecore layouts are reusable ASP.NET Web Forms (.aspx) or MVC views (.cshtml) that you register with Sitecore. ASP.NET uses Web Forms or views to serve HTTP requests. Here, on requesting the Home item, Sitecore first reads the item and renders the physical file of the layout associated with the item.

In the view file, we used the Sitecore field helper, @Html.Sitecore().Field(<field name>), to render the Title and Body field values from the context item (in our case, Home). This helper method can also render a field of items other than the context item, which we used in order to render the Logo and Copyright Text fields of the Configurations item, @Html.Sitecore().Field(<field name>, Sitecore.Context.Database.GetItem(<ItemId or path of item>)).

Here, the Sitecore.Context.Database.GetItem() method provides the Sitecore.Data.Items.Item object, which has a collection of all the field values associated with the item.

Note

To learn more APIs, download Sitecore Presentation Component API Cookbook (https://goo.gl/fu99Vh). It provides APIs from Sitecore 6.4 or later with examples of Web Forms or Web controls, but they are still valid for Sitecore 8 or later with MVC as well.

Apart from the Content Editor, Sitecore also provides another tool, Experience Editor, to view pages in editing mode. From the ribbon, click on the Experience Editor button in the Publish tab to open an item in the Experience Editor. You can open it from Launch Pad as well. Here, you can change field values (for example, Body in the following image) rendered on the layout or view:

To disable content editing for an item field, you can pass additional parameters to the field helper, as shown in the following code:

@Html.Sitecore().Field("<field name>", new {DisableWebEdit=true})

You can also customize its rendering behavior by extending the Sitecore helper class. You can learn this from https://goo.gl/ZHruKe and http://goo.gl/Kx8MQl.