Create Redirect Rule with PowerShell

This is a follow-up to my recent post showing how quick the creation of a self-signed certificate can be. Now that you have an SSL certificate it is helpful to ensure that all calls to your site go through on SSL. The easiest way to do this ( and save yourself typing time) is to create a Url rewrite rule via IIS’s Url Rewrite Module, https://www.iis.net/downloads/microsoft/url-rewrite.

Ensure Url Rewrite Module is Installed

For redirect rules to be written you need to confirm the module is installed. The best way to do this is to open up IIS, select a web application, and check for the module’s icon.

Url Redirect Rule - Url Rewrite Module Icon

If you do not see the icon, then you will need to install the module before moving on. You can install the module through the Web Platform Installer or the link at https://www.iis.net/downloads/microsoft/url-rewrite.

Run the Create Redirect Rule Script

  1. Download and save as CreateRedirectRule.ps1 from Gist, https://gist.github.com/gillissm/0344c9551e7a8180354544ff5f60e821.
  2. Open a PowerShell command prompt, ensure you are running it as Admin
  3. Change directory to the location you saved to in step 1
  4. At the prompt enter, and complete the requested parameters
    .\CreateRedirectRule.ps1

    Url Redirect Rule -Script with Prompts

    OR you can submit the parameters at run

    .\CreateRedirectRule.ps1 -SiteBinding "coffeehouse.thecodeattic.com" -RuleName "Redirect to SSL"

    Url Redirect Rule -Script in singleline

Script for Reference

Advertisements

Helix Project Creation Script

Creating Helix Solutions and Modules with PowerShell

Helix is a set of overall design principles and conventions for Sitecore development, put forth by Sitecore in hopes of providing the community a path toward standardized solution development. As noted in the official documentation:

Helix provide a set of guidelines for your Sitecore projects. The Habitat example provides you with a pre-built and tested set of common modules that you can use as an inspiration to your project. Both improve the efficiency of your projects, reduce costs and time to market. As more and more people and organisations adopt the Helix conventions and principles, it will become a Sitecore standard. This means that people who are familiar with the conventions or the Habitat example will be able to work more easily on other convention-based projects with minimal training. It will be easier for Sitecore Product Support to understand projects built using the conventions, enabling them to resolve issues more quickly. Sitecore will test its software using the conventions so any compatible project that has been implemented for a customer will be more reliable. And since Sitecore will test its software using the conventions, Sitecore will be able to provide better guidance on how to update and upgrade existing Sitecore projects when new versions and new products are released.

