Internet Technologies:cxp

Organizing your code with helpers Foundation

As a developer, you may already know and hopefully follow the idea of "divide and conquer". In fact, when a unit of code grows too large and contains too many elements, it becomes hard to navigate, hard to get an overview of, and hard to understand. In short: it becomes complex. Our main weapon against this complexity is divide and conquer: we split the unit into smaller parts which we can understand and test in isolation.

This is especially true when you look at your CXP pages: they consist of HTML markup, possibly Javascript code and finally your Xbase++ code. This is fine as long as you just create dynamic content or super small web applications. But what if you develop a web application with business logic and views? An indication that you are actually creating a web application is the number of CXP pages. If your project consists of more than 3-4 CXP pages sharing logic or the same datasource, then you need follow the rules below without exception:

Move all Javascript and CSS code out to separate files which are included in a layout page used by your CXP pages.

Use members or methods only via the @() inline syntax inside your CXP pages/views.

Use the @ single-line syntax for iterators and conditional sections.

Never have code in your CXP page which performs ?/?? HTML output.

Try to avoid code sections (<% %>) in your CXP pages. Of course, you can have CXP pages which contain just code.

Add a DLL target to your project. The location of the DLL target must be in .\helpers.

Move all your business logic or function code to this DLL target.

Add a unit-test target to your DLL target, so that you can write automated tests for your business logic.

But how does a CXP page know that the classes and functions you want to use in your code are located in a helper DLL? Well, for this you need to add a helper section to your <filename>.cxp.config or application.config file as shown below:

<helpers lib="featuremgmt.lib" 
         lib="sitecore.lib" 
         dll="anotherdll.dll" /> 

The previous helpers declaration forces the cxc-builder to link two libraries to your CXP page when building the page's binary. The "dll" entries of your helpers declaration are used by the cxp-worker, however, which will load these DLLs into the process before loading your CXP binary and executing the code in your page.

It should be noted that there are no path elements allowed in the helper LIB and DLL references. The reason for this is that each web application should be self-contained and moveable to another location without reconfiguration. Consequently, all helper DLLs and LIBs must be deployed in a helpers sub-directory relative to your CXP page.

Feedback

If you see anything in the documentation that is not correct, does not match your experience with the particular feature or requires further clarification, please use this form to report a documentation issue.