(“Why be interested at all in Helix or Habitat?“, http://helix.sitecore.net/introduction/what-is-helix.html#why-be-interested-at-all-in-helix-or-habitat, April 16, 2018)

Some Basic Principles

Before we can dig into the script and creating Helix based solutions and modules, I want to reference some basic principles from the Helix documentation.

A Module is a conceptual grouping of assets which relates to a business requirement. For example, when the company asks that their Sitecore solution contains website search, all assets, business logic and configuration relating to search belongs to the Search module.

In technical terms, project often refers to Visual Studio project, but conceptually can also to the process of implementing the business requirements into an implementation.

The layer concept in Helix supports the architecture by making the dependency flow completely clear everywhere in the solution, in Sitecore, in Visual Studio and even in the file system. Furthermore, the layers provide a structure that is extremely suitable for creating and maintaining solutions of any size and steers both new and experienced developers to producing more maintenance-friendly and clean code. Layers helps control the direction of dependencies the importance of which is described by the Stable Dependencies Principle or SDP, which is one of the cornerstone principles in Modular Architecture:

Helix - Dependencies Direction

File System and Solution Layout

In the Helix documentation, (and a review of the sample Habitat site) one will find a very specific recommended (if not expected) layout and naming of folders both in the Visual Studio Solution as well as the file system. The uniqueness of this ‘recommended’ layout makes the initial setup of a solution very time consuming and increasingly error prone when you start to deal with adding modules at the different layers. The following two images, taken from the Helix documentation show what the Visual Studio Solution and corresponding file system begin to look like.

Helix - Visual Studio Solution, from Sitecore           Helix - File System, from Sitecore

Helpful but difficult

My team enjoys the flexibility as well as cleanliness of a solution built on the Helix principles. What we find most difficult is the extra leg work required in making the file system as well as the Visual Studio Solution appropriate to meet the principles. Trying to solve this problem has led us to try several solutions available in the Sitecore Community, many function very nicely, but didn’t always meet the needs of my teams. So I setout to solve some of these issues, including :

  • No use of custom templates and files to ease setup across machines
  • Option for serialization project creation
  • Pre-loading basic NuGet packages for a module
  • New projects added into the solution by default

Helix Project Creator PowerShell Module

Enough with the intro stuff and into the meat of what you’ve come looking for…a script to ease your Helix headaches and focus on the fun of implementing solutions. TheCodeAttic.Helix.ProjectCreator can be pulled from GitHub at https://github.com/gillissm/TheCodeAttic.Helix.PowerShellProjectCreator.

Setup and Use the Simple Manual Process

The first thing you need to do is retrieve the script from the GitHub repository. As this is hosted on GitHub there are numerous ways you can go about getting things ready to use. In an attempt to make adaption as easy as possible I’ve simplified setup to the following four steps for you:

  1. Open PowerShell command prompt as Admin.
  2. Change the directory to a working/temporary location
  3. Enter the following command
    (Invoke-WebRequest -UseBasicParsing -Uri https://raw.githubusercontent.com/gillissm/TheCodeAttic.Helix.PowerShellProjectCreator/master/ProjectCreatorEasyInstall.ps1).Content | Out-File "ProjectCreatorEasyInstall.ps1"
  4. Then enter
    .\SELRES_09210478-5ac2-4be5-81ef-480eb16e800fSELRES_66c735a3-48ae-4ec2-9967-83d5f083a6f6SELRES_906c181e-dccb-4538-a6c3-1eb25a8f6853ProjectCreatorEasyInstallSELRES_906c181e-dccb-4538-a6c3-1eb25a8f6853SELRES_66c735a3-48ae-4ec2-9967-83d5f083a6f6SELRES_09210478-5ac2-4be5-81ef-480eb16e800f.ps1
  5. Now go implement some awesome Sitecore solutions!

Setup and Configure the Manual Way

As an alternate to the above, you can pull the script from the GitHub repository and load it into Package Manager Console each time you need it with the following steps:

  1. Download from the GitHub repository to your local system in the manner that suits your workflow the best.
  2. Each time you wish to leverage the module in Visual Studio you will need to enter the following in the Package Manager Console
    Import-Module "C:\MyFiles\TheCodeAttic.Helix.PowerShellProjectCreator.psm1"

    Helix - Open Package Manager Console

Manual Process – Full Setup

OR you could download and configure the module manually (this is what ProjectCreatorEasyInstall.ps1 does for you.)

  1. Go to C:\Users\\Documents\WindowsPowerShell\Modules
  2. Create a new folder called “TheCodeAttic.Helix.PowerShellProjectCreator”
  3. Download the GitHub repository into the above directory
  4. Go up a level in the file system, should be at C:\Users\\Documents\WindowsPowerShell\
  5. Open (or create) NuGet_profile.ps1
  6. Add the following
    Import-Module TheCodeAttic.Helix.PowerShellProjectCreator
  7. Each time you run Visual Studio the module will be available to use in the Package Console Manager

Using Helix Project Creation

Create a new Helix Solution

  1. Open Visual Studio as Admin
  2. Open the Package Manager Console
    Helix - Open Package Manager Console
  3. Create a new Helix based solution by running Invoke-VisualStudioSolution
    Invoke-VisualStudioSolution -SolutionPath 'C:\Code\Coffeehouse.Demo.SXA'  -SolutionName 'Coffeehouse.Demo.SXA'

    Helix - Open Package Manager Console

Add a new module to a solution

  1. Open Visual Studio as Admin
  2. Open your Solution
  3. Open the Package Manager Console
  4. ‘Wake-up’ the $dte object by running
    $dte.Solution.FullName
    Helix - Wake-up $dte
  5. Add new module by running Invoke-NewModule
    Invoke-NewModule -ModuleName 'Coffeehouse.Demo.SXA.Coupon' -Layer 'Feature' -UseGlass -UseTDS

    Helix - Executing Invoke-NewModule

    Helix - Invoke-NewModule output

    Helix - Invoke-NewModule output, continued

  6. Go write some Sitecore code!!!!

Proof is in the pudding, they say

After running the Invoke-NewModule command your solution explorer should now look like the following:

Helix - New Module in Solution Explorer

And your file system will have the this:

Helix - New Module in File Explorer

References

The Sitecore Community members are always out to help each other, and some other Helix project creation solutions that may fit your work stream better are:

The Easier Way to Sitecore XP 9

This article was originally posted in its entirety on the Paragon Blog here: http://www.paragon-inc.com/blog/sitecore-9-install-the-easy-way.


You’ve either arrived because you made it through the full series or a quick google landed you here as you where looking for a quick and easy Sitecore XP 9 install.

Most of the following was taken from the Sitecore Installation Guide but is a little buried in all the documentation, so this will be a long term refernece for myself, my teams, and now you!

Prerequisites

The Steps

  1. Install MS SQL 2016 SP1 or later
  2. Install Web Deploy 3.6 for Hosting Servers (done via the Web Platform Installer)
  3. Install Url Rewrite 2.1 (done via the Web Platform Installer)
  4. Install Microsoft SQL Server Data-Tier Application Framework (DacFx) version 2016
  5. To support DacFx, the target SQL server needs to allow users and logins at the DB level, this can be configured/confirmed by running the following SQL script
    sp_configure 'contained database authentication', 1;
    GO
    RECONFIGURE;
    GO
  6. Extract the contents of Sitecore 9.0.1 rev. 171219 (WDP XP0 packages).zip to a working directory. You should see the following
    • Sitecore 9.0.1 rev. 171219 (OnPrem)_single.scwdp.zip
    • Sitecore 9.0.1 rev. 171219 (OnPrem)_zp0xconnect.scwdp.zip
    • XP0 Configuration Files 9.0.1 rev 171219.zip
  7. Extract the contents of XP0 Configuration Files 9.0.1 rev 171219.zip, and you should have the following JSON configuration files, this should be the same directory as the WDP packages in step 6:
    • sitecore-solr.json
    • sitecore-XP0.json
    • xconnect-createcert.json
    • xconnect-solr.json
    • xconnect-xp0.json

    At this point the working directory should look like this:
    Sitecore Easy Install - Working Directory

  8. Open a PowerShell Command prompt as Admin
  9. Change directory to your Working Directory as defined in step 7
  10. Download the install script from Sitecore Easy Install Gist by running the following
    (Invoke-WebRequest https://gist.githubusercontent.com/gillissm/1a3d826e6287e4cd106acea941748643/raw/c59dd9cef02d7e4adec1a90188d099948af43662/SitecoreEasyInstall.ps1).Content | Out-File "SitecoreEasyInstall.ps1"
  11. Open SitecoreEasyInstall.ps1 in your favorite editor (my recommendation is to open the entire working directory in Visual Studio Code).
  12. The first section of the file are global parameters that will define how your environment is configured and installed so update accordingly based on the instructions. At a minimum all values in the ‘CUSTOM TO THE ENVIRONMENT’ section should be completed.
    Sitecore Easy Install - Install Parameters
  13. From the PowerShell prompt run
    .\SitecoreEasyInstall.ps1
  14. Grab some coffee (or beer, I won’t judge) while it runs. (On my machine I was up and runninng in about 10 minutes.)
  15. Enjoy Sitecore Experience Platform 9!!!

 

Getting Ready for Security in Sitecore XP 9

Security in Sitecore 9 Experience Cloud

The next step towards installing Sitecore Experience Platform 9 is making sure we can easily handle the creation of locally signed certificates.

Background

Sitecore 9 by default is meant to run as a secure application. To help with managing these new security needs, the good (and smart) people at Sitecore have provided some PowerShell scripts to help. These scripts are found as part of the Sitecore Fundamentals module, which can be installed manually via a download from Sitecore, or through a custom MyGet Feed as shown here.

Sitecore Fundamentals Install

As I prefer to script for repeatability and ease of sharing with my dev team, this guide will be based on installing Sitecore Fundamentals via the MyGet feed approach.

Setup PowerShell to interact with the Sitecore MyGet feed

  1. Open a PowerShell command prompt, ensure you are running it as Admin
  2. Register the connection to MyGet feed, at the prompt enter (Note: if you have followed my SIF Install skip to step 3.)
    Register-PSRepository -Name SitecoreGallery -SourceLocation https://sitecore.myget.org/f/sc-powershell/api/v2

    Sitecore Fundamentals - Register Sitecore Gallery

  3. Install the Sitecore Fundamentals module, at the prompt enter
     Install-Module SitecoreFundamentals
  4. PowerShell will ask if untrusted scripts can be ran, enter ‘A’ and hit Enter. (Note: If you have already set this value during SIF Install won’t apply to you.)Sitecore Fundamentals - Accept Untrusted Scripts
  5. Before performing any other steps, and each time before you use the module, you will want to perform a check and update of the module via
     Update-Module SitecoreFundamentals
  6. Confirming everything installed correctly is as easy as running the following command, at time of writing the current version is 1.1.0
    Get-Module SitecoreFundamentals -ListAvailable

    Sitecore Fundamentals - Available Versions

You should now be ready leverage Sitecore Fundamentals as needed in maintaining and installing Sitecore.

Load Test from the Cloud

Building a any application, but especially high traffic websites on Sitecore one of the final steps before launch is to tune ensure any caching mechanisms have been properly tuned to support the needs of the organization.

One of the difficulties my teams always have is finding a server or two or three with enough available horse power to pound on out site. Running from a simple local machine is good enough for about 2 minutes until it begins heating the entire office.

But this headache and a more reasonably temperature office exists. How did we achieve this utopian level? Through the cloud of course…Visual Studio Team Services to be specific, by the way it’s free to register and take advantage of even.

Visual Studio Team Services provides a number of different tools and services, many for free such as GIT repos, CI, team and task management. One of the services provided is the ability to run scaled load testing from the cloud. Depending on your needs, you have the opportunity to run four types of tests from VSTS, Visual Studio Test, HTTP Archive Based Test, URL Based Test, Apache jMeter Test.

Load Test Options

Two things I found great about the service is, A) I get a decent number of free testing units (called Virtual User Minutes) to perform my testing, and B) I don’t have to purchase a high level MSDN or Visual Studio license. Why? Because it supports my tool of choice Apache’s jMeter.

As easy as 1, 2, 3

I can build and even pre-test my jMeter test scenarios on my local or internal hardware to confirm it generates the proper simulated traffic. After this is as easy as 1,2,3,4..and maybe a 5th step.

  1. Login to Visual Studio Online
  2. Click over to the Load Test screen
  3. Create a new test of type jmeter from the selector
  4. Upload the jmx file representing you developed jMeter scenario
    Load Test Options
  5. Upload your jmx file that defines your test run. Note, that the name of the file is the name the test will be referenced in the other screens.
  6. Set yout number of agents, length of run, and region the test should run from.
  7. Click Run
    Load Test Setup
  8. Smile and sip your coffee as the data pours into convenient charts and table.

Not Accessible to the World, yet?

If your site is sitting behind a firewall and only has internal DNS, with some additional setup you can still leverage the power of the cloud to perform your test, Testing private/intranet applications using Cloud-based load testing.

Testing Sitecore

For testing Sitecore load check-out this pre-started jMeter test provided by Sitecore themselves https://kb.sitecore.net/articles/398589. One thing to note if you would also like to test out or populate out xAnalytics data you will want to disable robots detection via the following patch config. Robots detection needs disabled as the tester does not trigger page events as required by xAnalytics for identifying a ‘human’ user. (Just be sure to turn it back on before site launch.)

<! --  ANALYTICS ROBOTS IGNORE ROBOTS    
    Ignore requests and do not write information to the Analytics 
        database when the visitor       
        classification identifies the visitor as a robot.   
    Default: true
 -- >
<setting name="Analytics.Robots.IgnoreRobots">
    <patch:attribute name="value">false</patch:attribute>
</setting>

If data still isn’t properly collecting you may also need to tweak the robot’s timeout value to allow the session to run longer.

<! --  ANALYTICS ROBOTS SESSION TIMEOUT 
        The ASP.NET Session Timeout for auto detected robots.
        When the automatic robot detection identifies a session as 
        being a robot, the ASP.NET Session Timeout 
        is set to this value (in minutes).  
    Default: 1  
-- >
<setting name="Analytics.Robots.SessionTimeout">
    <patch:attribute name="value">5</patch:attribute>
</setting>

Its that simple, and now there is no longer any reason to avoid even basic site load tests for Sitecore or any other application.

During my exploration of leveraging this cloud based load testing I found the following links to be informative:

Multilist with Search Secret Sauce

Discover the Multilist with Search Formula

I find myself wanting to leverage the Multilist with Search field often when architecting a site. The ability to provide the users multiple pages of information to pick from while having the ability to perform a wildcard search makes it an excellent option for assigning taxonomy to a page or item. As many the benefits are for the editor, the headaches trying to recall the syntax to setup the source is always a pain for me. I spend an hour or so digging through old code snippets, notes, and google looking for the right syntax formula.

But that is to be no more, as this post will be my notes for future setup and hopefully yours too.

The Setup

Let’s say we have a product taxonomy which is made up of a series of nested folders for organizational purposes and a product can be assigned one or more. If we are building out taxonomy assignments for some products for our Coffeeshop, we may have list of items in the content tree, such as

Product Category Taxonomy

Our product template will be fairly simple and contain the following fields

Product Template

The field we are focused on is Product Taxonomy and how to properly point it at our taxonomy list as we want to allow the editor to pick one or more categories.

Gut Instinct

Your initial gut instinct, or at least mine, is to begin wiring up Product Taxonomy with DataSource= to set the pick list like any of the other pick types, so our value would be

DataSource=/sitecore/content/GlobalSettingsAndData/ProductTaxonomy

Which ends up producing a list of everything. (If you try and get fancy and use the item ID you’ll end up with the same results.)
DataSource source

Start Search Location

The value we need to use is StartSearchLocation, which always points to a single item whose chidren and grand-children and great-*-grandchildren will be filterd and displayed. My gut feel would use a path like

StartSearchLocation=/sitecore/content/GlobalSettingsAndData/ProductTaxonomy

And this to sadly ends with a list of everything in the content tree. The natural progression of trial and error means to use the ID, so we have

StartSearchLocation={0A05923B-F8DA-4865-AE0A-D4288C70B0B6}

StartSearchLocation

Template Filter

Feeling a little better now, but it includes the sub-folders which have been setup that we want to not allow for selection. To limit what is available for selection we can apply a second parameter appended via an ampersand (‘&’) to the source value. The addition is TemplateFilter, which accepts a list of pipe delimited (‘|’) template IDs. In this sample we want all Basic Setting items (7F289750-AA0F-49DB-B479-F7D4646061DB) and CSS Class items (B28694DA-2FE5-478E-A64F-AA918BA53796)

StartSearchLocation={0A05923B-F8DA-4865-AE0A-D4288C70B0B6}&TemplateFilter={7F289750-AA0F-49DB-B479-F7D4646061DB}|{B28694DA-2FE5-478E-A64F-AA918BA53796}

Template Filter

Page Size

If for some reason the default page size of 20 items doesn’t fit your editor’s needs, then there is an additional parameter that can be added PageSize which will limit the number of items shown. In this sample we only want to show 3 items per page.

StartSearchLocation={0A05923B-F8DA-4865-AE0A-D4288C70B0B6}&TemplateFilter={7F289750-AA0F-49DB-B479-F7D4646061DB}|{B28694DA-2FE5-478E-A64F-AA918BA53796}&PageSize=3

PageSize

Filter

In instances when you need to provide a very finely tuned list of items to pick for the editor, you can use the Filter parameter which supports simple to very complex Lucene queries. When using the filter, you must include a plus or minus sign with the field indicating the appropriate inclusion (plus sign) or exclusion (minus sign) you wish to achieve. In this example we want to only show the taxonomy items that include the sub-string ‘caff’

StartSearchLocation={0A05923B-F8DA-4865-AE0A-D4288C70B0B6}&TemplateFilter={7F289750-AA0F-49DB-B479-F7D4646061DB}|{B28694DA-2FE5-478E-A64F-AA918BA53796}&Filter=+_name:*caff*

Filter with Lucene

Sitecore Query

Finally, for those who have really complex needs we can perform our filter via a traditional Sitecore query. Just by assigning it to the StartSearchLocation value. When using this method, note that you need to be sure to convert ‘=’ to ‘->’ to have them properly translated by the system. StartSearchLocation always needs to point to a single item of which the children will be selected and filtered for displaying.For this example, we only want the color items only, we could achieve this by filtering for specific items, or for the parent folder

StartSearchLocation=query:/sitecore/content/GlobalSettingsAndData/ProductTaxonomy/*/*[@@templatename->’CSSClass’]

Filter with a Sitecore Query

 

But wait there is some more

When working on building the perfect source for your field, and the field is always blank or you just keep getting the entire tree, be sure to check the log. Sitecore has provided some nice error logging to help you figure out what might need to be changed. These messages include

  • Content Editor – Multilist with search: Cannot find any item by query ‘{0}’ from the StartSearchLocation parameter. Location: ‘Source’ field of the ‘{1}’ field in the ‘{2}’ template
  • Content Editor – Multilist with search: Query ‘{0}’ from the StartSearchLocation parameter has incorrect format. Location: ‘Source’ field of the ‘{1}’ field in the ‘{2}’ template
  • Content Editor – Multilist with search: Cannot find any item by id ‘{0}’ from the StartSearchLocation parameter. Location: ‘Source’ field of the ‘{1}’ field in the ‘{2}’ template. ‘{3}’ will be used instead.
  • Content Editor – Multilist with search: Value ‘{0}’ from the StartSearchLocation parameter could not be treated as a valid GUID. Location: ‘Source’ field of the ‘{1}’ field in the ‘{2}’ template. ‘{3}’ will be used instead.

Finally, if you want to do some further exploring the full source to how the field parses the source into queries can be found with a little decompile magic of Sitecore.Buckets.dll, you’ll be looking for the SearchList class.

 

Cleaning up log messages for Geo IP Location

Starting with Sitecore 8.1 Geo IP lookup services come pre-installed and configured. All a site owner than need to do is log into the App Center and purchase the service. This is great from an implementer standpoint this is great as it’s one less configuration step that we have to take.

On the downside, if the site owners never purchase the lookup service the log will quickly clutter with ERROR messages.

ManagedPoolThread #12 16:01:15 ERROR Failed to perform GeoIp lookup for dd4795c0-1dca-ea8d-93c4-06d7f7aa5063
Exception: System.Net.WebException
Message: The remote name could not be resolved: ‘discovery-ces.cloud.sitecore.net’
Source: System
at System.Net.HttpWebRequest.GetResponse()
at Sitecore.CES.Client.WebClient.ExecuteRequest(String requestUri)
at Sitecore.CES.Client.ResourceConnector`1.Request(String endpoint, Object[] parameters)
at Sitecore.CES.Discovery.EndpointSource.GetEndpoint(String serviceName)
at Sitecore.CES.GeoIp.SitecoreProvider.GetInformationByIp(String ip)
at Sitecore.Analytics.Lookups.GeoIpManager.GetDataFromLookupProvider(GeoIpHandle geoIpHandle)

The Fix

The fix isn’t hard; all it requires is a simple patch config to disable the lookup service.

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
    <sitecore>
        <settings>
            <setting name="Analytics.PerformLookup">
                <patch:attribute name="value">false</patch:attribute>
            </setting>
        </settings>
    </sitecore>
</configuration>

For the full details on the lookup service checkout the full documentation at https://doc.sitecore.net/sitecore_experience_platform/setting_up__maintaining/ip_geolocation/setting_up_sitecore_ip_geolocation.